babylon.viewer.max.js 5.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865
  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. "use strict";
  109. var BABYLON;
  110. (function (BABYLON) {
  111. /**
  112. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  113. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  114. */
  115. var EffectFallbacks = /** @class */ (function () {
  116. function EffectFallbacks() {
  117. this._defines = {};
  118. this._currentRank = 32;
  119. this._maxRank = -1;
  120. }
  121. /**
  122. * Removes the fallback from the bound mesh.
  123. */
  124. EffectFallbacks.prototype.unBindMesh = function () {
  125. this._mesh = null;
  126. };
  127. /**
  128. * Adds a fallback on the specified property.
  129. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  130. * @param define The name of the define in the shader
  131. */
  132. EffectFallbacks.prototype.addFallback = function (rank, define) {
  133. if (!this._defines[rank]) {
  134. if (rank < this._currentRank) {
  135. this._currentRank = rank;
  136. }
  137. if (rank > this._maxRank) {
  138. this._maxRank = rank;
  139. }
  140. this._defines[rank] = new Array();
  141. }
  142. this._defines[rank].push(define);
  143. };
  144. /**
  145. * Sets the mesh to use CPU skinning when needing to fallback.
  146. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  147. * @param mesh The mesh to use the fallbacks.
  148. */
  149. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  150. this._mesh = mesh;
  151. if (rank < this._currentRank) {
  152. this._currentRank = rank;
  153. }
  154. if (rank > this._maxRank) {
  155. this._maxRank = rank;
  156. }
  157. };
  158. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  159. /**
  160. * Checks to see if more fallbacks are still availible.
  161. */
  162. get: function () {
  163. return this._currentRank <= this._maxRank;
  164. },
  165. enumerable: true,
  166. configurable: true
  167. });
  168. /**
  169. * Removes the defines that shoould be removed when falling back.
  170. * @param currentDefines defines the current define statements for the shader.
  171. * @param effect defines the current effect we try to compile
  172. * @returns The resulting defines with defines of the current rank removed.
  173. */
  174. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  175. // First we try to switch to CPU skinning
  176. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  177. this._mesh.computeBonesUsingShaders = false;
  178. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  179. var scene = this._mesh.getScene();
  180. for (var index = 0; index < scene.meshes.length; index++) {
  181. var otherMesh = scene.meshes[index];
  182. if (!otherMesh.material) {
  183. continue;
  184. }
  185. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  186. continue;
  187. }
  188. if (otherMesh.material.getEffect() === effect) {
  189. otherMesh.computeBonesUsingShaders = false;
  190. }
  191. else {
  192. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  193. var subMesh = _a[_i];
  194. var subMeshEffect = subMesh.effect;
  195. if (subMeshEffect === effect) {
  196. otherMesh.computeBonesUsingShaders = false;
  197. break;
  198. }
  199. }
  200. }
  201. }
  202. }
  203. else {
  204. var currentFallbacks = this._defines[this._currentRank];
  205. if (currentFallbacks) {
  206. for (var index = 0; index < currentFallbacks.length; index++) {
  207. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  208. }
  209. }
  210. this._currentRank++;
  211. }
  212. return currentDefines;
  213. };
  214. return EffectFallbacks;
  215. }());
  216. BABYLON.EffectFallbacks = EffectFallbacks;
  217. /**
  218. * Options to be used when creating an effect.
  219. */
  220. var EffectCreationOptions = /** @class */ (function () {
  221. function EffectCreationOptions() {
  222. }
  223. return EffectCreationOptions;
  224. }());
  225. BABYLON.EffectCreationOptions = EffectCreationOptions;
  226. /**
  227. * Effect containing vertex and fragment shader that can be executed on an object.
  228. */
  229. var Effect = /** @class */ (function () {
  230. /**
  231. * Instantiates an effect.
  232. * An effect can be used to create/manage/execute vertex and fragment shaders.
  233. * @param baseName Name of the effect.
  234. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  235. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  236. * @param samplers List of sampler variables that will be passed to the shader.
  237. * @param engine Engine to be used to render the effect
  238. * @param defines Define statements to be added to the shader.
  239. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  240. * @param onCompiled Callback that will be called when the shader is compiled.
  241. * @param onError Callback that will be called if an error occurs during shader compilation.
  242. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  243. */
  244. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  245. if (samplers === void 0) { samplers = null; }
  246. if (defines === void 0) { defines = null; }
  247. if (fallbacks === void 0) { fallbacks = null; }
  248. if (onCompiled === void 0) { onCompiled = null; }
  249. if (onError === void 0) { onError = null; }
  250. var _this = this;
  251. /**
  252. * Unique ID of the effect.
  253. */
  254. this.uniqueId = 0;
  255. /**
  256. * Observable that will be called when the shader is compiled.
  257. */
  258. this.onCompileObservable = new BABYLON.Observable();
  259. /**
  260. * Observable that will be called if an error occurs during shader compilation.
  261. */
  262. this.onErrorObservable = new BABYLON.Observable();
  263. /**
  264. * Observable that will be called when effect is bound.
  265. */
  266. this.onBindObservable = new BABYLON.Observable();
  267. this._uniformBuffersNames = {};
  268. this._isReady = false;
  269. this._compilationError = "";
  270. this.name = baseName;
  271. if (attributesNamesOrOptions.attributes) {
  272. var options = attributesNamesOrOptions;
  273. this._engine = uniformsNamesOrEngine;
  274. this._attributesNames = options.attributes;
  275. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  276. this._samplers = options.samplers;
  277. this.defines = options.defines;
  278. this.onError = options.onError;
  279. this.onCompiled = options.onCompiled;
  280. this._fallbacks = options.fallbacks;
  281. this._indexParameters = options.indexParameters;
  282. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  283. if (options.uniformBuffersNames) {
  284. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  285. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  286. }
  287. }
  288. }
  289. else {
  290. this._engine = engine;
  291. this.defines = defines;
  292. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  293. this._samplers = samplers;
  294. this._attributesNames = attributesNamesOrOptions;
  295. this.onError = onError;
  296. this.onCompiled = onCompiled;
  297. this._indexParameters = indexParameters;
  298. this._fallbacks = fallbacks;
  299. }
  300. this.uniqueId = Effect._uniqueIdSeed++;
  301. if (this._getFromCache(baseName)) {
  302. this._prepareEffect();
  303. return;
  304. }
  305. var vertexSource;
  306. var fragmentSource;
  307. if (baseName.vertexElement) {
  308. vertexSource = document.getElementById(baseName.vertexElement);
  309. if (!vertexSource) {
  310. vertexSource = baseName.vertexElement;
  311. }
  312. }
  313. else {
  314. vertexSource = baseName.vertex || baseName;
  315. }
  316. if (baseName.fragmentElement) {
  317. fragmentSource = document.getElementById(baseName.fragmentElement);
  318. if (!fragmentSource) {
  319. fragmentSource = baseName.fragmentElement;
  320. }
  321. }
  322. else {
  323. fragmentSource = baseName.fragment || baseName;
  324. }
  325. var finalVertexCode;
  326. this._loadVertexShaderAsync(vertexSource)
  327. .then(function (vertexCode) {
  328. return _this._processIncludesAsync(vertexCode);
  329. })
  330. .then(function (vertexCodeWithIncludes) {
  331. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  332. return _this._loadFragmentShaderAsync(fragmentSource);
  333. })
  334. .then(function (fragmentCode) {
  335. return _this._processIncludesAsync(fragmentCode);
  336. })
  337. .then(function (fragmentCodeWithIncludes) {
  338. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  339. if (baseName) {
  340. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  341. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  342. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  343. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  344. }
  345. else {
  346. _this._vertexSourceCode = finalVertexCode;
  347. _this._fragmentSourceCode = migratedFragmentCode;
  348. }
  349. _this._setInCache(baseName);
  350. _this._prepareEffect();
  351. });
  352. }
  353. Effect.prototype._getSourceCacheKey = function (baseName) {
  354. var cacheKey = baseName;
  355. if (this._indexParameters) {
  356. for (var key in this._indexParameters) {
  357. if (this._indexParameters.hasOwnProperty(key)) {
  358. cacheKey += "|";
  359. cacheKey += key;
  360. cacheKey += "_";
  361. cacheKey += this._indexParameters[key];
  362. }
  363. }
  364. }
  365. return cacheKey;
  366. };
  367. Effect.prototype._getFromCache = function (baseName) {
  368. if (typeof baseName !== "string") {
  369. return false;
  370. }
  371. var cacheKey = this._getSourceCacheKey(baseName);
  372. var sources = Effect._sourceCache[cacheKey];
  373. if (!sources) {
  374. return false;
  375. }
  376. this._vertexSourceCode = sources.vertex;
  377. this._fragmentSourceCode = sources.fragment;
  378. return true;
  379. };
  380. Effect.prototype._setInCache = function (baseName) {
  381. if (typeof baseName !== "string") {
  382. return;
  383. }
  384. var cacheKey = this._getSourceCacheKey(baseName);
  385. Effect._sourceCache[cacheKey] = {
  386. vertex: this._vertexSourceCode,
  387. fragment: this._fragmentSourceCode
  388. };
  389. };
  390. Object.defineProperty(Effect.prototype, "key", {
  391. /**
  392. * Unique key for this effect
  393. */
  394. get: function () {
  395. return this._key;
  396. },
  397. enumerable: true,
  398. configurable: true
  399. });
  400. /**
  401. * If the effect has been compiled and prepared.
  402. * @returns if the effect is compiled and prepared.
  403. */
  404. Effect.prototype.isReady = function () {
  405. return this._isReady;
  406. };
  407. /**
  408. * The engine the effect was initialized with.
  409. * @returns the engine.
  410. */
  411. Effect.prototype.getEngine = function () {
  412. return this._engine;
  413. };
  414. /**
  415. * The compiled webGL program for the effect
  416. * @returns the webGL program.
  417. */
  418. Effect.prototype.getProgram = function () {
  419. return this._program;
  420. };
  421. /**
  422. * The set of names of attribute variables for the shader.
  423. * @returns An array of attribute names.
  424. */
  425. Effect.prototype.getAttributesNames = function () {
  426. return this._attributesNames;
  427. };
  428. /**
  429. * Returns the attribute at the given index.
  430. * @param index The index of the attribute.
  431. * @returns The location of the attribute.
  432. */
  433. Effect.prototype.getAttributeLocation = function (index) {
  434. return this._attributes[index];
  435. };
  436. /**
  437. * Returns the attribute based on the name of the variable.
  438. * @param name of the attribute to look up.
  439. * @returns the attribute location.
  440. */
  441. Effect.prototype.getAttributeLocationByName = function (name) {
  442. var index = this._attributesNames.indexOf(name);
  443. return this._attributes[index];
  444. };
  445. /**
  446. * The number of attributes.
  447. * @returns the numnber of attributes.
  448. */
  449. Effect.prototype.getAttributesCount = function () {
  450. return this._attributes.length;
  451. };
  452. /**
  453. * Gets the index of a uniform variable.
  454. * @param uniformName of the uniform to look up.
  455. * @returns the index.
  456. */
  457. Effect.prototype.getUniformIndex = function (uniformName) {
  458. return this._uniformsNames.indexOf(uniformName);
  459. };
  460. /**
  461. * Returns the attribute based on the name of the variable.
  462. * @param uniformName of the uniform to look up.
  463. * @returns the location of the uniform.
  464. */
  465. Effect.prototype.getUniform = function (uniformName) {
  466. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  467. };
  468. /**
  469. * Returns an array of sampler variable names
  470. * @returns The array of sampler variable neames.
  471. */
  472. Effect.prototype.getSamplers = function () {
  473. return this._samplers;
  474. };
  475. /**
  476. * The error from the last compilation.
  477. * @returns the error string.
  478. */
  479. Effect.prototype.getCompilationError = function () {
  480. return this._compilationError;
  481. };
  482. /**
  483. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  484. * @param func The callback to be used.
  485. */
  486. Effect.prototype.executeWhenCompiled = function (func) {
  487. if (this.isReady()) {
  488. func(this);
  489. return;
  490. }
  491. this.onCompileObservable.add(function (effect) {
  492. func(effect);
  493. });
  494. };
  495. /** @ignore */
  496. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  497. if (BABYLON.Tools.IsWindowObjectExist()) {
  498. // DOM element ?
  499. if (vertex instanceof HTMLElement) {
  500. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  501. return Promise.resolve(vertexCode);
  502. }
  503. }
  504. // Base64 encoded ?
  505. if (vertex.substr(0, 7) === "base64:") {
  506. var vertexBinary = window.atob(vertex.substr(7));
  507. return Promise.resolve(vertexBinary);
  508. }
  509. // Is in local store ?
  510. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  511. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  512. }
  513. var vertexShaderUrl;
  514. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  515. vertexShaderUrl = vertex;
  516. }
  517. else {
  518. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  519. }
  520. // Vertex shader
  521. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  522. };
  523. /** @ignore */
  524. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  525. if (BABYLON.Tools.IsWindowObjectExist()) {
  526. // DOM element ?
  527. if (fragment instanceof HTMLElement) {
  528. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  529. return Promise.resolve(fragmentCode);
  530. }
  531. }
  532. // Base64 encoded ?
  533. if (fragment.substr(0, 7) === "base64:") {
  534. var fragmentBinary = window.atob(fragment.substr(7));
  535. return Promise.resolve(fragmentBinary);
  536. }
  537. // Is in local store ?
  538. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  539. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  540. }
  541. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  542. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  543. }
  544. var fragmentShaderUrl;
  545. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  546. fragmentShaderUrl = fragment;
  547. }
  548. else {
  549. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  550. }
  551. // Fragment shader
  552. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  553. };
  554. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  555. // Rebuild shaders source code
  556. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  557. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  558. vertexCode = prefix + vertexCode;
  559. fragmentCode = prefix + fragmentCode;
  560. // Number lines of shaders source code
  561. var i = 2;
  562. var regex = /\n/gm;
  563. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  564. i = 2;
  565. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  566. // Dump shaders name and formatted source code
  567. if (this.name.vertexElement) {
  568. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  569. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  570. }
  571. else if (this.name.vertex) {
  572. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  573. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  574. }
  575. else {
  576. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  577. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  578. }
  579. };
  580. ;
  581. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  582. var preparedSourceCode = this._processPrecision(sourceCode);
  583. if (this._engine.webGLVersion == 1) {
  584. return preparedSourceCode;
  585. }
  586. // Already converted
  587. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  588. return preparedSourceCode.replace("#version 300 es", "");
  589. }
  590. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  591. // Remove extensions
  592. // #extension GL_OES_standard_derivatives : enable
  593. // #extension GL_EXT_shader_texture_lod : enable
  594. // #extension GL_EXT_frag_depth : enable
  595. // #extension GL_EXT_draw_buffers : require
  596. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  597. var result = preparedSourceCode.replace(regex, "");
  598. // Migrate to GLSL v300
  599. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  600. result = result.replace(/attribute[ \t]/g, "in ");
  601. result = result.replace(/[ \t]attribute/g, " in");
  602. if (isFragment) {
  603. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  604. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  605. result = result.replace(/texture2D\s*\(/g, "texture(");
  606. result = result.replace(/textureCube\s*\(/g, "texture(");
  607. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  608. result = result.replace(/gl_FragColor/g, "glFragColor");
  609. result = result.replace(/gl_FragData/g, "glFragData");
  610. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  611. }
  612. return result;
  613. };
  614. Effect.prototype._processIncludesAsync = function (sourceCode) {
  615. var _this = this;
  616. return new Promise(function (resolve, reject) {
  617. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  618. var match = regex.exec(sourceCode);
  619. var returnValue = sourceCode;
  620. while (match != null) {
  621. var includeFile = match[1];
  622. // Uniform declaration
  623. if (includeFile.indexOf("__decl__") !== -1) {
  624. includeFile = includeFile.replace(/__decl__/, "");
  625. if (_this._engine.supportsUniformBuffers) {
  626. includeFile = includeFile.replace(/Vertex/, "Ubo");
  627. includeFile = includeFile.replace(/Fragment/, "Ubo");
  628. }
  629. includeFile = includeFile + "Declaration";
  630. }
  631. if (Effect.IncludesShadersStore[includeFile]) {
  632. // Substitution
  633. var includeContent = Effect.IncludesShadersStore[includeFile];
  634. if (match[2]) {
  635. var splits = match[3].split(",");
  636. for (var index = 0; index < splits.length; index += 2) {
  637. var source = new RegExp(splits[index], "g");
  638. var dest = splits[index + 1];
  639. includeContent = includeContent.replace(source, dest);
  640. }
  641. }
  642. if (match[4]) {
  643. var indexString = match[5];
  644. if (indexString.indexOf("..") !== -1) {
  645. var indexSplits = indexString.split("..");
  646. var minIndex = parseInt(indexSplits[0]);
  647. var maxIndex = parseInt(indexSplits[1]);
  648. var sourceIncludeContent = includeContent.slice(0);
  649. includeContent = "";
  650. if (isNaN(maxIndex)) {
  651. maxIndex = _this._indexParameters[indexSplits[1]];
  652. }
  653. for (var i = minIndex; i < maxIndex; i++) {
  654. if (!_this._engine.supportsUniformBuffers) {
  655. // Ubo replacement
  656. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  657. return p1 + "{X}";
  658. });
  659. }
  660. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  661. }
  662. }
  663. else {
  664. if (!_this._engine.supportsUniformBuffers) {
  665. // Ubo replacement
  666. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  667. return p1 + "{X}";
  668. });
  669. }
  670. includeContent = includeContent.replace(/\{X\}/g, indexString);
  671. }
  672. }
  673. // Replace
  674. returnValue = returnValue.replace(match[0], includeContent);
  675. }
  676. else {
  677. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  678. _this._engine._loadFileAsync(includeShaderUrl)
  679. .then(function (fileContent) {
  680. Effect.IncludesShadersStore[includeFile] = fileContent;
  681. return _this._processIncludesAsync(returnValue);
  682. })
  683. .then(function (returnValue) {
  684. resolve(returnValue);
  685. });
  686. return;
  687. }
  688. match = regex.exec(sourceCode);
  689. }
  690. resolve(returnValue);
  691. });
  692. };
  693. Effect.prototype._processPrecision = function (source) {
  694. if (source.indexOf("precision highp float") === -1) {
  695. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  696. source = "precision mediump float;\n" + source;
  697. }
  698. else {
  699. source = "precision highp float;\n" + source;
  700. }
  701. }
  702. else {
  703. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  704. source = source.replace("precision highp float", "precision mediump float");
  705. }
  706. }
  707. return source;
  708. };
  709. /**
  710. * Recompiles the webGL program
  711. * @param vertexSourceCode The source code for the vertex shader.
  712. * @param fragmentSourceCode The source code for the fragment shader.
  713. * @param onCompiled Callback called when completed.
  714. * @param onError Callback called on error.
  715. */
  716. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  717. var _this = this;
  718. this._isReady = false;
  719. this._vertexSourceCodeOverride = vertexSourceCode;
  720. this._fragmentSourceCodeOverride = fragmentSourceCode;
  721. this.onError = function (effect, error) {
  722. if (onError) {
  723. onError(error);
  724. }
  725. };
  726. this.onCompiled = function () {
  727. var scenes = _this.getEngine().scenes;
  728. for (var i = 0; i < scenes.length; i++) {
  729. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  730. }
  731. if (onCompiled) {
  732. onCompiled(_this._program);
  733. }
  734. };
  735. this._fallbacks = null;
  736. this._prepareEffect();
  737. };
  738. /**
  739. * Gets the uniform locations of the the specified variable names
  740. * @param names THe names of the variables to lookup.
  741. * @returns Array of locations in the same order as variable names.
  742. */
  743. Effect.prototype.getSpecificUniformLocations = function (names) {
  744. var engine = this._engine;
  745. return engine.getUniforms(this._program, names);
  746. };
  747. /**
  748. * Prepares the effect
  749. */
  750. Effect.prototype._prepareEffect = function () {
  751. var attributesNames = this._attributesNames;
  752. var defines = this.defines;
  753. var fallbacks = this._fallbacks;
  754. this._valueCache = {};
  755. var previousProgram = this._program;
  756. try {
  757. var engine = this._engine;
  758. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  759. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  760. }
  761. else {
  762. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  763. }
  764. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  765. if (engine.supportsUniformBuffers) {
  766. for (var name in this._uniformBuffersNames) {
  767. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  768. }
  769. }
  770. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  771. this._attributes = engine.getAttributes(this._program, attributesNames);
  772. var index;
  773. for (index = 0; index < this._samplers.length; index++) {
  774. var sampler = this.getUniform(this._samplers[index]);
  775. if (sampler == null) {
  776. this._samplers.splice(index, 1);
  777. index--;
  778. }
  779. }
  780. engine.bindSamplers(this);
  781. this._compilationError = "";
  782. this._isReady = true;
  783. if (this.onCompiled) {
  784. this.onCompiled(this);
  785. }
  786. this.onCompileObservable.notifyObservers(this);
  787. this.onCompileObservable.clear();
  788. // Unbind mesh reference in fallbacks
  789. if (this._fallbacks) {
  790. this._fallbacks.unBindMesh();
  791. }
  792. if (previousProgram) {
  793. this.getEngine()._deleteProgram(previousProgram);
  794. }
  795. }
  796. catch (e) {
  797. this._compilationError = e.message;
  798. // Let's go through fallbacks then
  799. BABYLON.Tools.Error("Unable to compile effect:");
  800. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  801. return " " + uniform;
  802. }));
  803. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  804. return " " + attribute;
  805. }));
  806. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  807. BABYLON.Tools.Error("Error: " + this._compilationError);
  808. if (previousProgram) {
  809. this._program = previousProgram;
  810. this._isReady = true;
  811. if (this.onError) {
  812. this.onError(this, this._compilationError);
  813. }
  814. this.onErrorObservable.notifyObservers(this);
  815. }
  816. if (fallbacks && fallbacks.isMoreFallbacks) {
  817. BABYLON.Tools.Error("Trying next fallback.");
  818. this.defines = fallbacks.reduce(this.defines, this);
  819. this._prepareEffect();
  820. }
  821. else {
  822. if (this.onError) {
  823. this.onError(this, this._compilationError);
  824. }
  825. this.onErrorObservable.notifyObservers(this);
  826. this.onErrorObservable.clear();
  827. // Unbind mesh reference in fallbacks
  828. if (this._fallbacks) {
  829. this._fallbacks.unBindMesh();
  830. }
  831. }
  832. }
  833. };
  834. Object.defineProperty(Effect.prototype, "isSupported", {
  835. /**
  836. * Checks if the effect is supported. (Must be called after compilation)
  837. */
  838. get: function () {
  839. return this._compilationError === "";
  840. },
  841. enumerable: true,
  842. configurable: true
  843. });
  844. /**
  845. * Binds a texture to the engine to be used as output of the shader.
  846. * @param channel Name of the output variable.
  847. * @param texture Texture to bind.
  848. */
  849. Effect.prototype._bindTexture = function (channel, texture) {
  850. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  851. };
  852. /**
  853. * Sets a texture on the engine to be used in the shader.
  854. * @param channel Name of the sampler variable.
  855. * @param texture Texture to set.
  856. */
  857. Effect.prototype.setTexture = function (channel, texture) {
  858. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  859. };
  860. /**
  861. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  862. * @param channel Name of the sampler variable.
  863. * @param texture Texture to set.
  864. */
  865. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  866. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  867. };
  868. /**
  869. * Sets an array of textures on the engine to be used in the shader.
  870. * @param channel Name of the variable.
  871. * @param textures Textures to set.
  872. */
  873. Effect.prototype.setTextureArray = function (channel, textures) {
  874. if (this._samplers.indexOf(channel + "Ex") === -1) {
  875. var initialPos = this._samplers.indexOf(channel);
  876. for (var index = 1; index < textures.length; index++) {
  877. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  878. }
  879. }
  880. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  881. };
  882. /**
  883. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  884. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  885. * @param channel Name of the sampler variable.
  886. * @param postProcess Post process to get the input texture from.
  887. */
  888. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  889. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  890. };
  891. /**
  892. * Sets the output texture of the passed in post process to be input of this effect.
  893. * @param channel Name of the sampler variable.
  894. * @param postProcess Post process to get the output texture from.
  895. */
  896. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  897. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  898. };
  899. /** @ignore */
  900. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  901. var cache = this._valueCache[uniformName];
  902. var flag = matrix.updateFlag;
  903. if (cache !== undefined && cache === flag) {
  904. return false;
  905. }
  906. this._valueCache[uniformName] = flag;
  907. return true;
  908. };
  909. /** @ignore */
  910. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  911. var cache = this._valueCache[uniformName];
  912. if (!cache) {
  913. cache = [x, y];
  914. this._valueCache[uniformName] = cache;
  915. return true;
  916. }
  917. var changed = false;
  918. if (cache[0] !== x) {
  919. cache[0] = x;
  920. changed = true;
  921. }
  922. if (cache[1] !== y) {
  923. cache[1] = y;
  924. changed = true;
  925. }
  926. return changed;
  927. };
  928. /** @ignore */
  929. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  930. var cache = this._valueCache[uniformName];
  931. if (!cache) {
  932. cache = [x, y, z];
  933. this._valueCache[uniformName] = cache;
  934. return true;
  935. }
  936. var changed = false;
  937. if (cache[0] !== x) {
  938. cache[0] = x;
  939. changed = true;
  940. }
  941. if (cache[1] !== y) {
  942. cache[1] = y;
  943. changed = true;
  944. }
  945. if (cache[2] !== z) {
  946. cache[2] = z;
  947. changed = true;
  948. }
  949. return changed;
  950. };
  951. /** @ignore */
  952. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  953. var cache = this._valueCache[uniformName];
  954. if (!cache) {
  955. cache = [x, y, z, w];
  956. this._valueCache[uniformName] = cache;
  957. return true;
  958. }
  959. var changed = false;
  960. if (cache[0] !== x) {
  961. cache[0] = x;
  962. changed = true;
  963. }
  964. if (cache[1] !== y) {
  965. cache[1] = y;
  966. changed = true;
  967. }
  968. if (cache[2] !== z) {
  969. cache[2] = z;
  970. changed = true;
  971. }
  972. if (cache[3] !== w) {
  973. cache[3] = w;
  974. changed = true;
  975. }
  976. return changed;
  977. };
  978. /**
  979. * Binds a buffer to a uniform.
  980. * @param buffer Buffer to bind.
  981. * @param name Name of the uniform variable to bind to.
  982. */
  983. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  984. var bufferName = this._uniformBuffersNames[name];
  985. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  986. return;
  987. }
  988. Effect._baseCache[bufferName] = buffer;
  989. this._engine.bindUniformBufferBase(buffer, bufferName);
  990. };
  991. /**
  992. * Binds block to a uniform.
  993. * @param blockName Name of the block to bind.
  994. * @param index Index to bind.
  995. */
  996. Effect.prototype.bindUniformBlock = function (blockName, index) {
  997. this._engine.bindUniformBlock(this._program, blockName, index);
  998. };
  999. /**
  1000. * Sets an interger value on a uniform variable.
  1001. * @param uniformName Name of the variable.
  1002. * @param value Value to be set.
  1003. * @returns this effect.
  1004. */
  1005. Effect.prototype.setInt = function (uniformName, value) {
  1006. var cache = this._valueCache[uniformName];
  1007. if (cache !== undefined && cache === value)
  1008. return this;
  1009. this._valueCache[uniformName] = value;
  1010. this._engine.setInt(this.getUniform(uniformName), value);
  1011. return this;
  1012. };
  1013. /**
  1014. * Sets an int array on a uniform variable.
  1015. * @param uniformName Name of the variable.
  1016. * @param array array to be set.
  1017. * @returns this effect.
  1018. */
  1019. Effect.prototype.setIntArray = function (uniformName, array) {
  1020. this._valueCache[uniformName] = null;
  1021. this._engine.setIntArray(this.getUniform(uniformName), array);
  1022. return this;
  1023. };
  1024. /**
  1025. * 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)
  1026. * @param uniformName Name of the variable.
  1027. * @param array array to be set.
  1028. * @returns this effect.
  1029. */
  1030. Effect.prototype.setIntArray2 = function (uniformName, array) {
  1031. this._valueCache[uniformName] = null;
  1032. this._engine.setIntArray2(this.getUniform(uniformName), array);
  1033. return this;
  1034. };
  1035. /**
  1036. * 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)
  1037. * @param uniformName Name of the variable.
  1038. * @param array array to be set.
  1039. * @returns this effect.
  1040. */
  1041. Effect.prototype.setIntArray3 = function (uniformName, array) {
  1042. this._valueCache[uniformName] = null;
  1043. this._engine.setIntArray3(this.getUniform(uniformName), array);
  1044. return this;
  1045. };
  1046. /**
  1047. * 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)
  1048. * @param uniformName Name of the variable.
  1049. * @param array array to be set.
  1050. * @returns this effect.
  1051. */
  1052. Effect.prototype.setIntArray4 = function (uniformName, array) {
  1053. this._valueCache[uniformName] = null;
  1054. this._engine.setIntArray4(this.getUniform(uniformName), array);
  1055. return this;
  1056. };
  1057. /**
  1058. * Sets an float array on a uniform variable.
  1059. * @param uniformName Name of the variable.
  1060. * @param array array to be set.
  1061. * @returns this effect.
  1062. */
  1063. Effect.prototype.setFloatArray = function (uniformName, array) {
  1064. this._valueCache[uniformName] = null;
  1065. this._engine.setFloatArray(this.getUniform(uniformName), array);
  1066. return this;
  1067. };
  1068. /**
  1069. * 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)
  1070. * @param uniformName Name of the variable.
  1071. * @param array array to be set.
  1072. * @returns this effect.
  1073. */
  1074. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  1075. this._valueCache[uniformName] = null;
  1076. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  1077. return this;
  1078. };
  1079. /**
  1080. * 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)
  1081. * @param uniformName Name of the variable.
  1082. * @param array array to be set.
  1083. * @returns this effect.
  1084. */
  1085. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  1086. this._valueCache[uniformName] = null;
  1087. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  1088. return this;
  1089. };
  1090. /**
  1091. * 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)
  1092. * @param uniformName Name of the variable.
  1093. * @param array array to be set.
  1094. * @returns this effect.
  1095. */
  1096. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  1097. this._valueCache[uniformName] = null;
  1098. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1099. return this;
  1100. };
  1101. /**
  1102. * Sets an array on a uniform variable.
  1103. * @param uniformName Name of the variable.
  1104. * @param array array to be set.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setArray = function (uniformName, array) {
  1108. this._valueCache[uniformName] = null;
  1109. this._engine.setArray(this.getUniform(uniformName), array);
  1110. return this;
  1111. };
  1112. /**
  1113. * 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)
  1114. * @param uniformName Name of the variable.
  1115. * @param array array to be set.
  1116. * @returns this effect.
  1117. */
  1118. Effect.prototype.setArray2 = function (uniformName, array) {
  1119. this._valueCache[uniformName] = null;
  1120. this._engine.setArray2(this.getUniform(uniformName), array);
  1121. return this;
  1122. };
  1123. /**
  1124. * 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)
  1125. * @param uniformName Name of the variable.
  1126. * @param array array to be set.
  1127. * @returns this effect.
  1128. */
  1129. Effect.prototype.setArray3 = function (uniformName, array) {
  1130. this._valueCache[uniformName] = null;
  1131. this._engine.setArray3(this.getUniform(uniformName), array);
  1132. return this;
  1133. };
  1134. /**
  1135. * 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)
  1136. * @param uniformName Name of the variable.
  1137. * @param array array to be set.
  1138. * @returns this effect.
  1139. */
  1140. Effect.prototype.setArray4 = function (uniformName, array) {
  1141. this._valueCache[uniformName] = null;
  1142. this._engine.setArray4(this.getUniform(uniformName), array);
  1143. return this;
  1144. };
  1145. /**
  1146. * Sets matrices on a uniform variable.
  1147. * @param uniformName Name of the variable.
  1148. * @param matrices matrices to be set.
  1149. * @returns this effect.
  1150. */
  1151. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1152. if (!matrices) {
  1153. return this;
  1154. }
  1155. this._valueCache[uniformName] = null;
  1156. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1157. return this;
  1158. };
  1159. /**
  1160. * Sets matrix on a uniform variable.
  1161. * @param uniformName Name of the variable.
  1162. * @param matrix matrix to be set.
  1163. * @returns this effect.
  1164. */
  1165. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1166. if (this._cacheMatrix(uniformName, matrix)) {
  1167. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1168. }
  1169. return this;
  1170. };
  1171. /**
  1172. * 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)
  1173. * @param uniformName Name of the variable.
  1174. * @param matrix matrix to be set.
  1175. * @returns this effect.
  1176. */
  1177. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1178. this._valueCache[uniformName] = null;
  1179. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1180. return this;
  1181. };
  1182. /**
  1183. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1184. * @param uniformName Name of the variable.
  1185. * @param matrix matrix to be set.
  1186. * @returns this effect.
  1187. */
  1188. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1189. this._valueCache[uniformName] = null;
  1190. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1191. return this;
  1192. };
  1193. /**
  1194. * Sets a float on a uniform variable.
  1195. * @param uniformName Name of the variable.
  1196. * @param value value to be set.
  1197. * @returns this effect.
  1198. */
  1199. Effect.prototype.setFloat = function (uniformName, value) {
  1200. var cache = this._valueCache[uniformName];
  1201. if (cache !== undefined && cache === value)
  1202. return this;
  1203. this._valueCache[uniformName] = value;
  1204. this._engine.setFloat(this.getUniform(uniformName), value);
  1205. return this;
  1206. };
  1207. /**
  1208. * Sets a boolean on a uniform variable.
  1209. * @param uniformName Name of the variable.
  1210. * @param bool value to be set.
  1211. * @returns this effect.
  1212. */
  1213. Effect.prototype.setBool = function (uniformName, bool) {
  1214. var cache = this._valueCache[uniformName];
  1215. if (cache !== undefined && cache === bool)
  1216. return this;
  1217. this._valueCache[uniformName] = bool;
  1218. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1219. return this;
  1220. };
  1221. /**
  1222. * Sets a Vector2 on a uniform variable.
  1223. * @param uniformName Name of the variable.
  1224. * @param vector2 vector2 to be set.
  1225. * @returns this effect.
  1226. */
  1227. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1228. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1229. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1230. }
  1231. return this;
  1232. };
  1233. /**
  1234. * Sets a float2 on a uniform variable.
  1235. * @param uniformName Name of the variable.
  1236. * @param x First float in float2.
  1237. * @param y Second float in float2.
  1238. * @returns this effect.
  1239. */
  1240. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1241. if (this._cacheFloat2(uniformName, x, y)) {
  1242. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1243. }
  1244. return this;
  1245. };
  1246. /**
  1247. * Sets a Vector3 on a uniform variable.
  1248. * @param uniformName Name of the variable.
  1249. * @param vector3 Value to be set.
  1250. * @returns this effect.
  1251. */
  1252. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1253. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1254. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1255. }
  1256. return this;
  1257. };
  1258. /**
  1259. * Sets a float3 on a uniform variable.
  1260. * @param uniformName Name of the variable.
  1261. * @param x First float in float3.
  1262. * @param y Second float in float3.
  1263. * @param z Third float in float3.
  1264. * @returns this effect.
  1265. */
  1266. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1267. if (this._cacheFloat3(uniformName, x, y, z)) {
  1268. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1269. }
  1270. return this;
  1271. };
  1272. /**
  1273. * Sets a Vector4 on a uniform variable.
  1274. * @param uniformName Name of the variable.
  1275. * @param vector4 Value to be set.
  1276. * @returns this effect.
  1277. */
  1278. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1279. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1280. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1281. }
  1282. return this;
  1283. };
  1284. /**
  1285. * Sets a float4 on a uniform variable.
  1286. * @param uniformName Name of the variable.
  1287. * @param x First float in float4.
  1288. * @param y Second float in float4.
  1289. * @param z Third float in float4.
  1290. * @param w Fourth float in float4.
  1291. * @returns this effect.
  1292. */
  1293. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1294. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1295. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1296. }
  1297. return this;
  1298. };
  1299. /**
  1300. * Sets a Color3 on a uniform variable.
  1301. * @param uniformName Name of the variable.
  1302. * @param color3 Value to be set.
  1303. * @returns this effect.
  1304. */
  1305. Effect.prototype.setColor3 = function (uniformName, color3) {
  1306. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1307. this._engine.setColor3(this.getUniform(uniformName), color3);
  1308. }
  1309. return this;
  1310. };
  1311. /**
  1312. * Sets a Color4 on a uniform variable.
  1313. * @param uniformName Name of the variable.
  1314. * @param color3 Value to be set.
  1315. * @param alpha Alpha value to be set.
  1316. * @returns this effect.
  1317. */
  1318. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1319. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1320. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1321. }
  1322. return this;
  1323. };
  1324. /**
  1325. * Sets a Color4 on a uniform variable
  1326. * @param uniformName defines the name of the variable
  1327. * @param color4 defines the value to be set
  1328. * @returns this effect.
  1329. */
  1330. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1331. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1332. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1333. }
  1334. return this;
  1335. };
  1336. /**
  1337. * Resets the cache of effects.
  1338. */
  1339. Effect.ResetCache = function () {
  1340. Effect._baseCache = {};
  1341. };
  1342. Effect._uniqueIdSeed = 0;
  1343. Effect._baseCache = {};
  1344. Effect._sourceCache = {};
  1345. // Statics
  1346. /**
  1347. * Store of each shader (The can be looked up using effect.key)
  1348. */
  1349. Effect.ShadersStore = {};
  1350. /**
  1351. * Store of each included file for a shader (The can be looked up using effect.key)
  1352. */
  1353. Effect.IncludesShadersStore = {};
  1354. return Effect;
  1355. }());
  1356. BABYLON.Effect = Effect;
  1357. })(BABYLON || (BABYLON = {}));
  1358. //# sourceMappingURL=babylon.effect.js.map
  1359. "use strict";
  1360. //# sourceMappingURL=babylon.types.js.map
  1361. "use strict";
  1362. var BABYLON;
  1363. (function (BABYLON) {
  1364. var KeyboardEventTypes = /** @class */ (function () {
  1365. function KeyboardEventTypes() {
  1366. }
  1367. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1368. get: function () {
  1369. return KeyboardEventTypes._KEYDOWN;
  1370. },
  1371. enumerable: true,
  1372. configurable: true
  1373. });
  1374. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1375. get: function () {
  1376. return KeyboardEventTypes._KEYUP;
  1377. },
  1378. enumerable: true,
  1379. configurable: true
  1380. });
  1381. KeyboardEventTypes._KEYDOWN = 0x01;
  1382. KeyboardEventTypes._KEYUP = 0x02;
  1383. return KeyboardEventTypes;
  1384. }());
  1385. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1386. var KeyboardInfo = /** @class */ (function () {
  1387. function KeyboardInfo(type, event) {
  1388. this.type = type;
  1389. this.event = event;
  1390. }
  1391. return KeyboardInfo;
  1392. }());
  1393. BABYLON.KeyboardInfo = KeyboardInfo;
  1394. /**
  1395. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1396. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1397. */
  1398. var KeyboardInfoPre = /** @class */ (function (_super) {
  1399. __extends(KeyboardInfoPre, _super);
  1400. function KeyboardInfoPre(type, event) {
  1401. var _this = _super.call(this, type, event) || this;
  1402. _this.skipOnPointerObservable = false;
  1403. return _this;
  1404. }
  1405. return KeyboardInfoPre;
  1406. }(KeyboardInfo));
  1407. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1408. })(BABYLON || (BABYLON = {}));
  1409. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1410. "use strict";
  1411. var BABYLON;
  1412. (function (BABYLON) {
  1413. var PointerEventTypes = /** @class */ (function () {
  1414. function PointerEventTypes() {
  1415. }
  1416. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1417. get: function () {
  1418. return PointerEventTypes._POINTERDOWN;
  1419. },
  1420. enumerable: true,
  1421. configurable: true
  1422. });
  1423. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1424. get: function () {
  1425. return PointerEventTypes._POINTERUP;
  1426. },
  1427. enumerable: true,
  1428. configurable: true
  1429. });
  1430. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1431. get: function () {
  1432. return PointerEventTypes._POINTERMOVE;
  1433. },
  1434. enumerable: true,
  1435. configurable: true
  1436. });
  1437. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1438. get: function () {
  1439. return PointerEventTypes._POINTERWHEEL;
  1440. },
  1441. enumerable: true,
  1442. configurable: true
  1443. });
  1444. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1445. get: function () {
  1446. return PointerEventTypes._POINTERPICK;
  1447. },
  1448. enumerable: true,
  1449. configurable: true
  1450. });
  1451. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1452. get: function () {
  1453. return PointerEventTypes._POINTERTAP;
  1454. },
  1455. enumerable: true,
  1456. configurable: true
  1457. });
  1458. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1459. get: function () {
  1460. return PointerEventTypes._POINTERDOUBLETAP;
  1461. },
  1462. enumerable: true,
  1463. configurable: true
  1464. });
  1465. PointerEventTypes._POINTERDOWN = 0x01;
  1466. PointerEventTypes._POINTERUP = 0x02;
  1467. PointerEventTypes._POINTERMOVE = 0x04;
  1468. PointerEventTypes._POINTERWHEEL = 0x08;
  1469. PointerEventTypes._POINTERPICK = 0x10;
  1470. PointerEventTypes._POINTERTAP = 0x20;
  1471. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1472. return PointerEventTypes;
  1473. }());
  1474. BABYLON.PointerEventTypes = PointerEventTypes;
  1475. var PointerInfoBase = /** @class */ (function () {
  1476. function PointerInfoBase(type, event) {
  1477. this.type = type;
  1478. this.event = event;
  1479. }
  1480. return PointerInfoBase;
  1481. }());
  1482. BABYLON.PointerInfoBase = PointerInfoBase;
  1483. /**
  1484. * This class is used to store pointer related info for the onPrePointerObservable event.
  1485. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1486. */
  1487. var PointerInfoPre = /** @class */ (function (_super) {
  1488. __extends(PointerInfoPre, _super);
  1489. function PointerInfoPre(type, event, localX, localY) {
  1490. var _this = _super.call(this, type, event) || this;
  1491. _this.skipOnPointerObservable = false;
  1492. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1493. return _this;
  1494. }
  1495. return PointerInfoPre;
  1496. }(PointerInfoBase));
  1497. BABYLON.PointerInfoPre = PointerInfoPre;
  1498. /**
  1499. * This type contains all the data related to a pointer event in Babylon.js.
  1500. * 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.
  1501. */
  1502. var PointerInfo = /** @class */ (function (_super) {
  1503. __extends(PointerInfo, _super);
  1504. function PointerInfo(type, event, pickInfo) {
  1505. var _this = _super.call(this, type, event) || this;
  1506. _this.pickInfo = pickInfo;
  1507. return _this;
  1508. }
  1509. return PointerInfo;
  1510. }(PointerInfoBase));
  1511. BABYLON.PointerInfo = PointerInfo;
  1512. })(BABYLON || (BABYLON = {}));
  1513. //# sourceMappingURL=babylon.pointerEvents.js.map
  1514. "use strict";
  1515. var BABYLON;
  1516. (function (BABYLON) {
  1517. BABYLON.ToGammaSpace = 1 / 2.2;
  1518. BABYLON.ToLinearSpace = 2.2;
  1519. BABYLON.Epsilon = 0.001;
  1520. /**
  1521. * Class used to hold a RBG color
  1522. */
  1523. var Color3 = /** @class */ (function () {
  1524. /**
  1525. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1526. * @param r defines the red component (between 0 and 1, default is 0)
  1527. * @param g defines the green component (between 0 and 1, default is 0)
  1528. * @param b defines the blue component (between 0 and 1, default is 0)
  1529. */
  1530. function Color3(
  1531. /**
  1532. * Defines the red component (between 0 and 1, default is 0)
  1533. */
  1534. r,
  1535. /**
  1536. * Defines the green component (between 0 and 1, default is 0)
  1537. */
  1538. g,
  1539. /**
  1540. * Defines the blue component (between 0 and 1, default is 0)
  1541. */
  1542. b) {
  1543. if (r === void 0) { r = 0; }
  1544. if (g === void 0) { g = 0; }
  1545. if (b === void 0) { b = 0; }
  1546. this.r = r;
  1547. this.g = g;
  1548. this.b = b;
  1549. }
  1550. /**
  1551. * Creates a string with the Color3 current values
  1552. * @returns the string representation of the Color3 object
  1553. */
  1554. Color3.prototype.toString = function () {
  1555. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1556. };
  1557. /**
  1558. * Returns the string "Color3"
  1559. * @returns "Color3"
  1560. */
  1561. Color3.prototype.getClassName = function () {
  1562. return "Color3";
  1563. };
  1564. /**
  1565. * Compute the Color3 hash code
  1566. * @returns an unique number that can be used to hash Color3 objects
  1567. */
  1568. Color3.prototype.getHashCode = function () {
  1569. var hash = this.r || 0;
  1570. hash = (hash * 397) ^ (this.g || 0);
  1571. hash = (hash * 397) ^ (this.b || 0);
  1572. return hash;
  1573. };
  1574. // Operators
  1575. /**
  1576. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1577. * @param array defines the array where to store the r,g,b components
  1578. * @param index defines an optional index in the target array to define where to start storing values
  1579. * @returns the current Color3 object
  1580. */
  1581. Color3.prototype.toArray = function (array, index) {
  1582. if (index === undefined) {
  1583. index = 0;
  1584. }
  1585. array[index] = this.r;
  1586. array[index + 1] = this.g;
  1587. array[index + 2] = this.b;
  1588. return this;
  1589. };
  1590. /**
  1591. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1592. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1593. * @returns a new {BABYLON.Color4} object
  1594. */
  1595. Color3.prototype.toColor4 = function (alpha) {
  1596. if (alpha === void 0) { alpha = 1; }
  1597. return new Color4(this.r, this.g, this.b, alpha);
  1598. };
  1599. /**
  1600. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1601. * @returns the new array
  1602. */
  1603. Color3.prototype.asArray = function () {
  1604. var result = new Array();
  1605. this.toArray(result, 0);
  1606. return result;
  1607. };
  1608. /**
  1609. * Returns the luminance value
  1610. * @returns a float value
  1611. */
  1612. Color3.prototype.toLuminance = function () {
  1613. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1614. };
  1615. /**
  1616. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1617. * @param otherColor defines the second operand
  1618. * @returns the new Color3 object
  1619. */
  1620. Color3.prototype.multiply = function (otherColor) {
  1621. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1622. };
  1623. /**
  1624. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1625. * @param otherColor defines the second operand
  1626. * @param result defines the Color3 object where to store the result
  1627. * @returns the current Color3
  1628. */
  1629. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1630. result.r = this.r * otherColor.r;
  1631. result.g = this.g * otherColor.g;
  1632. result.b = this.b * otherColor.b;
  1633. return this;
  1634. };
  1635. /**
  1636. * Determines equality between Color3 objects
  1637. * @param otherColor defines the second operand
  1638. * @returns true if the rgb values are equal to the passed ones
  1639. */
  1640. Color3.prototype.equals = function (otherColor) {
  1641. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1642. };
  1643. /**
  1644. * Determines equality between the current Color3 object and a set of r,b,g values
  1645. * @param r defines the red component to check
  1646. * @param g defines the green component to check
  1647. * @param b defines the blue component to check
  1648. * @returns true if the rgb values are equal to the passed ones
  1649. */
  1650. Color3.prototype.equalsFloats = function (r, g, b) {
  1651. return this.r === r && this.g === g && this.b === b;
  1652. };
  1653. /**
  1654. * Multiplies in place each rgb value by scale
  1655. * @param scale defines the scaling factor
  1656. * @returns the updated Color3
  1657. */
  1658. Color3.prototype.scale = function (scale) {
  1659. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1660. };
  1661. /**
  1662. * Multiplies the rgb values by scale and stores the result into "result"
  1663. * @param scale defines the scaling factor
  1664. * @param result defines the Color3 object where to store the result
  1665. * @returns the unmodified current Color3
  1666. */
  1667. Color3.prototype.scaleToRef = function (scale, result) {
  1668. result.r = this.r * scale;
  1669. result.g = this.g * scale;
  1670. result.b = this.b * scale;
  1671. return this;
  1672. };
  1673. /**
  1674. * Scale the current Color3 values by a factor and add the result to a given Color3
  1675. * @param scale defines the scale factor
  1676. * @param result defines color to store the result into
  1677. * @returns the unmodified current Color3
  1678. */
  1679. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1680. result.r += this.r * scale;
  1681. result.g += this.g * scale;
  1682. result.b += this.b * scale;
  1683. return this;
  1684. };
  1685. /**
  1686. * Clamps the rgb values by the min and max values and stores the result into "result"
  1687. * @param min defines minimum clamping value (default is 0)
  1688. * @param max defines maximum clamping value (default is 1)
  1689. * @param result defines color to store the result into
  1690. * @returns the original Color3
  1691. */
  1692. Color3.prototype.clampToRef = function (min, max, result) {
  1693. if (min === void 0) { min = 0; }
  1694. if (max === void 0) { max = 1; }
  1695. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1696. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1697. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1698. return this;
  1699. };
  1700. /**
  1701. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1702. * @param otherColor defines the second operand
  1703. * @returns the new Color3
  1704. */
  1705. Color3.prototype.add = function (otherColor) {
  1706. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1707. };
  1708. /**
  1709. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1710. * @param otherColor defines the second operand
  1711. * @param result defines Color3 object to store the result into
  1712. * @returns the unmodified current Color3
  1713. */
  1714. Color3.prototype.addToRef = function (otherColor, result) {
  1715. result.r = this.r + otherColor.r;
  1716. result.g = this.g + otherColor.g;
  1717. result.b = this.b + otherColor.b;
  1718. return this;
  1719. };
  1720. /**
  1721. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1722. * @param otherColor defines the second operand
  1723. * @returns the new Color3
  1724. */
  1725. Color3.prototype.subtract = function (otherColor) {
  1726. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1727. };
  1728. /**
  1729. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1730. * @param otherColor defines the second operand
  1731. * @param result defines Color3 object to store the result into
  1732. * @returns the unmodified current Color3
  1733. */
  1734. Color3.prototype.subtractToRef = function (otherColor, result) {
  1735. result.r = this.r - otherColor.r;
  1736. result.g = this.g - otherColor.g;
  1737. result.b = this.b - otherColor.b;
  1738. return this;
  1739. };
  1740. /**
  1741. * Copy the current object
  1742. * @returns a new Color3 copied the current one
  1743. */
  1744. Color3.prototype.clone = function () {
  1745. return new Color3(this.r, this.g, this.b);
  1746. };
  1747. /**
  1748. * Copies the rgb values from the source in the current Color3
  1749. * @param source defines the source Color3 object
  1750. * @returns the updated Color3 object
  1751. */
  1752. Color3.prototype.copyFrom = function (source) {
  1753. this.r = source.r;
  1754. this.g = source.g;
  1755. this.b = source.b;
  1756. return this;
  1757. };
  1758. /**
  1759. * Updates the Color3 rgb values from the passed floats
  1760. * @param r defines the red component to read from
  1761. * @param g defines the green component to read from
  1762. * @param b defines the blue component to read from
  1763. * @returns the current Color3 object
  1764. */
  1765. Color3.prototype.copyFromFloats = function (r, g, b) {
  1766. this.r = r;
  1767. this.g = g;
  1768. this.b = b;
  1769. return this;
  1770. };
  1771. /**
  1772. * Updates the Color3 rgb values from the passed floats
  1773. * @param r defines the red component to read from
  1774. * @param g defines the green component to read from
  1775. * @param b defines the blue component to read from
  1776. * @returns the current Color3 object
  1777. */
  1778. Color3.prototype.set = function (r, g, b) {
  1779. return this.copyFromFloats(r, g, b);
  1780. };
  1781. /**
  1782. * Compute the Color3 hexadecimal code as a string
  1783. * @returns a string containing the hexadecimal representation of the Color3 object
  1784. */
  1785. Color3.prototype.toHexString = function () {
  1786. var intR = (this.r * 255) | 0;
  1787. var intG = (this.g * 255) | 0;
  1788. var intB = (this.b * 255) | 0;
  1789. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1790. };
  1791. /**
  1792. * Computes a new Color3 converted from the current one to linear space
  1793. * @returns a new Color3 object
  1794. */
  1795. Color3.prototype.toLinearSpace = function () {
  1796. var convertedColor = new Color3();
  1797. this.toLinearSpaceToRef(convertedColor);
  1798. return convertedColor;
  1799. };
  1800. /**
  1801. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1802. * @param convertedColor defines the Color3 object where to store the linear space version
  1803. * @returns the unmodified Color3
  1804. */
  1805. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1806. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1807. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1808. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1809. return this;
  1810. };
  1811. /**
  1812. * Computes a new Color3 converted from the current one to gamma space
  1813. * @returns a new Color3 object
  1814. */
  1815. Color3.prototype.toGammaSpace = function () {
  1816. var convertedColor = new Color3();
  1817. this.toGammaSpaceToRef(convertedColor);
  1818. return convertedColor;
  1819. };
  1820. /**
  1821. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1822. * @param convertedColor defines the Color3 object where to store the gamma space version
  1823. * @returns the unmodified Color3
  1824. */
  1825. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1826. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1827. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1828. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1829. return this;
  1830. };
  1831. // Statics
  1832. /**
  1833. * Creates a new Color3 from the string containing valid hexadecimal values
  1834. * @param hex defines a string containing valid hexadecimal values
  1835. * @returns a new Color3 object
  1836. */
  1837. Color3.FromHexString = function (hex) {
  1838. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1839. return new Color3(0, 0, 0);
  1840. }
  1841. var r = parseInt(hex.substring(1, 3), 16);
  1842. var g = parseInt(hex.substring(3, 5), 16);
  1843. var b = parseInt(hex.substring(5, 7), 16);
  1844. return Color3.FromInts(r, g, b);
  1845. };
  1846. /**
  1847. * Creates a new Vector3 from the starting index of the passed array
  1848. * @param array defines the source array
  1849. * @param offset defines an offset in the source array
  1850. * @returns a new Color3 object
  1851. */
  1852. Color3.FromArray = function (array, offset) {
  1853. if (offset === void 0) { offset = 0; }
  1854. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1855. };
  1856. /**
  1857. * Creates a new Color3 from integer values (< 256)
  1858. * @param r defines the red component to read from (value between 0 and 255)
  1859. * @param g defines the green component to read from (value between 0 and 255)
  1860. * @param b defines the blue component to read from (value between 0 and 255)
  1861. * @returns a new Color3 object
  1862. */
  1863. Color3.FromInts = function (r, g, b) {
  1864. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1865. };
  1866. /**
  1867. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1868. * @param start defines the start Color3 value
  1869. * @param end defines the end Color3 value
  1870. * @param amount defines the gradient value between start and end
  1871. * @returns a new Color3 object
  1872. */
  1873. Color3.Lerp = function (start, end, amount) {
  1874. var r = start.r + ((end.r - start.r) * amount);
  1875. var g = start.g + ((end.g - start.g) * amount);
  1876. var b = start.b + ((end.b - start.b) * amount);
  1877. return new Color3(r, g, b);
  1878. };
  1879. /**
  1880. * Returns a Color3 value containing a red color
  1881. * @returns a new Color3 object
  1882. */
  1883. Color3.Red = function () { return new Color3(1, 0, 0); };
  1884. /**
  1885. * Returns a Color3 value containing a green color
  1886. * @returns a new Color3 object
  1887. */
  1888. Color3.Green = function () { return new Color3(0, 1, 0); };
  1889. /**
  1890. * Returns a Color3 value containing a blue color
  1891. * @returns a new Color3 object
  1892. */
  1893. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1894. /**
  1895. * Returns a Color3 value containing a black color
  1896. * @returns a new Color3 object
  1897. */
  1898. Color3.Black = function () { return new Color3(0, 0, 0); };
  1899. /**
  1900. * Returns a Color3 value containing a white color
  1901. * @returns a new Color3 object
  1902. */
  1903. Color3.White = function () { return new Color3(1, 1, 1); };
  1904. /**
  1905. * Returns a Color3 value containing a purple color
  1906. * @returns a new Color3 object
  1907. */
  1908. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1909. /**
  1910. * Returns a Color3 value containing a magenta color
  1911. * @returns a new Color3 object
  1912. */
  1913. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1914. /**
  1915. * Returns a Color3 value containing a yellow color
  1916. * @returns a new Color3 object
  1917. */
  1918. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1919. /**
  1920. * Returns a Color3 value containing a gray color
  1921. * @returns a new Color3 object
  1922. */
  1923. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1924. /**
  1925. * Returns a Color3 value containing a teal color
  1926. * @returns a new Color3 object
  1927. */
  1928. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1929. /**
  1930. * Returns a Color3 value containing a random color
  1931. * @returns a new Color3 object
  1932. */
  1933. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1934. return Color3;
  1935. }());
  1936. BABYLON.Color3 = Color3;
  1937. /**
  1938. * Class used to hold a RBGA color
  1939. */
  1940. var Color4 = /** @class */ (function () {
  1941. /**
  1942. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1943. * @param r defines the red component (between 0 and 1, default is 0)
  1944. * @param g defines the green component (between 0 and 1, default is 0)
  1945. * @param b defines the blue component (between 0 and 1, default is 0)
  1946. * @param a defines the alpha component (between 0 and 1, default is 1)
  1947. */
  1948. function Color4(
  1949. /**
  1950. * Defines the red component (between 0 and 1, default is 0)
  1951. */
  1952. r,
  1953. /**
  1954. * Defines the green component (between 0 and 1, default is 0)
  1955. */
  1956. g,
  1957. /**
  1958. * Defines the blue component (between 0 and 1, default is 0)
  1959. */
  1960. b,
  1961. /**
  1962. * Defines the alpha component (between 0 and 1, default is 1)
  1963. */
  1964. a) {
  1965. if (r === void 0) { r = 0; }
  1966. if (g === void 0) { g = 0; }
  1967. if (b === void 0) { b = 0; }
  1968. if (a === void 0) { a = 1; }
  1969. this.r = r;
  1970. this.g = g;
  1971. this.b = b;
  1972. this.a = a;
  1973. }
  1974. // Operators
  1975. /**
  1976. * Adds in place the passed Color4 values to the current Color4 object
  1977. * @param right defines the second operand
  1978. * @returns the current updated Color4 object
  1979. */
  1980. Color4.prototype.addInPlace = function (right) {
  1981. this.r += right.r;
  1982. this.g += right.g;
  1983. this.b += right.b;
  1984. this.a += right.a;
  1985. return this;
  1986. };
  1987. /**
  1988. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1989. * @returns the new array
  1990. */
  1991. Color4.prototype.asArray = function () {
  1992. var result = new Array();
  1993. this.toArray(result, 0);
  1994. return result;
  1995. };
  1996. /**
  1997. * Stores from the starting index in the passed array the Color4 successive values
  1998. * @param array defines the array where to store the r,g,b components
  1999. * @param index defines an optional index in the target array to define where to start storing values
  2000. * @returns the current Color4 object
  2001. */
  2002. Color4.prototype.toArray = function (array, index) {
  2003. if (index === undefined) {
  2004. index = 0;
  2005. }
  2006. array[index] = this.r;
  2007. array[index + 1] = this.g;
  2008. array[index + 2] = this.b;
  2009. array[index + 3] = this.a;
  2010. return this;
  2011. };
  2012. /**
  2013. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  2014. * @param right defines the second operand
  2015. * @returns a new Color4 object
  2016. */
  2017. Color4.prototype.add = function (right) {
  2018. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  2019. };
  2020. /**
  2021. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  2022. * @param right defines the second operand
  2023. * @returns a new Color4 object
  2024. */
  2025. Color4.prototype.subtract = function (right) {
  2026. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  2027. };
  2028. /**
  2029. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  2030. * @param right defines the second operand
  2031. * @param result defines the Color4 object where to store the result
  2032. * @returns the current Color4 object
  2033. */
  2034. Color4.prototype.subtractToRef = function (right, result) {
  2035. result.r = this.r - right.r;
  2036. result.g = this.g - right.g;
  2037. result.b = this.b - right.b;
  2038. result.a = this.a - right.a;
  2039. return this;
  2040. };
  2041. /**
  2042. * Creates a new Color4 with the current Color4 values multiplied by scale
  2043. * @param scale defines the scaling factor to apply
  2044. * @returns a new Color4 object
  2045. */
  2046. Color4.prototype.scale = function (scale) {
  2047. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  2048. };
  2049. /**
  2050. * Multiplies the current Color4 values by scale and stores the result in "result"
  2051. * @param scale defines the scaling factor to apply
  2052. * @param result defines the Color4 object where to store the result
  2053. * @returns the current unmodified Color4
  2054. */
  2055. Color4.prototype.scaleToRef = function (scale, result) {
  2056. result.r = this.r * scale;
  2057. result.g = this.g * scale;
  2058. result.b = this.b * scale;
  2059. result.a = this.a * scale;
  2060. return this;
  2061. };
  2062. /**
  2063. * Scale the current Color4 values by a factor and add the result to a given Color4
  2064. * @param scale defines the scale factor
  2065. * @param result defines the Color4 object where to store the result
  2066. * @returns the unmodified current Color4
  2067. */
  2068. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2069. result.r += this.r * scale;
  2070. result.g += this.g * scale;
  2071. result.b += this.b * scale;
  2072. result.a += this.a * scale;
  2073. return this;
  2074. };
  2075. /**
  2076. * Clamps the rgb values by the min and max values and stores the result into "result"
  2077. * @param min defines minimum clamping value (default is 0)
  2078. * @param max defines maximum clamping value (default is 1)
  2079. * @param result defines color to store the result into.
  2080. * @returns the cuurent Color4
  2081. */
  2082. Color4.prototype.clampToRef = function (min, max, result) {
  2083. if (min === void 0) { min = 0; }
  2084. if (max === void 0) { max = 1; }
  2085. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2086. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2087. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2088. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2089. return this;
  2090. };
  2091. /**
  2092. * Multipy an Color4 value by another and return a new Color4 object
  2093. * @param color defines the Color4 value to multiply by
  2094. * @returns a new Color4 object
  2095. */
  2096. Color4.prototype.multiply = function (color) {
  2097. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2098. };
  2099. /**
  2100. * Multipy a Color4 value by another and push the result in a reference value
  2101. * @param color defines the Color4 value to multiply by
  2102. * @param result defines the Color4 to fill the result in
  2103. * @returns the result Color4
  2104. */
  2105. Color4.prototype.multiplyToRef = function (color, result) {
  2106. result.r = this.r * color.r;
  2107. result.g = this.g * color.g;
  2108. result.b = this.b * color.b;
  2109. result.a = this.a * color.a;
  2110. return result;
  2111. };
  2112. /**
  2113. * Creates a string with the Color4 current values
  2114. * @returns the string representation of the Color4 object
  2115. */
  2116. Color4.prototype.toString = function () {
  2117. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2118. };
  2119. /**
  2120. * Returns the string "Color4"
  2121. * @returns "Color4"
  2122. */
  2123. Color4.prototype.getClassName = function () {
  2124. return "Color4";
  2125. };
  2126. /**
  2127. * Compute the Color4 hash code
  2128. * @returns an unique number that can be used to hash Color4 objects
  2129. */
  2130. Color4.prototype.getHashCode = function () {
  2131. var hash = this.r || 0;
  2132. hash = (hash * 397) ^ (this.g || 0);
  2133. hash = (hash * 397) ^ (this.b || 0);
  2134. hash = (hash * 397) ^ (this.a || 0);
  2135. return hash;
  2136. };
  2137. /**
  2138. * Creates a new Color4 copied from the current one
  2139. * @returns a new Color4 object
  2140. */
  2141. Color4.prototype.clone = function () {
  2142. return new Color4(this.r, this.g, this.b, this.a);
  2143. };
  2144. /**
  2145. * Copies the passed Color4 values into the current one
  2146. * @param source defines the source Color4 object
  2147. * @returns the current updated Color4 object
  2148. */
  2149. Color4.prototype.copyFrom = function (source) {
  2150. this.r = source.r;
  2151. this.g = source.g;
  2152. this.b = source.b;
  2153. this.a = source.a;
  2154. return this;
  2155. };
  2156. /**
  2157. * Copies the passed float values into the current one
  2158. * @param r defines the red component to read from
  2159. * @param g defines the green component to read from
  2160. * @param b defines the blue component to read from
  2161. * @param a defines the alpha component to read from
  2162. * @returns the current updated Color4 object
  2163. */
  2164. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2165. this.r = r;
  2166. this.g = g;
  2167. this.b = b;
  2168. this.a = a;
  2169. return this;
  2170. };
  2171. /**
  2172. * Copies the passed float values into the current one
  2173. * @param r defines the red component to read from
  2174. * @param g defines the green component to read from
  2175. * @param b defines the blue component to read from
  2176. * @param a defines the alpha component to read from
  2177. * @returns the current updated Color4 object
  2178. */
  2179. Color4.prototype.set = function (r, g, b, a) {
  2180. return this.copyFromFloats(r, g, b, a);
  2181. };
  2182. /**
  2183. * Compute the Color4 hexadecimal code as a string
  2184. * @returns a string containing the hexadecimal representation of the Color4 object
  2185. */
  2186. Color4.prototype.toHexString = function () {
  2187. var intR = (this.r * 255) | 0;
  2188. var intG = (this.g * 255) | 0;
  2189. var intB = (this.b * 255) | 0;
  2190. var intA = (this.a * 255) | 0;
  2191. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2192. };
  2193. /**
  2194. * Computes a new Color4 converted from the current one to linear space
  2195. * @returns a new Color4 object
  2196. */
  2197. Color4.prototype.toLinearSpace = function () {
  2198. var convertedColor = new Color4();
  2199. this.toLinearSpaceToRef(convertedColor);
  2200. return convertedColor;
  2201. };
  2202. /**
  2203. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2204. * @param convertedColor defines the Color4 object where to store the linear space version
  2205. * @returns the unmodified Color4
  2206. */
  2207. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2208. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2209. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2210. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2211. convertedColor.a = this.a;
  2212. return this;
  2213. };
  2214. /**
  2215. * Computes a new Color4 converted from the current one to gamma space
  2216. * @returns a new Color4 object
  2217. */
  2218. Color4.prototype.toGammaSpace = function () {
  2219. var convertedColor = new Color4();
  2220. this.toGammaSpaceToRef(convertedColor);
  2221. return convertedColor;
  2222. };
  2223. /**
  2224. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2225. * @param convertedColor defines the Color4 object where to store the gamma space version
  2226. * @returns the unmodified Color4
  2227. */
  2228. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2229. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2230. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2231. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2232. convertedColor.a = this.a;
  2233. return this;
  2234. };
  2235. // Statics
  2236. /**
  2237. * Creates a new Color4 from the string containing valid hexadecimal values
  2238. * @param hex defines a string containing valid hexadecimal values
  2239. * @returns a new Color4 object
  2240. */
  2241. Color4.FromHexString = function (hex) {
  2242. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2243. return new Color4(0.0, 0.0, 0.0, 0.0);
  2244. }
  2245. var r = parseInt(hex.substring(1, 3), 16);
  2246. var g = parseInt(hex.substring(3, 5), 16);
  2247. var b = parseInt(hex.substring(5, 7), 16);
  2248. var a = parseInt(hex.substring(7, 9), 16);
  2249. return Color4.FromInts(r, g, b, a);
  2250. };
  2251. /**
  2252. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2253. * @param left defines the start value
  2254. * @param right defines the end value
  2255. * @param amount defines the gradient factor
  2256. * @returns a new Color4 object
  2257. */
  2258. Color4.Lerp = function (left, right, amount) {
  2259. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2260. Color4.LerpToRef(left, right, amount, result);
  2261. return result;
  2262. };
  2263. /**
  2264. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2265. * @param left defines the start value
  2266. * @param right defines the end value
  2267. * @param amount defines the gradient factor
  2268. * @param result defines the Color4 object where to store data
  2269. */
  2270. Color4.LerpToRef = function (left, right, amount, result) {
  2271. result.r = left.r + (right.r - left.r) * amount;
  2272. result.g = left.g + (right.g - left.g) * amount;
  2273. result.b = left.b + (right.b - left.b) * amount;
  2274. result.a = left.a + (right.a - left.a) * amount;
  2275. };
  2276. /**
  2277. * Creates a new Color4 from the starting index element of the passed array
  2278. * @param array defines the source array to read from
  2279. * @param offset defines the offset in the source array
  2280. * @returns a new Color4 object
  2281. */
  2282. Color4.FromArray = function (array, offset) {
  2283. if (offset === void 0) { offset = 0; }
  2284. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2285. };
  2286. /**
  2287. * Creates a new Color3 from integer values (< 256)
  2288. * @param r defines the red component to read from (value between 0 and 255)
  2289. * @param g defines the green component to read from (value between 0 and 255)
  2290. * @param b defines the blue component to read from (value between 0 and 255)
  2291. * @param a defines the alpha component to read from (value between 0 and 255)
  2292. * @returns a new Color3 object
  2293. */
  2294. Color4.FromInts = function (r, g, b, a) {
  2295. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2296. };
  2297. /**
  2298. * Check the content of a given array and convert it to an array containing RGBA data
  2299. * If the original array was already containing count * 4 values then it is returned directly
  2300. * @param colors defines the array to check
  2301. * @param count defines the number of RGBA data to expect
  2302. * @returns an array containing count * 4 values (RGBA)
  2303. */
  2304. Color4.CheckColors4 = function (colors, count) {
  2305. // Check if color3 was used
  2306. if (colors.length === count * 3) {
  2307. var colors4 = [];
  2308. for (var index = 0; index < colors.length; index += 3) {
  2309. var newIndex = (index / 3) * 4;
  2310. colors4[newIndex] = colors[index];
  2311. colors4[newIndex + 1] = colors[index + 1];
  2312. colors4[newIndex + 2] = colors[index + 2];
  2313. colors4[newIndex + 3] = 1.0;
  2314. }
  2315. return colors4;
  2316. }
  2317. return colors;
  2318. };
  2319. return Color4;
  2320. }());
  2321. BABYLON.Color4 = Color4;
  2322. var Vector2 = /** @class */ (function () {
  2323. /**
  2324. * Creates a new Vector2 from the passed x and y coordinates.
  2325. */
  2326. function Vector2(x, y) {
  2327. this.x = x;
  2328. this.y = y;
  2329. }
  2330. /**
  2331. * Returns a string with the Vector2 coordinates.
  2332. */
  2333. Vector2.prototype.toString = function () {
  2334. return "{X: " + this.x + " Y:" + this.y + "}";
  2335. };
  2336. /**
  2337. * Returns the string "Vector2"
  2338. */
  2339. Vector2.prototype.getClassName = function () {
  2340. return "Vector2";
  2341. };
  2342. /**
  2343. * Returns the Vector2 hash code as a number.
  2344. */
  2345. Vector2.prototype.getHashCode = function () {
  2346. var hash = this.x || 0;
  2347. hash = (hash * 397) ^ (this.y || 0);
  2348. return hash;
  2349. };
  2350. // Operators
  2351. /**
  2352. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2353. * Returns the Vector2.
  2354. */
  2355. Vector2.prototype.toArray = function (array, index) {
  2356. if (index === void 0) { index = 0; }
  2357. array[index] = this.x;
  2358. array[index + 1] = this.y;
  2359. return this;
  2360. };
  2361. /**
  2362. * Returns a new array with 2 elements : the Vector2 coordinates.
  2363. */
  2364. Vector2.prototype.asArray = function () {
  2365. var result = new Array();
  2366. this.toArray(result, 0);
  2367. return result;
  2368. };
  2369. /**
  2370. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2371. * Returns the updated Vector2.
  2372. */
  2373. Vector2.prototype.copyFrom = function (source) {
  2374. this.x = source.x;
  2375. this.y = source.y;
  2376. return this;
  2377. };
  2378. /**
  2379. * Sets the Vector2 coordinates with the passed floats.
  2380. * Returns the updated Vector2.
  2381. */
  2382. Vector2.prototype.copyFromFloats = function (x, y) {
  2383. this.x = x;
  2384. this.y = y;
  2385. return this;
  2386. };
  2387. /**
  2388. * Sets the Vector2 coordinates with the passed floats.
  2389. * Returns the updated Vector2.
  2390. */
  2391. Vector2.prototype.set = function (x, y) {
  2392. return this.copyFromFloats(x, y);
  2393. };
  2394. /**
  2395. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2396. */
  2397. Vector2.prototype.add = function (otherVector) {
  2398. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2399. };
  2400. /**
  2401. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2402. * Returns the Vector2.
  2403. */
  2404. Vector2.prototype.addToRef = function (otherVector, result) {
  2405. result.x = this.x + otherVector.x;
  2406. result.y = this.y + otherVector.y;
  2407. return this;
  2408. };
  2409. /**
  2410. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2411. * Returns the updated Vector2.
  2412. */
  2413. Vector2.prototype.addInPlace = function (otherVector) {
  2414. this.x += otherVector.x;
  2415. this.y += otherVector.y;
  2416. return this;
  2417. };
  2418. /**
  2419. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2420. */
  2421. Vector2.prototype.addVector3 = function (otherVector) {
  2422. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2423. };
  2424. /**
  2425. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2426. */
  2427. Vector2.prototype.subtract = function (otherVector) {
  2428. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2429. };
  2430. /**
  2431. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2432. * Returns the Vector2.
  2433. */
  2434. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2435. result.x = this.x - otherVector.x;
  2436. result.y = this.y - otherVector.y;
  2437. return this;
  2438. };
  2439. /**
  2440. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2441. * Returns the updated Vector2.
  2442. */
  2443. Vector2.prototype.subtractInPlace = function (otherVector) {
  2444. this.x -= otherVector.x;
  2445. this.y -= otherVector.y;
  2446. return this;
  2447. };
  2448. /**
  2449. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2450. * Returns the updated Vector2.
  2451. */
  2452. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2453. this.x *= otherVector.x;
  2454. this.y *= otherVector.y;
  2455. return this;
  2456. };
  2457. /**
  2458. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2459. */
  2460. Vector2.prototype.multiply = function (otherVector) {
  2461. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2462. };
  2463. /**
  2464. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2465. * Returns the Vector2.
  2466. */
  2467. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2468. result.x = this.x * otherVector.x;
  2469. result.y = this.y * otherVector.y;
  2470. return this;
  2471. };
  2472. /**
  2473. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2474. */
  2475. Vector2.prototype.multiplyByFloats = function (x, y) {
  2476. return new Vector2(this.x * x, this.y * y);
  2477. };
  2478. /**
  2479. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2480. */
  2481. Vector2.prototype.divide = function (otherVector) {
  2482. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2483. };
  2484. /**
  2485. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2486. * Returns the Vector2.
  2487. */
  2488. Vector2.prototype.divideToRef = function (otherVector, result) {
  2489. result.x = this.x / otherVector.x;
  2490. result.y = this.y / otherVector.y;
  2491. return this;
  2492. };
  2493. /**
  2494. * Divides the current Vector3 coordinates by the passed ones.
  2495. * Returns the updated Vector3.
  2496. */
  2497. Vector2.prototype.divideInPlace = function (otherVector) {
  2498. return this.divideToRef(otherVector, this);
  2499. };
  2500. /**
  2501. * Returns a new Vector2 with current Vector2 negated coordinates.
  2502. */
  2503. Vector2.prototype.negate = function () {
  2504. return new Vector2(-this.x, -this.y);
  2505. };
  2506. /**
  2507. * Multiply the Vector2 coordinates by scale.
  2508. * Returns the updated Vector2.
  2509. */
  2510. Vector2.prototype.scaleInPlace = function (scale) {
  2511. this.x *= scale;
  2512. this.y *= scale;
  2513. return this;
  2514. };
  2515. /**
  2516. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2517. */
  2518. Vector2.prototype.scale = function (scale) {
  2519. var result = new Vector2(0, 0);
  2520. this.scaleToRef(scale, result);
  2521. return result;
  2522. };
  2523. /**
  2524. * Scale the current Vector2 values by a factor to a given Vector2
  2525. * @param scale defines the scale factor
  2526. * @param result defines the Vector2 object where to store the result
  2527. * @returns the unmodified current Vector2
  2528. */
  2529. Vector2.prototype.scaleToRef = function (scale, result) {
  2530. result.x = this.x * scale;
  2531. result.y = this.y * scale;
  2532. return this;
  2533. };
  2534. /**
  2535. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2536. * @param scale defines the scale factor
  2537. * @param result defines the Vector2 object where to store the result
  2538. * @returns the unmodified current Vector2
  2539. */
  2540. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2541. result.x += this.x * scale;
  2542. result.y += this.y * scale;
  2543. return this;
  2544. };
  2545. /**
  2546. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2547. */
  2548. Vector2.prototype.equals = function (otherVector) {
  2549. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2550. };
  2551. /**
  2552. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2553. */
  2554. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2555. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2556. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2557. };
  2558. // Properties
  2559. /**
  2560. * Returns the vector length (float).
  2561. */
  2562. Vector2.prototype.length = function () {
  2563. return Math.sqrt(this.x * this.x + this.y * this.y);
  2564. };
  2565. /**
  2566. * Returns the vector squared length (float);
  2567. */
  2568. Vector2.prototype.lengthSquared = function () {
  2569. return (this.x * this.x + this.y * this.y);
  2570. };
  2571. // Methods
  2572. /**
  2573. * Normalize the vector.
  2574. * Returns the updated Vector2.
  2575. */
  2576. Vector2.prototype.normalize = function () {
  2577. var len = this.length();
  2578. if (len === 0)
  2579. return this;
  2580. var num = 1.0 / len;
  2581. this.x *= num;
  2582. this.y *= num;
  2583. return this;
  2584. };
  2585. /**
  2586. * Returns a new Vector2 copied from the Vector2.
  2587. */
  2588. Vector2.prototype.clone = function () {
  2589. return new Vector2(this.x, this.y);
  2590. };
  2591. // Statics
  2592. /**
  2593. * Returns a new Vector2(0, 0)
  2594. */
  2595. Vector2.Zero = function () {
  2596. return new Vector2(0, 0);
  2597. };
  2598. /**
  2599. * Returns a new Vector2(1, 1)
  2600. */
  2601. Vector2.One = function () {
  2602. return new Vector2(1, 1);
  2603. };
  2604. /**
  2605. * Returns a new Vector2 set from the passed index element of the passed array.
  2606. */
  2607. Vector2.FromArray = function (array, offset) {
  2608. if (offset === void 0) { offset = 0; }
  2609. return new Vector2(array[offset], array[offset + 1]);
  2610. };
  2611. /**
  2612. * Sets "result" from the passed index element of the passed array.
  2613. */
  2614. Vector2.FromArrayToRef = function (array, offset, result) {
  2615. result.x = array[offset];
  2616. result.y = array[offset + 1];
  2617. };
  2618. /**
  2619. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2620. */
  2621. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2622. var squared = amount * amount;
  2623. var cubed = amount * squared;
  2624. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2625. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2626. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2627. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2628. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2629. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2630. return new Vector2(x, y);
  2631. };
  2632. /**
  2633. * 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".
  2634. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2635. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2636. */
  2637. Vector2.Clamp = function (value, min, max) {
  2638. var x = value.x;
  2639. x = (x > max.x) ? max.x : x;
  2640. x = (x < min.x) ? min.x : x;
  2641. var y = value.y;
  2642. y = (y > max.y) ? max.y : y;
  2643. y = (y < min.y) ? min.y : y;
  2644. return new Vector2(x, y);
  2645. };
  2646. /**
  2647. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2648. */
  2649. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2650. var squared = amount * amount;
  2651. var cubed = amount * squared;
  2652. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2653. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2654. var part3 = (cubed - (2.0 * squared)) + amount;
  2655. var part4 = cubed - squared;
  2656. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2657. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2658. return new Vector2(x, y);
  2659. };
  2660. /**
  2661. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2662. */
  2663. Vector2.Lerp = function (start, end, amount) {
  2664. var x = start.x + ((end.x - start.x) * amount);
  2665. var y = start.y + ((end.y - start.y) * amount);
  2666. return new Vector2(x, y);
  2667. };
  2668. /**
  2669. * Returns the dot product (float) of the vector "left" and the vector "right".
  2670. */
  2671. Vector2.Dot = function (left, right) {
  2672. return left.x * right.x + left.y * right.y;
  2673. };
  2674. /**
  2675. * Returns a new Vector2 equal to the normalized passed vector.
  2676. */
  2677. Vector2.Normalize = function (vector) {
  2678. var newVector = vector.clone();
  2679. newVector.normalize();
  2680. return newVector;
  2681. };
  2682. /**
  2683. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2684. */
  2685. Vector2.Minimize = function (left, right) {
  2686. var x = (left.x < right.x) ? left.x : right.x;
  2687. var y = (left.y < right.y) ? left.y : right.y;
  2688. return new Vector2(x, y);
  2689. };
  2690. /**
  2691. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2692. */
  2693. Vector2.Maximize = function (left, right) {
  2694. var x = (left.x > right.x) ? left.x : right.x;
  2695. var y = (left.y > right.y) ? left.y : right.y;
  2696. return new Vector2(x, y);
  2697. };
  2698. /**
  2699. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2700. */
  2701. Vector2.Transform = function (vector, transformation) {
  2702. var r = Vector2.Zero();
  2703. Vector2.TransformToRef(vector, transformation, r);
  2704. return r;
  2705. };
  2706. /**
  2707. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2708. */
  2709. Vector2.TransformToRef = function (vector, transformation, result) {
  2710. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2711. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2712. result.x = x;
  2713. result.y = y;
  2714. };
  2715. /**
  2716. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2717. */
  2718. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2719. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2720. var sign = a < 0 ? -1 : 1;
  2721. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2722. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2723. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2724. };
  2725. /**
  2726. * Returns the distance (float) between the vectors "value1" and "value2".
  2727. */
  2728. Vector2.Distance = function (value1, value2) {
  2729. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2730. };
  2731. /**
  2732. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2733. */
  2734. Vector2.DistanceSquared = function (value1, value2) {
  2735. var x = value1.x - value2.x;
  2736. var y = value1.y - value2.y;
  2737. return (x * x) + (y * y);
  2738. };
  2739. /**
  2740. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2741. */
  2742. Vector2.Center = function (value1, value2) {
  2743. var center = value1.add(value2);
  2744. center.scaleInPlace(0.5);
  2745. return center;
  2746. };
  2747. /**
  2748. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2749. */
  2750. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2751. var l2 = Vector2.DistanceSquared(segA, segB);
  2752. if (l2 === 0.0) {
  2753. return Vector2.Distance(p, segA);
  2754. }
  2755. var v = segB.subtract(segA);
  2756. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2757. var proj = segA.add(v.multiplyByFloats(t, t));
  2758. return Vector2.Distance(p, proj);
  2759. };
  2760. return Vector2;
  2761. }());
  2762. BABYLON.Vector2 = Vector2;
  2763. /**
  2764. * Classed used to store (x,y,z) vector representation
  2765. * A Vector3 is the main object used in 3D geometry
  2766. * It can represent etiher the coordinates of a point the space, either a direction
  2767. * Reminder: Babylon.js uses a left handed forward facing system
  2768. */
  2769. var Vector3 = /** @class */ (function () {
  2770. /**
  2771. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2772. * @param x defines the first coordinates (on X axis)
  2773. * @param y defines the second coordinates (on Y axis)
  2774. * @param z defines the third coordinates (on Z axis)
  2775. */
  2776. function Vector3(
  2777. /**
  2778. * Defines the first coordinates (on X axis)
  2779. */
  2780. x,
  2781. /**
  2782. * Defines the second coordinates (on Y axis)
  2783. */
  2784. y,
  2785. /**
  2786. * Defines the third coordinates (on Z axis)
  2787. */
  2788. z) {
  2789. this.x = x;
  2790. this.y = y;
  2791. this.z = z;
  2792. }
  2793. /**
  2794. * Creates a string representation of the Vector3
  2795. * @returns a string with the Vector3 coordinates.
  2796. */
  2797. Vector3.prototype.toString = function () {
  2798. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2799. };
  2800. /**
  2801. * Gets the class name
  2802. * @returns the string "Vector3"
  2803. */
  2804. Vector3.prototype.getClassName = function () {
  2805. return "Vector3";
  2806. };
  2807. /**
  2808. * Creates the Vector3 hash code
  2809. * @returns a number which tends to be unique between Vector3 instances
  2810. */
  2811. Vector3.prototype.getHashCode = function () {
  2812. var hash = this.x || 0;
  2813. hash = (hash * 397) ^ (this.y || 0);
  2814. hash = (hash * 397) ^ (this.z || 0);
  2815. return hash;
  2816. };
  2817. // Operators
  2818. /**
  2819. * Creates an array containing three elements : the coordinates of the Vector3
  2820. * @returns a new array of numbers
  2821. */
  2822. Vector3.prototype.asArray = function () {
  2823. var result = [];
  2824. this.toArray(result, 0);
  2825. return result;
  2826. };
  2827. /**
  2828. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2829. * @param array defines the destination array
  2830. * @param index defines the offset in the destination array
  2831. * @returns the current Vector3
  2832. */
  2833. Vector3.prototype.toArray = function (array, index) {
  2834. if (index === void 0) { index = 0; }
  2835. array[index] = this.x;
  2836. array[index + 1] = this.y;
  2837. array[index + 2] = this.z;
  2838. return this;
  2839. };
  2840. /**
  2841. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2842. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2843. */
  2844. Vector3.prototype.toQuaternion = function () {
  2845. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2846. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2847. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2848. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2849. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2850. var cosy = Math.cos(this.y * 0.5);
  2851. var siny = Math.sin(this.y * 0.5);
  2852. result.x = coszMinusx * siny;
  2853. result.y = -sinzMinusx * siny;
  2854. result.z = sinxPlusz * cosy;
  2855. result.w = cosxPlusz * cosy;
  2856. return result;
  2857. };
  2858. /**
  2859. * Adds the passed vector to the current Vector3
  2860. * @param otherVector defines the second operand
  2861. * @returns the current updated Vector3
  2862. */
  2863. Vector3.prototype.addInPlace = function (otherVector) {
  2864. this.x += otherVector.x;
  2865. this.y += otherVector.y;
  2866. this.z += otherVector.z;
  2867. return this;
  2868. };
  2869. /**
  2870. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2871. * @param otherVector defines the second operand
  2872. * @returns the resulting Vector3
  2873. */
  2874. Vector3.prototype.add = function (otherVector) {
  2875. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2876. };
  2877. /**
  2878. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2879. * @param otherVector defines the second operand
  2880. * @param result defines the Vector3 object where to store the result
  2881. * @returns the current Vector3
  2882. */
  2883. Vector3.prototype.addToRef = function (otherVector, result) {
  2884. result.x = this.x + otherVector.x;
  2885. result.y = this.y + otherVector.y;
  2886. result.z = this.z + otherVector.z;
  2887. return this;
  2888. };
  2889. /**
  2890. * Subtract the passed vector from the current Vector3
  2891. * @param otherVector defines the second operand
  2892. * @returns the current updated Vector3
  2893. */
  2894. Vector3.prototype.subtractInPlace = function (otherVector) {
  2895. this.x -= otherVector.x;
  2896. this.y -= otherVector.y;
  2897. this.z -= otherVector.z;
  2898. return this;
  2899. };
  2900. /**
  2901. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2902. * @param otherVector defines the second operand
  2903. * @returns the resulting Vector3
  2904. */
  2905. Vector3.prototype.subtract = function (otherVector) {
  2906. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2907. };
  2908. /**
  2909. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2910. * @param otherVector defines the second operand
  2911. * @param result defines the Vector3 object where to store the result
  2912. * @returns the current Vector3
  2913. */
  2914. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2915. result.x = this.x - otherVector.x;
  2916. result.y = this.y - otherVector.y;
  2917. result.z = this.z - otherVector.z;
  2918. return this;
  2919. };
  2920. /**
  2921. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2922. * @param x defines the x coordinate of the operand
  2923. * @param y defines the y coordinate of the operand
  2924. * @param z defines the z coordinate of the operand
  2925. * @returns the resulting Vector3
  2926. */
  2927. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2928. return new Vector3(this.x - x, this.y - y, this.z - z);
  2929. };
  2930. /**
  2931. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2932. * @param x defines the x coordinate of the operand
  2933. * @param y defines the y coordinate of the operand
  2934. * @param z defines the z coordinate of the operand
  2935. * @param result defines the Vector3 object where to store the result
  2936. * @returns the current Vector3
  2937. */
  2938. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2939. result.x = this.x - x;
  2940. result.y = this.y - y;
  2941. result.z = this.z - z;
  2942. return this;
  2943. };
  2944. /**
  2945. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2946. * @returns a new Vector3
  2947. */
  2948. Vector3.prototype.negate = function () {
  2949. return new Vector3(-this.x, -this.y, -this.z);
  2950. };
  2951. /**
  2952. * Multiplies the Vector3 coordinates by the float "scale"
  2953. * @param scale defines the multiplier factor
  2954. * @returns the current updated Vector3
  2955. */
  2956. Vector3.prototype.scaleInPlace = function (scale) {
  2957. this.x *= scale;
  2958. this.y *= scale;
  2959. this.z *= scale;
  2960. return this;
  2961. };
  2962. /**
  2963. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2964. * @param scale defines the multiplier factor
  2965. * @returns a new Vector3
  2966. */
  2967. Vector3.prototype.scale = function (scale) {
  2968. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2969. };
  2970. /**
  2971. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2972. * @param scale defines the multiplier factor
  2973. * @param result defines the Vector3 object where to store the result
  2974. * @returns the current Vector3
  2975. */
  2976. Vector3.prototype.scaleToRef = function (scale, result) {
  2977. result.x = this.x * scale;
  2978. result.y = this.y * scale;
  2979. result.z = this.z * scale;
  2980. return this;
  2981. };
  2982. /**
  2983. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2984. * @param scale defines the scale factor
  2985. * @param result defines the Vector3 object where to store the result
  2986. * @returns the unmodified current Vector3
  2987. */
  2988. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2989. result.x += this.x * scale;
  2990. result.y += this.y * scale;
  2991. result.z += this.z * scale;
  2992. return this;
  2993. };
  2994. /**
  2995. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2996. * @param otherVector defines the second operand
  2997. * @returns true if both vectors are equals
  2998. */
  2999. Vector3.prototype.equals = function (otherVector) {
  3000. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3001. };
  3002. /**
  3003. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  3004. * @param otherVector defines the second operand
  3005. * @param epsilon defines the minimal distance to define values as equals
  3006. * @returns true if both vectors are distant less than epsilon
  3007. */
  3008. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3009. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3010. 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);
  3011. };
  3012. /**
  3013. * Returns true if the current Vector3 coordinates equals the passed floats
  3014. * @param x defines the x coordinate of the operand
  3015. * @param y defines the y coordinate of the operand
  3016. * @param z defines the z coordinate of the operand
  3017. * @returns true if both vectors are equals
  3018. */
  3019. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3020. return this.x === x && this.y === y && this.z === z;
  3021. };
  3022. /**
  3023. * Multiplies the current Vector3 coordinates by the passed ones
  3024. * @param otherVector defines the second operand
  3025. * @returns the current updated Vector3
  3026. */
  3027. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3028. this.x *= otherVector.x;
  3029. this.y *= otherVector.y;
  3030. this.z *= otherVector.z;
  3031. return this;
  3032. };
  3033. /**
  3034. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  3035. * @param otherVector defines the second operand
  3036. * @returns the new Vector3
  3037. */
  3038. Vector3.prototype.multiply = function (otherVector) {
  3039. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3040. };
  3041. /**
  3042. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  3043. * @param otherVector defines the second operand
  3044. * @param result defines the Vector3 object where to store the result
  3045. * @returns the current Vector3
  3046. */
  3047. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3048. result.x = this.x * otherVector.x;
  3049. result.y = this.y * otherVector.y;
  3050. result.z = this.z * otherVector.z;
  3051. return this;
  3052. };
  3053. /**
  3054. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  3055. * @param x defines the x coordinate of the operand
  3056. * @param y defines the y coordinate of the operand
  3057. * @param z defines the z coordinate of the operand
  3058. * @returns the new Vector3
  3059. */
  3060. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3061. return new Vector3(this.x * x, this.y * y, this.z * z);
  3062. };
  3063. /**
  3064. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  3065. * @param otherVector defines the second operand
  3066. * @returns the new Vector3
  3067. */
  3068. Vector3.prototype.divide = function (otherVector) {
  3069. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3070. };
  3071. /**
  3072. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  3073. * @param otherVector defines the second operand
  3074. * @param result defines the Vector3 object where to store the result
  3075. * @returns the current Vector3
  3076. */
  3077. Vector3.prototype.divideToRef = function (otherVector, result) {
  3078. result.x = this.x / otherVector.x;
  3079. result.y = this.y / otherVector.y;
  3080. result.z = this.z / otherVector.z;
  3081. return this;
  3082. };
  3083. /**
  3084. * Divides the current Vector3 coordinates by the passed ones.
  3085. * @param otherVector defines the second operand
  3086. * @returns the current updated Vector3
  3087. */
  3088. Vector3.prototype.divideInPlace = function (otherVector) {
  3089. return this.divideToRef(otherVector, this);
  3090. };
  3091. /**
  3092. * Updates the current Vector3 with the minimal 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.minimizeInPlace = 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. /**
  3106. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  3107. * @param other defines the second operand
  3108. * @returns the current updated Vector3
  3109. */
  3110. Vector3.prototype.maximizeInPlace = function (other) {
  3111. if (other.x > this.x)
  3112. this.x = other.x;
  3113. if (other.y > this.y)
  3114. this.y = other.y;
  3115. if (other.z > this.z)
  3116. this.z = other.z;
  3117. return this;
  3118. };
  3119. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3120. /**
  3121. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3122. */
  3123. get: function () {
  3124. var absX = Math.abs(this.x);
  3125. var absY = Math.abs(this.y);
  3126. if (absX !== absY) {
  3127. return true;
  3128. }
  3129. var absZ = Math.abs(this.z);
  3130. if (absX !== absZ) {
  3131. return true;
  3132. }
  3133. if (absY !== absZ) {
  3134. return true;
  3135. }
  3136. return false;
  3137. },
  3138. enumerable: true,
  3139. configurable: true
  3140. });
  3141. // Properties
  3142. /**
  3143. * Gets the length of the Vector3
  3144. * @returns the length of the Vecto3
  3145. */
  3146. Vector3.prototype.length = function () {
  3147. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3148. };
  3149. /**
  3150. * Gets the squared length of the Vector3
  3151. * @returns squared length of the Vector3
  3152. */
  3153. Vector3.prototype.lengthSquared = function () {
  3154. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3155. };
  3156. /**
  3157. * Normalize the current Vector3.
  3158. * Please note that this is an in place operation.
  3159. * @returns the current updated Vector3
  3160. */
  3161. Vector3.prototype.normalize = function () {
  3162. var len = this.length();
  3163. if (len === 0 || len === 1.0)
  3164. return this;
  3165. var num = 1.0 / len;
  3166. this.x *= num;
  3167. this.y *= num;
  3168. this.z *= num;
  3169. return this;
  3170. };
  3171. /**
  3172. * Normalize the current Vector3 to a new vector
  3173. * @returns the new Vector3
  3174. */
  3175. Vector3.prototype.normalizeToNew = function () {
  3176. var normalized = new Vector3(0, 0, 0);
  3177. this.normalizeToRef(normalized);
  3178. return normalized;
  3179. };
  3180. /**
  3181. * Normalize the current Vector3 to the reference
  3182. * @param reference define the Vector3 to update
  3183. * @returns the updated Vector3
  3184. */
  3185. Vector3.prototype.normalizeToRef = function (reference) {
  3186. var len = this.length();
  3187. if (len === 0 || len === 1.0) {
  3188. reference.set(this.x, this.y, this.z);
  3189. return reference;
  3190. }
  3191. var scale = 1.0 / len;
  3192. this.scaleToRef(scale, reference);
  3193. return reference;
  3194. };
  3195. /**
  3196. * Creates a new Vector3 copied from the current Vector3
  3197. * @returns the new Vector3
  3198. */
  3199. Vector3.prototype.clone = function () {
  3200. return new Vector3(this.x, this.y, this.z);
  3201. };
  3202. /**
  3203. * Copies the passed vector coordinates to the current Vector3 ones
  3204. * @param source defines the source Vector3
  3205. * @returns the current updated Vector3
  3206. */
  3207. Vector3.prototype.copyFrom = function (source) {
  3208. this.x = source.x;
  3209. this.y = source.y;
  3210. this.z = source.z;
  3211. return this;
  3212. };
  3213. /**
  3214. * Copies the passed floats to the current Vector3 coordinates
  3215. * @param x defines the x coordinate of the operand
  3216. * @param y defines the y coordinate of the operand
  3217. * @param z defines the z coordinate of the operand
  3218. * @returns the current updated Vector3
  3219. */
  3220. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3221. this.x = x;
  3222. this.y = y;
  3223. this.z = z;
  3224. return this;
  3225. };
  3226. /**
  3227. * Copies the passed floats to the current Vector3 coordinates
  3228. * @param x defines the x coordinate of the operand
  3229. * @param y defines the y coordinate of the operand
  3230. * @param z defines the z coordinate of the operand
  3231. * @returns the current updated Vector3
  3232. */
  3233. Vector3.prototype.set = function (x, y, z) {
  3234. return this.copyFromFloats(x, y, z);
  3235. };
  3236. // Statics
  3237. /**
  3238. * Get the clip factor between two vectors
  3239. * @param vector0 defines the first operand
  3240. * @param vector1 defines the second operand
  3241. * @param axis defines the axis to use
  3242. * @param size defines the size along the axis
  3243. * @returns the clip factor
  3244. */
  3245. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3246. var d0 = Vector3.Dot(vector0, axis) - size;
  3247. var d1 = Vector3.Dot(vector1, axis) - size;
  3248. var s = d0 / (d0 - d1);
  3249. return s;
  3250. };
  3251. /**
  3252. * Get angle between two vectors
  3253. * @param vector0 angle between vector0 and vector1
  3254. * @param vector1 angle between vector0 and vector1
  3255. * @param normal direction of the normal
  3256. * @return the angle between vector0 and vector1
  3257. */
  3258. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3259. var v0 = vector0.clone().normalize();
  3260. var v1 = vector1.clone().normalize();
  3261. var dot = Vector3.Dot(v0, v1);
  3262. var n = Vector3.Cross(v0, v1);
  3263. if (Vector3.Dot(n, normal) > 0) {
  3264. return Math.acos(dot);
  3265. }
  3266. return -Math.acos(dot);
  3267. };
  3268. /**
  3269. * Returns a new Vector3 set from the index "offset" of the passed array
  3270. * @param array defines the source array
  3271. * @param offset defines the offset in the source array
  3272. * @returns the new Vector3
  3273. */
  3274. Vector3.FromArray = function (array, offset) {
  3275. if (!offset) {
  3276. offset = 0;
  3277. }
  3278. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3279. };
  3280. /**
  3281. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3282. * This function is deprecated. Use FromArray instead
  3283. * @param array defines the source array
  3284. * @param offset defines the offset in the source array
  3285. * @returns the new Vector3
  3286. */
  3287. Vector3.FromFloatArray = function (array, offset) {
  3288. return Vector3.FromArray(array, offset);
  3289. };
  3290. /**
  3291. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3292. * @param array defines the source array
  3293. * @param offset defines the offset in the source array
  3294. * @param result defines the Vector3 where to store the result
  3295. */
  3296. Vector3.FromArrayToRef = function (array, offset, result) {
  3297. result.x = array[offset];
  3298. result.y = array[offset + 1];
  3299. result.z = array[offset + 2];
  3300. };
  3301. /**
  3302. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3303. * This function is deprecated. Use FromArrayToRef instead.
  3304. * @param array defines the source array
  3305. * @param offset defines the offset in the source array
  3306. * @param result defines the Vector3 where to store the result
  3307. */
  3308. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3309. return Vector3.FromArrayToRef(array, offset, result);
  3310. };
  3311. /**
  3312. * Sets the passed vector "result" with the passed floats.
  3313. * @param x defines the x coordinate of the source
  3314. * @param y defines the y coordinate of the source
  3315. * @param z defines the z coordinate of the source
  3316. * @param result defines the Vector3 where to store the result
  3317. */
  3318. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3319. result.x = x;
  3320. result.y = y;
  3321. result.z = z;
  3322. };
  3323. /**
  3324. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3325. * @returns a new empty Vector3
  3326. */
  3327. Vector3.Zero = function () {
  3328. return new Vector3(0.0, 0.0, 0.0);
  3329. };
  3330. /**
  3331. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3332. * @returns a new unit Vector3
  3333. */
  3334. Vector3.One = function () {
  3335. return new Vector3(1.0, 1.0, 1.0);
  3336. };
  3337. /**
  3338. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3339. * @returns a new up Vector3
  3340. */
  3341. Vector3.Up = function () {
  3342. return new Vector3(0.0, 1.0, 0.0);
  3343. };
  3344. /**
  3345. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3346. * @returns a new forward Vector3
  3347. */
  3348. Vector3.Forward = function () {
  3349. return new Vector3(0.0, 0.0, 1.0);
  3350. };
  3351. /**
  3352. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3353. * @returns a new right Vector3
  3354. */
  3355. Vector3.Right = function () {
  3356. return new Vector3(1.0, 0.0, 0.0);
  3357. };
  3358. /**
  3359. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3360. * @returns a new left Vector3
  3361. */
  3362. Vector3.Left = function () {
  3363. return new Vector3(-1.0, 0.0, 0.0);
  3364. };
  3365. /**
  3366. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3367. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3368. * @param vector defines the Vector3 to transform
  3369. * @param transformation defines the transformation matrix
  3370. * @returns the transformed Vector3
  3371. */
  3372. Vector3.TransformCoordinates = function (vector, transformation) {
  3373. var result = Vector3.Zero();
  3374. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3375. return result;
  3376. };
  3377. /**
  3378. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3379. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3380. * @param vector defines the Vector3 to transform
  3381. * @param transformation defines the transformation matrix
  3382. * @param result defines the Vector3 where to store the result
  3383. */
  3384. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3385. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3386. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3387. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3388. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3389. result.x = x / w;
  3390. result.y = y / w;
  3391. result.z = z / w;
  3392. };
  3393. /**
  3394. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3395. * This method computes tranformed coordinates only, not transformed direction vectors
  3396. * @param x define the x coordinate of the source vector
  3397. * @param y define the y coordinate of the source vector
  3398. * @param z define the z coordinate of the source vector
  3399. * @param transformation defines the transformation matrix
  3400. * @param result defines the Vector3 where to store the result
  3401. */
  3402. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3403. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3404. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3405. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3406. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3407. result.x = rx / rw;
  3408. result.y = ry / rw;
  3409. result.z = rz / rw;
  3410. };
  3411. /**
  3412. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3413. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3414. * @param vector defines the Vector3 to transform
  3415. * @param transformation defines the transformation matrix
  3416. * @returns the new Vector3
  3417. */
  3418. Vector3.TransformNormal = function (vector, transformation) {
  3419. var result = Vector3.Zero();
  3420. Vector3.TransformNormalToRef(vector, transformation, result);
  3421. return result;
  3422. };
  3423. /**
  3424. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3425. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3426. * @param vector defines the Vector3 to transform
  3427. * @param transformation defines the transformation matrix
  3428. * @param result defines the Vector3 where to store the result
  3429. */
  3430. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3431. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3432. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3433. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3434. result.x = x;
  3435. result.y = y;
  3436. result.z = z;
  3437. };
  3438. /**
  3439. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3440. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3441. * @param x define the x coordinate of the source vector
  3442. * @param y define the y coordinate of the source vector
  3443. * @param z define the z coordinate of the source vector
  3444. * @param transformation defines the transformation matrix
  3445. * @param result defines the Vector3 where to store the result
  3446. */
  3447. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3448. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3449. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3450. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3451. };
  3452. /**
  3453. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3454. * @param value1 defines the first control point
  3455. * @param value2 defines the second control point
  3456. * @param value3 defines the third control point
  3457. * @param value4 defines the fourth control point
  3458. * @param amount defines the amount on the spline to use
  3459. * @returns the new Vector3
  3460. */
  3461. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3462. var squared = amount * amount;
  3463. var cubed = amount * squared;
  3464. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3465. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3466. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3467. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3468. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3469. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3470. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3471. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3472. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3473. return new Vector3(x, y, z);
  3474. };
  3475. /**
  3476. * 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"
  3477. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3478. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3479. * @param value defines the current value
  3480. * @param min defines the lower range value
  3481. * @param max defines the upper range value
  3482. * @returns the new Vector3
  3483. */
  3484. Vector3.Clamp = function (value, min, max) {
  3485. var x = value.x;
  3486. x = (x > max.x) ? max.x : x;
  3487. x = (x < min.x) ? min.x : x;
  3488. var y = value.y;
  3489. y = (y > max.y) ? max.y : y;
  3490. y = (y < min.y) ? min.y : y;
  3491. var z = value.z;
  3492. z = (z > max.z) ? max.z : z;
  3493. z = (z < min.z) ? min.z : z;
  3494. return new Vector3(x, y, z);
  3495. };
  3496. /**
  3497. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3498. * @param value1 defines the first control point
  3499. * @param tangent1 defines the first tangent vector
  3500. * @param value2 defines the second control point
  3501. * @param tangent2 defines the second tangent vector
  3502. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3503. * @returns the new Vector3
  3504. */
  3505. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3506. var squared = amount * amount;
  3507. var cubed = amount * squared;
  3508. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3509. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3510. var part3 = (cubed - (2.0 * squared)) + amount;
  3511. var part4 = cubed - squared;
  3512. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3513. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3514. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3515. return new Vector3(x, y, z);
  3516. };
  3517. /**
  3518. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3519. * @param start defines the start value
  3520. * @param end defines the end value
  3521. * @param amount max defines amount between both (between 0 and 1)
  3522. * @returns the new Vector3
  3523. */
  3524. Vector3.Lerp = function (start, end, amount) {
  3525. var result = new Vector3(0, 0, 0);
  3526. Vector3.LerpToRef(start, end, amount, result);
  3527. return result;
  3528. };
  3529. /**
  3530. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3531. * @param start defines the start value
  3532. * @param end defines the end value
  3533. * @param amount max defines amount between both (between 0 and 1)
  3534. * @param result defines the Vector3 where to store the result
  3535. */
  3536. Vector3.LerpToRef = function (start, end, amount, result) {
  3537. result.x = start.x + ((end.x - start.x) * amount);
  3538. result.y = start.y + ((end.y - start.y) * amount);
  3539. result.z = start.z + ((end.z - start.z) * amount);
  3540. };
  3541. /**
  3542. * Returns the dot product (float) between the vectors "left" and "right"
  3543. * @param left defines the left operand
  3544. * @param right defines the right operand
  3545. * @returns the dot product
  3546. */
  3547. Vector3.Dot = function (left, right) {
  3548. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3549. };
  3550. /**
  3551. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3552. * The cross product is then orthogonal to both "left" and "right"
  3553. * @param left defines the left operand
  3554. * @param right defines the right operand
  3555. * @returns the cross product
  3556. */
  3557. Vector3.Cross = function (left, right) {
  3558. var result = Vector3.Zero();
  3559. Vector3.CrossToRef(left, right, result);
  3560. return result;
  3561. };
  3562. /**
  3563. * Sets the passed vector "result" with the cross product of "left" and "right"
  3564. * The cross product is then orthogonal to both "left" and "right"
  3565. * @param left defines the left operand
  3566. * @param right defines the right operand
  3567. * @param result defines the Vector3 where to store the result
  3568. */
  3569. Vector3.CrossToRef = function (left, right, result) {
  3570. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3571. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3572. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3573. result.copyFrom(MathTmp.Vector3[0]);
  3574. };
  3575. /**
  3576. * Returns a new Vector3 as the normalization of the passed vector
  3577. * @param vector defines the Vector3 to normalize
  3578. * @returns the new Vector3
  3579. */
  3580. Vector3.Normalize = function (vector) {
  3581. var result = Vector3.Zero();
  3582. Vector3.NormalizeToRef(vector, result);
  3583. return result;
  3584. };
  3585. /**
  3586. * Sets the passed vector "result" with the normalization of the passed first vector
  3587. * @param vector defines the Vector3 to normalize
  3588. * @param result defines the Vector3 where to store the result
  3589. */
  3590. Vector3.NormalizeToRef = function (vector, result) {
  3591. result.copyFrom(vector);
  3592. result.normalize();
  3593. };
  3594. /**
  3595. * Project a Vector3 onto screen space
  3596. * @param vector defines the Vector3 to project
  3597. * @param world defines the world matrix to use
  3598. * @param transform defines the transform (view x projection) matrix to use
  3599. * @param viewport defines the screen viewport to use
  3600. * @returns the new Vector3
  3601. */
  3602. Vector3.Project = function (vector, world, transform, viewport) {
  3603. var cw = viewport.width;
  3604. var ch = viewport.height;
  3605. var cx = viewport.x;
  3606. var cy = viewport.y;
  3607. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3608. 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);
  3609. var matrix = MathTmp.Matrix[0];
  3610. world.multiplyToRef(transform, matrix);
  3611. matrix.multiplyToRef(viewportMatrix, matrix);
  3612. return Vector3.TransformCoordinates(vector, matrix);
  3613. };
  3614. /**
  3615. * Unproject from screen space to object space
  3616. * @param source defines the screen space Vector3 to use
  3617. * @param viewportWidth defines the current width of the viewport
  3618. * @param viewportHeight defines the current height of the viewport
  3619. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3620. * @param transform defines the transform (view x projection) matrix to use
  3621. * @returns the new Vector3
  3622. */
  3623. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3624. var matrix = MathTmp.Matrix[0];
  3625. world.multiplyToRef(transform, matrix);
  3626. matrix.invert();
  3627. source.x = source.x / viewportWidth * 2 - 1;
  3628. source.y = -(source.y / viewportHeight * 2 - 1);
  3629. var vector = Vector3.TransformCoordinates(source, matrix);
  3630. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3631. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3632. vector = vector.scale(1.0 / num);
  3633. }
  3634. return vector;
  3635. };
  3636. /**
  3637. * Unproject from screen space to object space
  3638. * @param source defines the screen space Vector3 to use
  3639. * @param viewportWidth defines the current width of the viewport
  3640. * @param viewportHeight defines the current height of the viewport
  3641. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3642. * @param view defines the view matrix to use
  3643. * @param projection defines the projection matrix to use
  3644. * @returns the new Vector3
  3645. */
  3646. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3647. var result = Vector3.Zero();
  3648. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3649. return result;
  3650. };
  3651. /**
  3652. * Unproject from screen space to object space
  3653. * @param source defines the screen space Vector3 to use
  3654. * @param viewportWidth defines the current width of the viewport
  3655. * @param viewportHeight defines the current height of the viewport
  3656. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3657. * @param view defines the view matrix to use
  3658. * @param projection defines the projection matrix to use
  3659. * @param result defines the Vector3 where to store the result
  3660. */
  3661. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3662. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3663. };
  3664. /**
  3665. * Unproject from screen space to object space
  3666. * @param sourceX defines the screen space x coordinate to use
  3667. * @param sourceY defines the screen space y coordinate to use
  3668. * @param sourceZ defines the screen space z coordinate to use
  3669. * @param viewportWidth defines the current width of the viewport
  3670. * @param viewportHeight defines the current height of the viewport
  3671. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3672. * @param view defines the view matrix to use
  3673. * @param projection defines the projection matrix to use
  3674. * @param result defines the Vector3 where to store the result
  3675. */
  3676. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3677. var matrix = MathTmp.Matrix[0];
  3678. world.multiplyToRef(view, matrix);
  3679. matrix.multiplyToRef(projection, matrix);
  3680. matrix.invert();
  3681. var screenSource = MathTmp.Vector3[0];
  3682. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3683. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3684. screenSource.z = 2 * sourceZ - 1.0;
  3685. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3686. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3687. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3688. result.scaleInPlace(1.0 / num);
  3689. }
  3690. };
  3691. /**
  3692. * Gets the minimal coordinate values between two Vector3
  3693. * @param left defines the first operand
  3694. * @param right defines the second operand
  3695. * @returns the new Vector3
  3696. */
  3697. Vector3.Minimize = function (left, right) {
  3698. var min = left.clone();
  3699. min.minimizeInPlace(right);
  3700. return min;
  3701. };
  3702. /**
  3703. * Gets the maximal coordinate values between two Vector3
  3704. * @param left defines the first operand
  3705. * @param right defines the second operand
  3706. * @returns the new Vector3
  3707. */
  3708. Vector3.Maximize = function (left, right) {
  3709. var max = left.clone();
  3710. max.maximizeInPlace(right);
  3711. return max;
  3712. };
  3713. /**
  3714. * Returns the distance between the vectors "value1" and "value2"
  3715. * @param value1 defines the first operand
  3716. * @param value2 defines the second operand
  3717. * @returns the distance
  3718. */
  3719. Vector3.Distance = function (value1, value2) {
  3720. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3721. };
  3722. /**
  3723. * Returns the squared distance between the vectors "value1" and "value2"
  3724. * @param value1 defines the first operand
  3725. * @param value2 defines the second operand
  3726. * @returns the squared distance
  3727. */
  3728. Vector3.DistanceSquared = function (value1, value2) {
  3729. var x = value1.x - value2.x;
  3730. var y = value1.y - value2.y;
  3731. var z = value1.z - value2.z;
  3732. return (x * x) + (y * y) + (z * z);
  3733. };
  3734. /**
  3735. * Returns a new Vector3 located at the center between "value1" and "value2"
  3736. * @param value1 defines the first operand
  3737. * @param value2 defines the second operand
  3738. * @returns the new Vector3
  3739. */
  3740. Vector3.Center = function (value1, value2) {
  3741. var center = value1.add(value2);
  3742. center.scaleInPlace(0.5);
  3743. return center;
  3744. };
  3745. /**
  3746. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3747. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3748. * to something in order to rotate it from its local system to the given target system
  3749. * Note: axis1, axis2 and axis3 are normalized during this operation
  3750. * @param axis1 defines the first axis
  3751. * @param axis2 defines the second axis
  3752. * @param axis3 defines the third axis
  3753. * @returns a new Vector3
  3754. */
  3755. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3756. var rotation = Vector3.Zero();
  3757. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3758. return rotation;
  3759. };
  3760. /**
  3761. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3762. * @param axis1 defines the first axis
  3763. * @param axis2 defines the second axis
  3764. * @param axis3 defines the third axis
  3765. * @param ref defines the Vector3 where to store the result
  3766. */
  3767. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3768. var quat = MathTmp.Quaternion[0];
  3769. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3770. quat.toEulerAnglesToRef(ref);
  3771. };
  3772. return Vector3;
  3773. }());
  3774. BABYLON.Vector3 = Vector3;
  3775. //Vector4 class created for EulerAngle class conversion to Quaternion
  3776. var Vector4 = /** @class */ (function () {
  3777. /**
  3778. * Creates a Vector4 object from the passed floats.
  3779. */
  3780. function Vector4(x, y, z, w) {
  3781. this.x = x;
  3782. this.y = y;
  3783. this.z = z;
  3784. this.w = w;
  3785. }
  3786. /**
  3787. * Returns the string with the Vector4 coordinates.
  3788. */
  3789. Vector4.prototype.toString = function () {
  3790. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3791. };
  3792. /**
  3793. * Returns the string "Vector4".
  3794. */
  3795. Vector4.prototype.getClassName = function () {
  3796. return "Vector4";
  3797. };
  3798. /**
  3799. * Returns the Vector4 hash code.
  3800. */
  3801. Vector4.prototype.getHashCode = function () {
  3802. var hash = this.x || 0;
  3803. hash = (hash * 397) ^ (this.y || 0);
  3804. hash = (hash * 397) ^ (this.z || 0);
  3805. hash = (hash * 397) ^ (this.w || 0);
  3806. return hash;
  3807. };
  3808. // Operators
  3809. /**
  3810. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3811. */
  3812. Vector4.prototype.asArray = function () {
  3813. var result = new Array();
  3814. this.toArray(result, 0);
  3815. return result;
  3816. };
  3817. /**
  3818. * Populates the passed array from the passed index with the Vector4 coordinates.
  3819. * Returns the Vector4.
  3820. */
  3821. Vector4.prototype.toArray = function (array, index) {
  3822. if (index === undefined) {
  3823. index = 0;
  3824. }
  3825. array[index] = this.x;
  3826. array[index + 1] = this.y;
  3827. array[index + 2] = this.z;
  3828. array[index + 3] = this.w;
  3829. return this;
  3830. };
  3831. /**
  3832. * Adds the passed vector to the current Vector4.
  3833. * Returns the updated Vector4.
  3834. */
  3835. Vector4.prototype.addInPlace = function (otherVector) {
  3836. this.x += otherVector.x;
  3837. this.y += otherVector.y;
  3838. this.z += otherVector.z;
  3839. this.w += otherVector.w;
  3840. return this;
  3841. };
  3842. /**
  3843. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3844. */
  3845. Vector4.prototype.add = function (otherVector) {
  3846. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3847. };
  3848. /**
  3849. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3850. * Returns the current Vector4.
  3851. */
  3852. Vector4.prototype.addToRef = function (otherVector, result) {
  3853. result.x = this.x + otherVector.x;
  3854. result.y = this.y + otherVector.y;
  3855. result.z = this.z + otherVector.z;
  3856. result.w = this.w + otherVector.w;
  3857. return this;
  3858. };
  3859. /**
  3860. * Subtract in place the passed vector from the current Vector4.
  3861. * Returns the updated Vector4.
  3862. */
  3863. Vector4.prototype.subtractInPlace = function (otherVector) {
  3864. this.x -= otherVector.x;
  3865. this.y -= otherVector.y;
  3866. this.z -= otherVector.z;
  3867. this.w -= otherVector.w;
  3868. return this;
  3869. };
  3870. /**
  3871. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3872. */
  3873. Vector4.prototype.subtract = function (otherVector) {
  3874. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3875. };
  3876. /**
  3877. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3878. * Returns the current Vector4.
  3879. */
  3880. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3881. result.x = this.x - otherVector.x;
  3882. result.y = this.y - otherVector.y;
  3883. result.z = this.z - otherVector.z;
  3884. result.w = this.w - otherVector.w;
  3885. return this;
  3886. };
  3887. /**
  3888. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3889. */
  3890. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3891. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3892. };
  3893. /**
  3894. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3895. * Returns the current Vector4.
  3896. */
  3897. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3898. result.x = this.x - x;
  3899. result.y = this.y - y;
  3900. result.z = this.z - z;
  3901. result.w = this.w - w;
  3902. return this;
  3903. };
  3904. /**
  3905. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3906. */
  3907. Vector4.prototype.negate = function () {
  3908. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3909. };
  3910. /**
  3911. * Multiplies the current Vector4 coordinates by scale (float).
  3912. * Returns the updated Vector4.
  3913. */
  3914. Vector4.prototype.scaleInPlace = function (scale) {
  3915. this.x *= scale;
  3916. this.y *= scale;
  3917. this.z *= scale;
  3918. this.w *= scale;
  3919. return this;
  3920. };
  3921. /**
  3922. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3923. */
  3924. Vector4.prototype.scale = function (scale) {
  3925. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3926. };
  3927. /**
  3928. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3929. * Returns the current Vector4.
  3930. */
  3931. Vector4.prototype.scaleToRef = function (scale, result) {
  3932. result.x = this.x * scale;
  3933. result.y = this.y * scale;
  3934. result.z = this.z * scale;
  3935. result.w = this.w * scale;
  3936. return this;
  3937. };
  3938. /**
  3939. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3940. * @param scale defines the scale factor
  3941. * @param result defines the Vector4 object where to store the result
  3942. * @returns the unmodified current Vector4
  3943. */
  3944. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3945. result.x += this.x * scale;
  3946. result.y += this.y * scale;
  3947. result.z += this.z * scale;
  3948. result.w += this.w * scale;
  3949. return this;
  3950. };
  3951. /**
  3952. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3953. */
  3954. Vector4.prototype.equals = function (otherVector) {
  3955. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3956. };
  3957. /**
  3958. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3959. */
  3960. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3961. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3962. return otherVector
  3963. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3964. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3965. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3966. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3967. };
  3968. /**
  3969. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3970. */
  3971. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3972. return this.x === x && this.y === y && this.z === z && this.w === w;
  3973. };
  3974. /**
  3975. * Multiplies in place the current Vector4 by the passed one.
  3976. * Returns the updated Vector4.
  3977. */
  3978. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3979. this.x *= otherVector.x;
  3980. this.y *= otherVector.y;
  3981. this.z *= otherVector.z;
  3982. this.w *= otherVector.w;
  3983. return this;
  3984. };
  3985. /**
  3986. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3987. */
  3988. Vector4.prototype.multiply = function (otherVector) {
  3989. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3990. };
  3991. /**
  3992. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3993. * Returns the current Vector4.
  3994. */
  3995. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3996. result.x = this.x * otherVector.x;
  3997. result.y = this.y * otherVector.y;
  3998. result.z = this.z * otherVector.z;
  3999. result.w = this.w * otherVector.w;
  4000. return this;
  4001. };
  4002. /**
  4003. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  4004. */
  4005. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4006. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4007. };
  4008. /**
  4009. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  4010. */
  4011. Vector4.prototype.divide = function (otherVector) {
  4012. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4013. };
  4014. /**
  4015. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  4016. * Returns the current Vector4.
  4017. */
  4018. Vector4.prototype.divideToRef = function (otherVector, result) {
  4019. result.x = this.x / otherVector.x;
  4020. result.y = this.y / otherVector.y;
  4021. result.z = this.z / otherVector.z;
  4022. result.w = this.w / otherVector.w;
  4023. return this;
  4024. };
  4025. /**
  4026. * Divides the current Vector3 coordinates by the passed ones.
  4027. * @returns the updated Vector3.
  4028. */
  4029. Vector4.prototype.divideInPlace = function (otherVector) {
  4030. return this.divideToRef(otherVector, this);
  4031. };
  4032. /**
  4033. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  4034. * @param other defines the second operand
  4035. * @returns the current updated Vector4
  4036. */
  4037. Vector4.prototype.minimizeInPlace = function (other) {
  4038. if (other.x < this.x)
  4039. this.x = other.x;
  4040. if (other.y < this.y)
  4041. this.y = other.y;
  4042. if (other.z < this.z)
  4043. this.z = other.z;
  4044. if (other.w < this.w)
  4045. this.w = other.w;
  4046. return this;
  4047. };
  4048. /**
  4049. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  4050. * @param other defines the second operand
  4051. * @returns the current updated Vector4
  4052. */
  4053. Vector4.prototype.maximizeInPlace = function (other) {
  4054. if (other.x > this.x)
  4055. this.x = other.x;
  4056. if (other.y > this.y)
  4057. this.y = other.y;
  4058. if (other.z > this.z)
  4059. this.z = other.z;
  4060. if (other.w > this.w)
  4061. this.w = other.w;
  4062. return this;
  4063. };
  4064. // Properties
  4065. /**
  4066. * Returns the Vector4 length (float).
  4067. */
  4068. Vector4.prototype.length = function () {
  4069. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4070. };
  4071. /**
  4072. * Returns the Vector4 squared length (float).
  4073. */
  4074. Vector4.prototype.lengthSquared = function () {
  4075. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4076. };
  4077. // Methods
  4078. /**
  4079. * Normalizes in place the Vector4.
  4080. * Returns the updated Vector4.
  4081. */
  4082. Vector4.prototype.normalize = function () {
  4083. var len = this.length();
  4084. if (len === 0)
  4085. return this;
  4086. var num = 1.0 / len;
  4087. this.x *= num;
  4088. this.y *= num;
  4089. this.z *= num;
  4090. this.w *= num;
  4091. return this;
  4092. };
  4093. /**
  4094. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4095. */
  4096. Vector4.prototype.toVector3 = function () {
  4097. return new Vector3(this.x, this.y, this.z);
  4098. };
  4099. /**
  4100. * Returns a new Vector4 copied from the current one.
  4101. */
  4102. Vector4.prototype.clone = function () {
  4103. return new Vector4(this.x, this.y, this.z, this.w);
  4104. };
  4105. /**
  4106. * Updates the current Vector4 with the passed one coordinates.
  4107. * Returns the updated Vector4.
  4108. */
  4109. Vector4.prototype.copyFrom = function (source) {
  4110. this.x = source.x;
  4111. this.y = source.y;
  4112. this.z = source.z;
  4113. this.w = source.w;
  4114. return this;
  4115. };
  4116. /**
  4117. * Updates the current Vector4 coordinates with the passed floats.
  4118. * Returns the updated Vector4.
  4119. */
  4120. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4121. this.x = x;
  4122. this.y = y;
  4123. this.z = z;
  4124. this.w = w;
  4125. return this;
  4126. };
  4127. /**
  4128. * Updates the current Vector4 coordinates with the passed floats.
  4129. * Returns the updated Vector4.
  4130. */
  4131. Vector4.prototype.set = function (x, y, z, w) {
  4132. return this.copyFromFloats(x, y, z, w);
  4133. };
  4134. // Statics
  4135. /**
  4136. * Returns a new Vector4 set from the starting index of the passed array.
  4137. */
  4138. Vector4.FromArray = function (array, offset) {
  4139. if (!offset) {
  4140. offset = 0;
  4141. }
  4142. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4143. };
  4144. /**
  4145. * Updates the passed vector "result" from the starting index of the passed array.
  4146. */
  4147. Vector4.FromArrayToRef = function (array, offset, result) {
  4148. result.x = array[offset];
  4149. result.y = array[offset + 1];
  4150. result.z = array[offset + 2];
  4151. result.w = array[offset + 3];
  4152. };
  4153. /**
  4154. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  4155. */
  4156. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4157. Vector4.FromArrayToRef(array, offset, result);
  4158. };
  4159. /**
  4160. * Updates the passed vector "result" coordinates from the passed floats.
  4161. */
  4162. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4163. result.x = x;
  4164. result.y = y;
  4165. result.z = z;
  4166. result.w = w;
  4167. };
  4168. /**
  4169. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4170. */
  4171. Vector4.Zero = function () {
  4172. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4173. };
  4174. /**
  4175. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4176. */
  4177. Vector4.One = function () {
  4178. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4179. };
  4180. /**
  4181. * Returns a new normalized Vector4 from the passed one.
  4182. */
  4183. Vector4.Normalize = function (vector) {
  4184. var result = Vector4.Zero();
  4185. Vector4.NormalizeToRef(vector, result);
  4186. return result;
  4187. };
  4188. /**
  4189. * Updates the passed vector "result" from the normalization of the passed one.
  4190. */
  4191. Vector4.NormalizeToRef = function (vector, result) {
  4192. result.copyFrom(vector);
  4193. result.normalize();
  4194. };
  4195. Vector4.Minimize = function (left, right) {
  4196. var min = left.clone();
  4197. min.minimizeInPlace(right);
  4198. return min;
  4199. };
  4200. Vector4.Maximize = function (left, right) {
  4201. var max = left.clone();
  4202. max.maximizeInPlace(right);
  4203. return max;
  4204. };
  4205. /**
  4206. * Returns the distance (float) between the vectors "value1" and "value2".
  4207. */
  4208. Vector4.Distance = function (value1, value2) {
  4209. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4210. };
  4211. /**
  4212. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4213. */
  4214. Vector4.DistanceSquared = function (value1, value2) {
  4215. var x = value1.x - value2.x;
  4216. var y = value1.y - value2.y;
  4217. var z = value1.z - value2.z;
  4218. var w = value1.w - value2.w;
  4219. return (x * x) + (y * y) + (z * z) + (w * w);
  4220. };
  4221. /**
  4222. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4223. */
  4224. Vector4.Center = function (value1, value2) {
  4225. var center = value1.add(value2);
  4226. center.scaleInPlace(0.5);
  4227. return center;
  4228. };
  4229. /**
  4230. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4231. * This methods computes transformed normalized direction vectors only.
  4232. */
  4233. Vector4.TransformNormal = function (vector, transformation) {
  4234. var result = Vector4.Zero();
  4235. Vector4.TransformNormalToRef(vector, transformation, result);
  4236. return result;
  4237. };
  4238. /**
  4239. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4240. * This methods computes transformed normalized direction vectors only.
  4241. */
  4242. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4243. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4244. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4245. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4246. result.x = x;
  4247. result.y = y;
  4248. result.z = z;
  4249. result.w = vector.w;
  4250. };
  4251. /**
  4252. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4253. * This methods computes transformed normalized direction vectors only.
  4254. */
  4255. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4256. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4257. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4258. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4259. result.w = w;
  4260. };
  4261. return Vector4;
  4262. }());
  4263. BABYLON.Vector4 = Vector4;
  4264. var Size = /** @class */ (function () {
  4265. /**
  4266. * Creates a Size object from the passed width and height (floats).
  4267. */
  4268. function Size(width, height) {
  4269. this.width = width;
  4270. this.height = height;
  4271. }
  4272. // Returns a string with the Size width and height.
  4273. Size.prototype.toString = function () {
  4274. return "{W: " + this.width + ", H: " + this.height + "}";
  4275. };
  4276. /**
  4277. * Returns the string "Size"
  4278. */
  4279. Size.prototype.getClassName = function () {
  4280. return "Size";
  4281. };
  4282. /**
  4283. * Returns the Size hash code.
  4284. */
  4285. Size.prototype.getHashCode = function () {
  4286. var hash = this.width || 0;
  4287. hash = (hash * 397) ^ (this.height || 0);
  4288. return hash;
  4289. };
  4290. /**
  4291. * Updates the current size from the passed one.
  4292. * Returns the updated Size.
  4293. */
  4294. Size.prototype.copyFrom = function (src) {
  4295. this.width = src.width;
  4296. this.height = src.height;
  4297. };
  4298. /**
  4299. * Updates in place the current Size from the passed floats.
  4300. * Returns the updated Size.
  4301. */
  4302. Size.prototype.copyFromFloats = function (width, height) {
  4303. this.width = width;
  4304. this.height = height;
  4305. return this;
  4306. };
  4307. /**
  4308. * Updates in place the current Size from the passed floats.
  4309. * Returns the updated Size.
  4310. */
  4311. Size.prototype.set = function (width, height) {
  4312. return this.copyFromFloats(width, height);
  4313. };
  4314. /**
  4315. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4316. */
  4317. Size.prototype.multiplyByFloats = function (w, h) {
  4318. return new Size(this.width * w, this.height * h);
  4319. };
  4320. /**
  4321. * Returns a new Size copied from the passed one.
  4322. */
  4323. Size.prototype.clone = function () {
  4324. return new Size(this.width, this.height);
  4325. };
  4326. /**
  4327. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4328. */
  4329. Size.prototype.equals = function (other) {
  4330. if (!other) {
  4331. return false;
  4332. }
  4333. return (this.width === other.width) && (this.height === other.height);
  4334. };
  4335. Object.defineProperty(Size.prototype, "surface", {
  4336. /**
  4337. * Returns the surface of the Size : width * height (float).
  4338. */
  4339. get: function () {
  4340. return this.width * this.height;
  4341. },
  4342. enumerable: true,
  4343. configurable: true
  4344. });
  4345. /**
  4346. * Returns a new Size set to (0.0, 0.0)
  4347. */
  4348. Size.Zero = function () {
  4349. return new Size(0.0, 0.0);
  4350. };
  4351. /**
  4352. * Returns a new Size set as the addition result of the current Size and the passed one.
  4353. */
  4354. Size.prototype.add = function (otherSize) {
  4355. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4356. return r;
  4357. };
  4358. /**
  4359. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4360. */
  4361. Size.prototype.subtract = function (otherSize) {
  4362. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4363. return r;
  4364. };
  4365. /**
  4366. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4367. */
  4368. Size.Lerp = function (start, end, amount) {
  4369. var w = start.width + ((end.width - start.width) * amount);
  4370. var h = start.height + ((end.height - start.height) * amount);
  4371. return new Size(w, h);
  4372. };
  4373. return Size;
  4374. }());
  4375. BABYLON.Size = Size;
  4376. var Quaternion = /** @class */ (function () {
  4377. /**
  4378. * Creates a new Quaternion from the passed floats.
  4379. */
  4380. function Quaternion(x, y, z, w) {
  4381. if (x === void 0) { x = 0.0; }
  4382. if (y === void 0) { y = 0.0; }
  4383. if (z === void 0) { z = 0.0; }
  4384. if (w === void 0) { w = 1.0; }
  4385. this.x = x;
  4386. this.y = y;
  4387. this.z = z;
  4388. this.w = w;
  4389. }
  4390. /**
  4391. * Returns a string with the Quaternion coordinates.
  4392. */
  4393. Quaternion.prototype.toString = function () {
  4394. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4395. };
  4396. /**
  4397. * Returns the string "Quaternion".
  4398. */
  4399. Quaternion.prototype.getClassName = function () {
  4400. return "Quaternion";
  4401. };
  4402. /**
  4403. * Returns the Quaternion hash code.
  4404. */
  4405. Quaternion.prototype.getHashCode = function () {
  4406. var hash = this.x || 0;
  4407. hash = (hash * 397) ^ (this.y || 0);
  4408. hash = (hash * 397) ^ (this.z || 0);
  4409. hash = (hash * 397) ^ (this.w || 0);
  4410. return hash;
  4411. };
  4412. /**
  4413. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4414. */
  4415. Quaternion.prototype.asArray = function () {
  4416. return [this.x, this.y, this.z, this.w];
  4417. };
  4418. /**
  4419. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4420. */
  4421. Quaternion.prototype.equals = function (otherQuaternion) {
  4422. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4423. };
  4424. /**
  4425. * Returns a new Quaternion copied from the current one.
  4426. */
  4427. Quaternion.prototype.clone = function () {
  4428. return new Quaternion(this.x, this.y, this.z, this.w);
  4429. };
  4430. /**
  4431. * Updates the current Quaternion from the passed one coordinates.
  4432. * Returns the updated Quaterion.
  4433. */
  4434. Quaternion.prototype.copyFrom = function (other) {
  4435. this.x = other.x;
  4436. this.y = other.y;
  4437. this.z = other.z;
  4438. this.w = other.w;
  4439. return this;
  4440. };
  4441. /**
  4442. * Updates the current Quaternion from the passed float coordinates.
  4443. * Returns the updated Quaterion.
  4444. */
  4445. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4446. this.x = x;
  4447. this.y = y;
  4448. this.z = z;
  4449. this.w = w;
  4450. return this;
  4451. };
  4452. /**
  4453. * Updates the current Quaternion from the passed float coordinates.
  4454. * Returns the updated Quaterion.
  4455. */
  4456. Quaternion.prototype.set = function (x, y, z, w) {
  4457. return this.copyFromFloats(x, y, z, w);
  4458. };
  4459. /**
  4460. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4461. */
  4462. Quaternion.prototype.add = function (other) {
  4463. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4464. };
  4465. /**
  4466. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4467. */
  4468. Quaternion.prototype.subtract = function (other) {
  4469. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4470. };
  4471. /**
  4472. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4473. */
  4474. Quaternion.prototype.scale = function (value) {
  4475. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4476. };
  4477. /**
  4478. * Scale the current Quaternion values by a factor to a given Quaternion
  4479. * @param scale defines the scale factor
  4480. * @param result defines the Quaternion object where to store the result
  4481. * @returns the unmodified current Quaternion
  4482. */
  4483. Quaternion.prototype.scaleToRef = function (scale, result) {
  4484. result.x = this.x * scale;
  4485. result.y = this.y * scale;
  4486. result.z = this.z * scale;
  4487. result.w = this.w * scale;
  4488. return this;
  4489. };
  4490. /**
  4491. * Scale the current Quaternion values by a factor and add the result to a given Quaternion
  4492. * @param scale defines the scale factor
  4493. * @param result defines the Quaternion object where to store the result
  4494. * @returns the unmodified current Quaternion
  4495. */
  4496. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4497. result.x += this.x * scale;
  4498. result.y += this.y * scale;
  4499. result.z += this.z * scale;
  4500. result.w += this.w * scale;
  4501. return this;
  4502. };
  4503. /**
  4504. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4505. */
  4506. Quaternion.prototype.multiply = function (q1) {
  4507. var result = new Quaternion(0, 0, 0, 1.0);
  4508. this.multiplyToRef(q1, result);
  4509. return result;
  4510. };
  4511. /**
  4512. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4513. * Returns the current Quaternion.
  4514. */
  4515. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4516. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4517. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4518. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4519. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4520. result.copyFromFloats(x, y, z, w);
  4521. return this;
  4522. };
  4523. /**
  4524. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4525. * Returns the updated Quaternion.
  4526. */
  4527. Quaternion.prototype.multiplyInPlace = function (q1) {
  4528. this.multiplyToRef(q1, this);
  4529. return this;
  4530. };
  4531. /**
  4532. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4533. * Returns the current Quaternion.
  4534. */
  4535. Quaternion.prototype.conjugateToRef = function (ref) {
  4536. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4537. return this;
  4538. };
  4539. /**
  4540. * Conjugates in place the current Quaternion.
  4541. * Returns the updated Quaternion.
  4542. */
  4543. Quaternion.prototype.conjugateInPlace = function () {
  4544. this.x *= -1;
  4545. this.y *= -1;
  4546. this.z *= -1;
  4547. return this;
  4548. };
  4549. /**
  4550. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4551. */
  4552. Quaternion.prototype.conjugate = function () {
  4553. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4554. return result;
  4555. };
  4556. /**
  4557. * Returns the Quaternion length (float).
  4558. */
  4559. Quaternion.prototype.length = function () {
  4560. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4561. };
  4562. /**
  4563. * Normalize in place the current Quaternion.
  4564. * Returns the updated Quaternion.
  4565. */
  4566. Quaternion.prototype.normalize = function () {
  4567. var length = 1.0 / this.length();
  4568. this.x *= length;
  4569. this.y *= length;
  4570. this.z *= length;
  4571. this.w *= length;
  4572. return this;
  4573. };
  4574. /**
  4575. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion
  4576. * @param order is a reserved parameter and is ignore for now
  4577. * @returns the new Vector3
  4578. */
  4579. Quaternion.prototype.toEulerAngles = function (order) {
  4580. if (order === void 0) { order = "YZX"; }
  4581. var result = Vector3.Zero();
  4582. this.toEulerAnglesToRef(result, order);
  4583. return result;
  4584. };
  4585. /**
  4586. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion
  4587. * @param result defines the vector which will be filled with the Euler angles
  4588. * @param order is a reserved parameter and is ignore for now
  4589. * @returns the current Quaternion
  4590. */
  4591. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4592. if (order === void 0) { order = "YZX"; }
  4593. var qz = this.z;
  4594. var qx = this.x;
  4595. var qy = this.y;
  4596. var qw = this.w;
  4597. var sqw = qw * qw;
  4598. var sqz = qz * qz;
  4599. var sqx = qx * qx;
  4600. var sqy = qy * qy;
  4601. var zAxisY = qy * qz - qx * qw;
  4602. var limit = .4999999;
  4603. if (zAxisY < -limit) {
  4604. result.y = 2 * Math.atan2(qy, qw);
  4605. result.x = Math.PI / 2;
  4606. result.z = 0;
  4607. }
  4608. else if (zAxisY > limit) {
  4609. result.y = 2 * Math.atan2(qy, qw);
  4610. result.x = -Math.PI / 2;
  4611. result.z = 0;
  4612. }
  4613. else {
  4614. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4615. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4616. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4617. }
  4618. return this;
  4619. };
  4620. /**
  4621. * Updates the passed rotation matrix with the current Quaternion values.
  4622. * Returns the current Quaternion.
  4623. */
  4624. Quaternion.prototype.toRotationMatrix = function (result) {
  4625. var xx = this.x * this.x;
  4626. var yy = this.y * this.y;
  4627. var zz = this.z * this.z;
  4628. var xy = this.x * this.y;
  4629. var zw = this.z * this.w;
  4630. var zx = this.z * this.x;
  4631. var yw = this.y * this.w;
  4632. var yz = this.y * this.z;
  4633. var xw = this.x * this.w;
  4634. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4635. result.m[1] = 2.0 * (xy + zw);
  4636. result.m[2] = 2.0 * (zx - yw);
  4637. result.m[3] = 0;
  4638. result.m[4] = 2.0 * (xy - zw);
  4639. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4640. result.m[6] = 2.0 * (yz + xw);
  4641. result.m[7] = 0;
  4642. result.m[8] = 2.0 * (zx + yw);
  4643. result.m[9] = 2.0 * (yz - xw);
  4644. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4645. result.m[11] = 0;
  4646. result.m[12] = 0;
  4647. result.m[13] = 0;
  4648. result.m[14] = 0;
  4649. result.m[15] = 1.0;
  4650. result._markAsUpdated();
  4651. return this;
  4652. };
  4653. /**
  4654. * Updates the current Quaternion from the passed rotation matrix values.
  4655. * Returns the updated Quaternion.
  4656. */
  4657. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4658. Quaternion.FromRotationMatrixToRef(matrix, this);
  4659. return this;
  4660. };
  4661. // Statics
  4662. /**
  4663. * Returns a new Quaternion set from the passed rotation matrix values.
  4664. */
  4665. Quaternion.FromRotationMatrix = function (matrix) {
  4666. var result = new Quaternion();
  4667. Quaternion.FromRotationMatrixToRef(matrix, result);
  4668. return result;
  4669. };
  4670. /**
  4671. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4672. */
  4673. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4674. var data = matrix.m;
  4675. var m11 = data[0], m12 = data[4], m13 = data[8];
  4676. var m21 = data[1], m22 = data[5], m23 = data[9];
  4677. var m31 = data[2], m32 = data[6], m33 = data[10];
  4678. var trace = m11 + m22 + m33;
  4679. var s;
  4680. if (trace > 0) {
  4681. s = 0.5 / Math.sqrt(trace + 1.0);
  4682. result.w = 0.25 / s;
  4683. result.x = (m32 - m23) * s;
  4684. result.y = (m13 - m31) * s;
  4685. result.z = (m21 - m12) * s;
  4686. }
  4687. else if (m11 > m22 && m11 > m33) {
  4688. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4689. result.w = (m32 - m23) / s;
  4690. result.x = 0.25 * s;
  4691. result.y = (m12 + m21) / s;
  4692. result.z = (m13 + m31) / s;
  4693. }
  4694. else if (m22 > m33) {
  4695. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4696. result.w = (m13 - m31) / s;
  4697. result.x = (m12 + m21) / s;
  4698. result.y = 0.25 * s;
  4699. result.z = (m23 + m32) / s;
  4700. }
  4701. else {
  4702. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4703. result.w = (m21 - m12) / s;
  4704. result.x = (m13 + m31) / s;
  4705. result.y = (m23 + m32) / s;
  4706. result.z = 0.25 * s;
  4707. }
  4708. };
  4709. /**
  4710. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4711. */
  4712. Quaternion.Zero = function () {
  4713. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4714. };
  4715. /**
  4716. * Returns a new Quaternion as the inverted current Quaternion.
  4717. */
  4718. Quaternion.Inverse = function (q) {
  4719. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4720. };
  4721. /**
  4722. * Returns the identity Quaternion.
  4723. */
  4724. Quaternion.Identity = function () {
  4725. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4726. };
  4727. Quaternion.IsIdentity = function (quaternion) {
  4728. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4729. };
  4730. /**
  4731. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4732. */
  4733. Quaternion.RotationAxis = function (axis, angle) {
  4734. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4735. };
  4736. /**
  4737. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4738. */
  4739. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4740. var sin = Math.sin(angle / 2);
  4741. axis.normalize();
  4742. result.w = Math.cos(angle / 2);
  4743. result.x = axis.x * sin;
  4744. result.y = axis.y * sin;
  4745. result.z = axis.z * sin;
  4746. return result;
  4747. };
  4748. /**
  4749. * Retuns a new Quaternion set from the starting index of the passed array.
  4750. */
  4751. Quaternion.FromArray = function (array, offset) {
  4752. if (!offset) {
  4753. offset = 0;
  4754. }
  4755. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4756. };
  4757. /**
  4758. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4759. */
  4760. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4761. var q = new Quaternion();
  4762. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4763. return q;
  4764. };
  4765. /**
  4766. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4767. */
  4768. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4769. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4770. var halfRoll = roll * 0.5;
  4771. var halfPitch = pitch * 0.5;
  4772. var halfYaw = yaw * 0.5;
  4773. var sinRoll = Math.sin(halfRoll);
  4774. var cosRoll = Math.cos(halfRoll);
  4775. var sinPitch = Math.sin(halfPitch);
  4776. var cosPitch = Math.cos(halfPitch);
  4777. var sinYaw = Math.sin(halfYaw);
  4778. var cosYaw = Math.cos(halfYaw);
  4779. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4780. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4781. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4782. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4783. };
  4784. /**
  4785. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4786. */
  4787. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4788. var result = new Quaternion();
  4789. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4790. return result;
  4791. };
  4792. /**
  4793. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4794. */
  4795. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4796. // Produces a quaternion from Euler angles in the z-x-z orientation
  4797. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4798. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4799. var halfBeta = beta * 0.5;
  4800. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4801. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4802. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4803. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4804. };
  4805. /**
  4806. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4807. * cf to Vector3.RotationFromAxis() documentation.
  4808. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4809. */
  4810. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4811. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4812. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4813. return quat;
  4814. };
  4815. /**
  4816. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4817. * cf to Vector3.RotationFromAxis() documentation.
  4818. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4819. */
  4820. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4821. var rotMat = MathTmp.Matrix[0];
  4822. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4823. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4824. };
  4825. Quaternion.Slerp = function (left, right, amount) {
  4826. var result = Quaternion.Identity();
  4827. Quaternion.SlerpToRef(left, right, amount, result);
  4828. return result;
  4829. };
  4830. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4831. var num2;
  4832. var num3;
  4833. var num = amount;
  4834. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4835. var flag = false;
  4836. if (num4 < 0) {
  4837. flag = true;
  4838. num4 = -num4;
  4839. }
  4840. if (num4 > 0.999999) {
  4841. num3 = 1 - num;
  4842. num2 = flag ? -num : num;
  4843. }
  4844. else {
  4845. var num5 = Math.acos(num4);
  4846. var num6 = (1.0 / Math.sin(num5));
  4847. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4848. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4849. }
  4850. result.x = (num3 * left.x) + (num2 * right.x);
  4851. result.y = (num3 * left.y) + (num2 * right.y);
  4852. result.z = (num3 * left.z) + (num2 * right.z);
  4853. result.w = (num3 * left.w) + (num2 * right.w);
  4854. };
  4855. /**
  4856. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4857. */
  4858. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4859. var squared = amount * amount;
  4860. var cubed = amount * squared;
  4861. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4862. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4863. var part3 = (cubed - (2.0 * squared)) + amount;
  4864. var part4 = cubed - squared;
  4865. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4866. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4867. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4868. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4869. return new Quaternion(x, y, z, w);
  4870. };
  4871. return Quaternion;
  4872. }());
  4873. BABYLON.Quaternion = Quaternion;
  4874. var Matrix = /** @class */ (function () {
  4875. function Matrix() {
  4876. this._isIdentity = false;
  4877. this._isIdentityDirty = true;
  4878. this.m = new Float32Array(16);
  4879. this._markAsUpdated();
  4880. }
  4881. Matrix.prototype._markAsUpdated = function () {
  4882. this.updateFlag = Matrix._updateFlagSeed++;
  4883. this._isIdentityDirty = true;
  4884. };
  4885. // Properties
  4886. /**
  4887. * Boolean : True is the matrix is the identity matrix
  4888. */
  4889. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4890. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4891. if (this._isIdentityDirty) {
  4892. this._isIdentityDirty = false;
  4893. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4894. this._isIdentity = false;
  4895. }
  4896. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4897. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4898. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4899. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4900. this._isIdentity = false;
  4901. }
  4902. else {
  4903. this._isIdentity = true;
  4904. }
  4905. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4906. this._isIdentity = false;
  4907. }
  4908. }
  4909. return this._isIdentity;
  4910. };
  4911. /**
  4912. * Returns the matrix determinant (float).
  4913. */
  4914. Matrix.prototype.determinant = function () {
  4915. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4916. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4917. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4918. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4919. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4920. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4921. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4922. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4923. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4924. };
  4925. // Methods
  4926. /**
  4927. * Returns the matrix underlying array.
  4928. */
  4929. Matrix.prototype.toArray = function () {
  4930. return this.m;
  4931. };
  4932. /**
  4933. * Returns the matrix underlying array.
  4934. */
  4935. Matrix.prototype.asArray = function () {
  4936. return this.toArray();
  4937. };
  4938. /**
  4939. * Inverts in place the Matrix.
  4940. * Returns the Matrix inverted.
  4941. */
  4942. Matrix.prototype.invert = function () {
  4943. this.invertToRef(this);
  4944. return this;
  4945. };
  4946. /**
  4947. * Sets all the matrix elements to zero.
  4948. * Returns the Matrix.
  4949. */
  4950. Matrix.prototype.reset = function () {
  4951. for (var index = 0; index < 16; index++) {
  4952. this.m[index] = 0.0;
  4953. }
  4954. this._markAsUpdated();
  4955. return this;
  4956. };
  4957. /**
  4958. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4959. */
  4960. Matrix.prototype.add = function (other) {
  4961. var result = new Matrix();
  4962. this.addToRef(other, result);
  4963. return result;
  4964. };
  4965. /**
  4966. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4967. * Returns the Matrix.
  4968. */
  4969. Matrix.prototype.addToRef = function (other, result) {
  4970. for (var index = 0; index < 16; index++) {
  4971. result.m[index] = this.m[index] + other.m[index];
  4972. }
  4973. result._markAsUpdated();
  4974. return this;
  4975. };
  4976. /**
  4977. * Adds in place the passed matrix to the current Matrix.
  4978. * Returns the updated Matrix.
  4979. */
  4980. Matrix.prototype.addToSelf = function (other) {
  4981. for (var index = 0; index < 16; index++) {
  4982. this.m[index] += other.m[index];
  4983. }
  4984. this._markAsUpdated();
  4985. return this;
  4986. };
  4987. /**
  4988. * Sets the passed matrix with the current inverted Matrix.
  4989. * Returns the unmodified current Matrix.
  4990. */
  4991. Matrix.prototype.invertToRef = function (other) {
  4992. var l1 = this.m[0];
  4993. var l2 = this.m[1];
  4994. var l3 = this.m[2];
  4995. var l4 = this.m[3];
  4996. var l5 = this.m[4];
  4997. var l6 = this.m[5];
  4998. var l7 = this.m[6];
  4999. var l8 = this.m[7];
  5000. var l9 = this.m[8];
  5001. var l10 = this.m[9];
  5002. var l11 = this.m[10];
  5003. var l12 = this.m[11];
  5004. var l13 = this.m[12];
  5005. var l14 = this.m[13];
  5006. var l15 = this.m[14];
  5007. var l16 = this.m[15];
  5008. var l17 = (l11 * l16) - (l12 * l15);
  5009. var l18 = (l10 * l16) - (l12 * l14);
  5010. var l19 = (l10 * l15) - (l11 * l14);
  5011. var l20 = (l9 * l16) - (l12 * l13);
  5012. var l21 = (l9 * l15) - (l11 * l13);
  5013. var l22 = (l9 * l14) - (l10 * l13);
  5014. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5015. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5016. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5017. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5018. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5019. var l28 = (l7 * l16) - (l8 * l15);
  5020. var l29 = (l6 * l16) - (l8 * l14);
  5021. var l30 = (l6 * l15) - (l7 * l14);
  5022. var l31 = (l5 * l16) - (l8 * l13);
  5023. var l32 = (l5 * l15) - (l7 * l13);
  5024. var l33 = (l5 * l14) - (l6 * l13);
  5025. var l34 = (l7 * l12) - (l8 * l11);
  5026. var l35 = (l6 * l12) - (l8 * l10);
  5027. var l36 = (l6 * l11) - (l7 * l10);
  5028. var l37 = (l5 * l12) - (l8 * l9);
  5029. var l38 = (l5 * l11) - (l7 * l9);
  5030. var l39 = (l5 * l10) - (l6 * l9);
  5031. other.m[0] = l23 * l27;
  5032. other.m[4] = l24 * l27;
  5033. other.m[8] = l25 * l27;
  5034. other.m[12] = l26 * l27;
  5035. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5036. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5037. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5038. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5039. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5040. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5041. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5042. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5043. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5044. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5045. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5046. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5047. other._markAsUpdated();
  5048. return this;
  5049. };
  5050. /**
  5051. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  5052. * Returns the updated Matrix.
  5053. */
  5054. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5055. this.m[12] = x;
  5056. this.m[13] = y;
  5057. this.m[14] = z;
  5058. this._markAsUpdated();
  5059. return this;
  5060. };
  5061. /**
  5062. * Inserts the translation vector in the current Matrix.
  5063. * Returns the updated Matrix.
  5064. */
  5065. Matrix.prototype.setTranslation = function (vector3) {
  5066. this.m[12] = vector3.x;
  5067. this.m[13] = vector3.y;
  5068. this.m[14] = vector3.z;
  5069. this._markAsUpdated();
  5070. return this;
  5071. };
  5072. /**
  5073. * Returns a new Vector3 as the extracted translation from the Matrix.
  5074. */
  5075. Matrix.prototype.getTranslation = function () {
  5076. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5077. };
  5078. /**
  5079. * Fill a Vector3 with the extracted translation from the Matrix.
  5080. */
  5081. Matrix.prototype.getTranslationToRef = function (result) {
  5082. result.x = this.m[12];
  5083. result.y = this.m[13];
  5084. result.z = this.m[14];
  5085. return this;
  5086. };
  5087. /**
  5088. * Remove rotation and scaling part from the Matrix.
  5089. * Returns the updated Matrix.
  5090. */
  5091. Matrix.prototype.removeRotationAndScaling = function () {
  5092. this.setRowFromFloats(0, 1, 0, 0, 0);
  5093. this.setRowFromFloats(1, 0, 1, 0, 0);
  5094. this.setRowFromFloats(2, 0, 0, 1, 0);
  5095. return this;
  5096. };
  5097. /**
  5098. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  5099. */
  5100. Matrix.prototype.multiply = function (other) {
  5101. var result = new Matrix();
  5102. this.multiplyToRef(other, result);
  5103. return result;
  5104. };
  5105. /**
  5106. * Updates the current Matrix from the passed one values.
  5107. * Returns the updated Matrix.
  5108. */
  5109. Matrix.prototype.copyFrom = function (other) {
  5110. for (var index = 0; index < 16; index++) {
  5111. this.m[index] = other.m[index];
  5112. }
  5113. this._markAsUpdated();
  5114. return this;
  5115. };
  5116. /**
  5117. * Populates the passed array from the starting index with the Matrix values.
  5118. * Returns the Matrix.
  5119. */
  5120. Matrix.prototype.copyToArray = function (array, offset) {
  5121. if (offset === void 0) { offset = 0; }
  5122. for (var index = 0; index < 16; index++) {
  5123. array[offset + index] = this.m[index];
  5124. }
  5125. return this;
  5126. };
  5127. /**
  5128. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  5129. */
  5130. Matrix.prototype.multiplyToRef = function (other, result) {
  5131. this.multiplyToArray(other, result.m, 0);
  5132. result._markAsUpdated();
  5133. return this;
  5134. };
  5135. /**
  5136. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  5137. */
  5138. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5139. var tm0 = this.m[0];
  5140. var tm1 = this.m[1];
  5141. var tm2 = this.m[2];
  5142. var tm3 = this.m[3];
  5143. var tm4 = this.m[4];
  5144. var tm5 = this.m[5];
  5145. var tm6 = this.m[6];
  5146. var tm7 = this.m[7];
  5147. var tm8 = this.m[8];
  5148. var tm9 = this.m[9];
  5149. var tm10 = this.m[10];
  5150. var tm11 = this.m[11];
  5151. var tm12 = this.m[12];
  5152. var tm13 = this.m[13];
  5153. var tm14 = this.m[14];
  5154. var tm15 = this.m[15];
  5155. var om0 = other.m[0];
  5156. var om1 = other.m[1];
  5157. var om2 = other.m[2];
  5158. var om3 = other.m[3];
  5159. var om4 = other.m[4];
  5160. var om5 = other.m[5];
  5161. var om6 = other.m[6];
  5162. var om7 = other.m[7];
  5163. var om8 = other.m[8];
  5164. var om9 = other.m[9];
  5165. var om10 = other.m[10];
  5166. var om11 = other.m[11];
  5167. var om12 = other.m[12];
  5168. var om13 = other.m[13];
  5169. var om14 = other.m[14];
  5170. var om15 = other.m[15];
  5171. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5172. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5173. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5174. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5175. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5176. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5177. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5178. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5179. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5180. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5181. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5182. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5183. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5184. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5185. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5186. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5187. return this;
  5188. };
  5189. /**
  5190. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  5191. */
  5192. Matrix.prototype.equals = function (value) {
  5193. return value &&
  5194. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5195. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5196. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5197. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5198. };
  5199. /**
  5200. * Returns a new Matrix from the current Matrix.
  5201. */
  5202. Matrix.prototype.clone = function () {
  5203. 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]);
  5204. };
  5205. /**
  5206. * Returns the string "Matrix"
  5207. */
  5208. Matrix.prototype.getClassName = function () {
  5209. return "Matrix";
  5210. };
  5211. /**
  5212. * Returns the Matrix hash code.
  5213. */
  5214. Matrix.prototype.getHashCode = function () {
  5215. var hash = this.m[0] || 0;
  5216. for (var i = 1; i < 16; i++) {
  5217. hash = (hash * 397) ^ (this.m[i] || 0);
  5218. }
  5219. return hash;
  5220. };
  5221. /**
  5222. * Decomposes the current Matrix into :
  5223. * - a scale vector3 passed as a reference to update,
  5224. * - a rotation quaternion passed as a reference to update,
  5225. * - a translation vector3 passed as a reference to update.
  5226. * Returns the true if operation was successful.
  5227. */
  5228. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5229. translation.x = this.m[12];
  5230. translation.y = this.m[13];
  5231. translation.z = this.m[14];
  5232. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5233. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5234. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5235. if (this.determinant() <= 0) {
  5236. scale.y *= -1;
  5237. }
  5238. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5239. rotation.x = 0;
  5240. rotation.y = 0;
  5241. rotation.z = 0;
  5242. rotation.w = 1;
  5243. return false;
  5244. }
  5245. 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]);
  5246. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5247. return true;
  5248. };
  5249. /**
  5250. * Returns the index-th row of the current matrix as a new Vector4.
  5251. */
  5252. Matrix.prototype.getRow = function (index) {
  5253. if (index < 0 || index > 3) {
  5254. return null;
  5255. }
  5256. var i = index * 4;
  5257. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5258. };
  5259. /**
  5260. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5261. * Returns the updated Matrix.
  5262. */
  5263. Matrix.prototype.setRow = function (index, row) {
  5264. if (index < 0 || index > 3) {
  5265. return this;
  5266. }
  5267. var i = index * 4;
  5268. this.m[i + 0] = row.x;
  5269. this.m[i + 1] = row.y;
  5270. this.m[i + 2] = row.z;
  5271. this.m[i + 3] = row.w;
  5272. this._markAsUpdated();
  5273. return this;
  5274. };
  5275. /**
  5276. * Compute the transpose of the matrix.
  5277. * Returns a new Matrix.
  5278. */
  5279. Matrix.prototype.transpose = function () {
  5280. return Matrix.Transpose(this);
  5281. };
  5282. /**
  5283. * Compute the transpose of the matrix.
  5284. * Returns the current matrix.
  5285. */
  5286. Matrix.prototype.transposeToRef = function (result) {
  5287. Matrix.TransposeToRef(this, result);
  5288. return this;
  5289. };
  5290. /**
  5291. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5292. * Returns the updated Matrix.
  5293. */
  5294. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5295. if (index < 0 || index > 3) {
  5296. return this;
  5297. }
  5298. var i = index * 4;
  5299. this.m[i + 0] = x;
  5300. this.m[i + 1] = y;
  5301. this.m[i + 2] = z;
  5302. this.m[i + 3] = w;
  5303. this._markAsUpdated();
  5304. return this;
  5305. };
  5306. /**
  5307. * Compute a new Matrix set with the current Matrix values multiplied by scale (float)
  5308. * @param scale defines the scale factor
  5309. * @returns a new Matrix
  5310. */
  5311. Matrix.prototype.scale = function (scale) {
  5312. var result = new Matrix();
  5313. this.scaleToRef(scale, result);
  5314. return result;
  5315. };
  5316. /**
  5317. * Scale the current Matrix values by a factor to a given result Matrix
  5318. * @param scale defines the scale factor
  5319. * @param result defines the Matrix to store the result
  5320. * @returns the current Matrix
  5321. */
  5322. Matrix.prototype.scaleToRef = function (scale, result) {
  5323. for (var index = 0; index < 16; index++) {
  5324. result.m[index] = this.m[index] * scale;
  5325. }
  5326. result._markAsUpdated();
  5327. return this;
  5328. };
  5329. /**
  5330. * Scale the current Matrix values by a factor and add the result to a given Matrix
  5331. * @param scale defines the scale factor
  5332. * @param result defines the Matrix to store the result
  5333. * @returns the current Matrix
  5334. */
  5335. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5336. for (var index = 0; index < 16; index++) {
  5337. result.m[index] += this.m[index] * scale;
  5338. }
  5339. result._markAsUpdated();
  5340. return this;
  5341. };
  5342. /**
  5343. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5344. * @param ref matrix to store the result
  5345. */
  5346. Matrix.prototype.toNormalMatrix = function (ref) {
  5347. this.invertToRef(ref);
  5348. ref.transpose();
  5349. var m = ref.m;
  5350. 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);
  5351. };
  5352. /**
  5353. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5354. */
  5355. Matrix.prototype.getRotationMatrix = function () {
  5356. var result = Matrix.Identity();
  5357. this.getRotationMatrixToRef(result);
  5358. return result;
  5359. };
  5360. /**
  5361. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5362. * Returns the current Matrix.
  5363. */
  5364. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5365. var m = this.m;
  5366. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5367. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5368. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5369. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5370. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5371. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5372. 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);
  5373. return this;
  5374. };
  5375. // Statics
  5376. /**
  5377. * Returns a new Matrix set from the starting index of the passed array.
  5378. */
  5379. Matrix.FromArray = function (array, offset) {
  5380. var result = new Matrix();
  5381. if (!offset) {
  5382. offset = 0;
  5383. }
  5384. Matrix.FromArrayToRef(array, offset, result);
  5385. return result;
  5386. };
  5387. /**
  5388. * Sets the passed "result" matrix from the starting index of the passed array.
  5389. */
  5390. Matrix.FromArrayToRef = function (array, offset, result) {
  5391. for (var index = 0; index < 16; index++) {
  5392. result.m[index] = array[index + offset];
  5393. }
  5394. result._markAsUpdated();
  5395. };
  5396. /**
  5397. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5398. */
  5399. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5400. for (var index = 0; index < 16; index++) {
  5401. result.m[index] = array[index + offset] * scale;
  5402. }
  5403. result._markAsUpdated();
  5404. };
  5405. /**
  5406. * Sets the passed matrix "result" with the 16 passed floats.
  5407. */
  5408. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5409. result.m[0] = initialM11;
  5410. result.m[1] = initialM12;
  5411. result.m[2] = initialM13;
  5412. result.m[3] = initialM14;
  5413. result.m[4] = initialM21;
  5414. result.m[5] = initialM22;
  5415. result.m[6] = initialM23;
  5416. result.m[7] = initialM24;
  5417. result.m[8] = initialM31;
  5418. result.m[9] = initialM32;
  5419. result.m[10] = initialM33;
  5420. result.m[11] = initialM34;
  5421. result.m[12] = initialM41;
  5422. result.m[13] = initialM42;
  5423. result.m[14] = initialM43;
  5424. result.m[15] = initialM44;
  5425. result._markAsUpdated();
  5426. };
  5427. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5428. /**
  5429. * Static identity matrix to be used as readonly matrix
  5430. * Must not be updated.
  5431. */
  5432. get: function () {
  5433. return Matrix._identityReadOnly;
  5434. },
  5435. enumerable: true,
  5436. configurable: true
  5437. });
  5438. /**
  5439. * Returns a new Matrix set from the 16 passed floats.
  5440. */
  5441. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5442. var result = new Matrix();
  5443. result.m[0] = initialM11;
  5444. result.m[1] = initialM12;
  5445. result.m[2] = initialM13;
  5446. result.m[3] = initialM14;
  5447. result.m[4] = initialM21;
  5448. result.m[5] = initialM22;
  5449. result.m[6] = initialM23;
  5450. result.m[7] = initialM24;
  5451. result.m[8] = initialM31;
  5452. result.m[9] = initialM32;
  5453. result.m[10] = initialM33;
  5454. result.m[11] = initialM34;
  5455. result.m[12] = initialM41;
  5456. result.m[13] = initialM42;
  5457. result.m[14] = initialM43;
  5458. result.m[15] = initialM44;
  5459. return result;
  5460. };
  5461. /**
  5462. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5463. */
  5464. Matrix.Compose = function (scale, rotation, translation) {
  5465. var result = Matrix.Identity();
  5466. Matrix.ComposeToRef(scale, rotation, translation, result);
  5467. return result;
  5468. };
  5469. /**
  5470. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5471. */
  5472. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5473. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5474. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5475. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5476. result.setTranslation(translation);
  5477. };
  5478. /**
  5479. * Returns a new indentity Matrix.
  5480. */
  5481. Matrix.Identity = function () {
  5482. 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);
  5483. };
  5484. /**
  5485. * Sets the passed "result" as an identity matrix.
  5486. */
  5487. Matrix.IdentityToRef = function (result) {
  5488. 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);
  5489. };
  5490. /**
  5491. * Returns a new zero Matrix.
  5492. */
  5493. Matrix.Zero = function () {
  5494. 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);
  5495. };
  5496. /**
  5497. * Returns a new rotation matrix for "angle" radians around the X axis.
  5498. */
  5499. Matrix.RotationX = function (angle) {
  5500. var result = new Matrix();
  5501. Matrix.RotationXToRef(angle, result);
  5502. return result;
  5503. };
  5504. /**
  5505. * Returns a new Matrix as the passed inverted one.
  5506. */
  5507. Matrix.Invert = function (source) {
  5508. var result = new Matrix();
  5509. source.invertToRef(result);
  5510. return result;
  5511. };
  5512. /**
  5513. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5514. */
  5515. Matrix.RotationXToRef = function (angle, result) {
  5516. var s = Math.sin(angle);
  5517. var c = Math.cos(angle);
  5518. result.m[0] = 1.0;
  5519. result.m[15] = 1.0;
  5520. result.m[5] = c;
  5521. result.m[10] = c;
  5522. result.m[9] = -s;
  5523. result.m[6] = s;
  5524. result.m[1] = 0.0;
  5525. result.m[2] = 0.0;
  5526. result.m[3] = 0.0;
  5527. result.m[4] = 0.0;
  5528. result.m[7] = 0.0;
  5529. result.m[8] = 0.0;
  5530. result.m[11] = 0.0;
  5531. result.m[12] = 0.0;
  5532. result.m[13] = 0.0;
  5533. result.m[14] = 0.0;
  5534. result._markAsUpdated();
  5535. };
  5536. /**
  5537. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5538. */
  5539. Matrix.RotationY = function (angle) {
  5540. var result = new Matrix();
  5541. Matrix.RotationYToRef(angle, result);
  5542. return result;
  5543. };
  5544. /**
  5545. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5546. */
  5547. Matrix.RotationYToRef = function (angle, result) {
  5548. var s = Math.sin(angle);
  5549. var c = Math.cos(angle);
  5550. result.m[5] = 1.0;
  5551. result.m[15] = 1.0;
  5552. result.m[0] = c;
  5553. result.m[2] = -s;
  5554. result.m[8] = s;
  5555. result.m[10] = c;
  5556. result.m[1] = 0.0;
  5557. result.m[3] = 0.0;
  5558. result.m[4] = 0.0;
  5559. result.m[6] = 0.0;
  5560. result.m[7] = 0.0;
  5561. result.m[9] = 0.0;
  5562. result.m[11] = 0.0;
  5563. result.m[12] = 0.0;
  5564. result.m[13] = 0.0;
  5565. result.m[14] = 0.0;
  5566. result._markAsUpdated();
  5567. };
  5568. /**
  5569. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5570. */
  5571. Matrix.RotationZ = function (angle) {
  5572. var result = new Matrix();
  5573. Matrix.RotationZToRef(angle, result);
  5574. return result;
  5575. };
  5576. /**
  5577. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5578. */
  5579. Matrix.RotationZToRef = function (angle, result) {
  5580. var s = Math.sin(angle);
  5581. var c = Math.cos(angle);
  5582. result.m[10] = 1.0;
  5583. result.m[15] = 1.0;
  5584. result.m[0] = c;
  5585. result.m[1] = s;
  5586. result.m[4] = -s;
  5587. result.m[5] = c;
  5588. result.m[2] = 0.0;
  5589. result.m[3] = 0.0;
  5590. result.m[6] = 0.0;
  5591. result.m[7] = 0.0;
  5592. result.m[8] = 0.0;
  5593. result.m[9] = 0.0;
  5594. result.m[11] = 0.0;
  5595. result.m[12] = 0.0;
  5596. result.m[13] = 0.0;
  5597. result.m[14] = 0.0;
  5598. result._markAsUpdated();
  5599. };
  5600. /**
  5601. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5602. */
  5603. Matrix.RotationAxis = function (axis, angle) {
  5604. var result = Matrix.Zero();
  5605. Matrix.RotationAxisToRef(axis, angle, result);
  5606. return result;
  5607. };
  5608. /**
  5609. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5610. */
  5611. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5612. var s = Math.sin(-angle);
  5613. var c = Math.cos(-angle);
  5614. var c1 = 1 - c;
  5615. axis.normalize();
  5616. result.m[0] = (axis.x * axis.x) * c1 + c;
  5617. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5618. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5619. result.m[3] = 0.0;
  5620. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5621. result.m[5] = (axis.y * axis.y) * c1 + c;
  5622. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5623. result.m[7] = 0.0;
  5624. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5625. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5626. result.m[10] = (axis.z * axis.z) * c1 + c;
  5627. result.m[11] = 0.0;
  5628. result.m[15] = 1.0;
  5629. result._markAsUpdated();
  5630. };
  5631. /**
  5632. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5633. */
  5634. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5635. var result = new Matrix();
  5636. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5637. return result;
  5638. };
  5639. /**
  5640. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5641. */
  5642. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5643. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5644. this._tempQuaternion.toRotationMatrix(result);
  5645. };
  5646. /**
  5647. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5648. */
  5649. Matrix.Scaling = function (x, y, z) {
  5650. var result = Matrix.Zero();
  5651. Matrix.ScalingToRef(x, y, z, result);
  5652. return result;
  5653. };
  5654. /**
  5655. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5656. */
  5657. Matrix.ScalingToRef = function (x, y, z, result) {
  5658. result.m[0] = x;
  5659. result.m[1] = 0.0;
  5660. result.m[2] = 0.0;
  5661. result.m[3] = 0.0;
  5662. result.m[4] = 0.0;
  5663. result.m[5] = y;
  5664. result.m[6] = 0.0;
  5665. result.m[7] = 0.0;
  5666. result.m[8] = 0.0;
  5667. result.m[9] = 0.0;
  5668. result.m[10] = z;
  5669. result.m[11] = 0.0;
  5670. result.m[12] = 0.0;
  5671. result.m[13] = 0.0;
  5672. result.m[14] = 0.0;
  5673. result.m[15] = 1.0;
  5674. result._markAsUpdated();
  5675. };
  5676. /**
  5677. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5678. */
  5679. Matrix.Translation = function (x, y, z) {
  5680. var result = Matrix.Identity();
  5681. Matrix.TranslationToRef(x, y, z, result);
  5682. return result;
  5683. };
  5684. /**
  5685. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5686. */
  5687. Matrix.TranslationToRef = function (x, y, z, result) {
  5688. 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);
  5689. };
  5690. /**
  5691. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5692. * @param startValue defines the start value
  5693. * @param endValue defines the end value
  5694. * @param gradient defines the gradient factor
  5695. * @returns the new matrix
  5696. */
  5697. Matrix.Lerp = function (startValue, endValue, gradient) {
  5698. var result = Matrix.Zero();
  5699. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5700. return result;
  5701. };
  5702. /**
  5703. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5704. * @param startValue defines the start value
  5705. * @param endValue defines the end value
  5706. * @param gradient defines the gradient factor
  5707. * @param result defines the Matrix object where to store data
  5708. */
  5709. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5710. for (var index = 0; index < 16; index++) {
  5711. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5712. }
  5713. result._markAsUpdated();
  5714. };
  5715. /**
  5716. * Returns a new Matrix whose values are computed by :
  5717. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5718. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5719. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5720. */
  5721. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5722. var startScale = new Vector3(0, 0, 0);
  5723. var startRotation = new Quaternion();
  5724. var startTranslation = new Vector3(0, 0, 0);
  5725. startValue.decompose(startScale, startRotation, startTranslation);
  5726. var endScale = new Vector3(0, 0, 0);
  5727. var endRotation = new Quaternion();
  5728. var endTranslation = new Vector3(0, 0, 0);
  5729. endValue.decompose(endScale, endRotation, endTranslation);
  5730. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5731. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5732. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5733. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5734. };
  5735. /**
  5736. * 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".
  5737. * This methods works for a Left-Handed system.
  5738. */
  5739. Matrix.LookAtLH = function (eye, target, up) {
  5740. var result = Matrix.Zero();
  5741. Matrix.LookAtLHToRef(eye, target, up, result);
  5742. return result;
  5743. };
  5744. /**
  5745. * 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".
  5746. * This methods works for a Left-Handed system.
  5747. */
  5748. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5749. // Z axis
  5750. target.subtractToRef(eye, this._zAxis);
  5751. this._zAxis.normalize();
  5752. // X axis
  5753. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5754. if (this._xAxis.lengthSquared() === 0) {
  5755. this._xAxis.x = 1.0;
  5756. }
  5757. else {
  5758. this._xAxis.normalize();
  5759. }
  5760. // Y axis
  5761. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5762. this._yAxis.normalize();
  5763. // Eye angles
  5764. var ex = -Vector3.Dot(this._xAxis, eye);
  5765. var ey = -Vector3.Dot(this._yAxis, eye);
  5766. var ez = -Vector3.Dot(this._zAxis, eye);
  5767. 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);
  5768. };
  5769. /**
  5770. * 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".
  5771. * This methods works for a Right-Handed system.
  5772. */
  5773. Matrix.LookAtRH = function (eye, target, up) {
  5774. var result = Matrix.Zero();
  5775. Matrix.LookAtRHToRef(eye, target, up, result);
  5776. return result;
  5777. };
  5778. /**
  5779. * 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".
  5780. * This methods works for a Left-Handed system.
  5781. */
  5782. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5783. // Z axis
  5784. eye.subtractToRef(target, this._zAxis);
  5785. this._zAxis.normalize();
  5786. // X axis
  5787. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5788. if (this._xAxis.lengthSquared() === 0) {
  5789. this._xAxis.x = 1.0;
  5790. }
  5791. else {
  5792. this._xAxis.normalize();
  5793. }
  5794. // Y axis
  5795. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5796. this._yAxis.normalize();
  5797. // Eye angles
  5798. var ex = -Vector3.Dot(this._xAxis, eye);
  5799. var ey = -Vector3.Dot(this._yAxis, eye);
  5800. var ez = -Vector3.Dot(this._zAxis, eye);
  5801. 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);
  5802. };
  5803. /**
  5804. * 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.
  5805. */
  5806. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5807. var matrix = Matrix.Zero();
  5808. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5809. return matrix;
  5810. };
  5811. /**
  5812. * 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.
  5813. */
  5814. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5815. var n = znear;
  5816. var f = zfar;
  5817. var a = 2.0 / width;
  5818. var b = 2.0 / height;
  5819. var c = 2.0 / (f - n);
  5820. var d = -(f + n) / (f - n);
  5821. 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);
  5822. };
  5823. /**
  5824. * 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.
  5825. */
  5826. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5827. var matrix = Matrix.Zero();
  5828. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5829. return matrix;
  5830. };
  5831. /**
  5832. * 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.
  5833. */
  5834. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5835. var n = znear;
  5836. var f = zfar;
  5837. var a = 2.0 / (right - left);
  5838. var b = 2.0 / (top - bottom);
  5839. var c = 2.0 / (f - n);
  5840. var d = -(f + n) / (f - n);
  5841. var i0 = (left + right) / (left - right);
  5842. var i1 = (top + bottom) / (bottom - top);
  5843. 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);
  5844. };
  5845. /**
  5846. * 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.
  5847. */
  5848. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5849. var matrix = Matrix.Zero();
  5850. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5851. return matrix;
  5852. };
  5853. /**
  5854. * 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.
  5855. */
  5856. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5857. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5858. result.m[10] *= -1.0;
  5859. };
  5860. /**
  5861. * 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.
  5862. */
  5863. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5864. var matrix = Matrix.Zero();
  5865. var n = znear;
  5866. var f = zfar;
  5867. var a = 2.0 * n / width;
  5868. var b = 2.0 * n / height;
  5869. var c = (f + n) / (f - n);
  5870. var d = -2.0 * f * n / (f - n);
  5871. 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);
  5872. return matrix;
  5873. };
  5874. /**
  5875. * 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.
  5876. */
  5877. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5878. var matrix = Matrix.Zero();
  5879. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5880. return matrix;
  5881. };
  5882. /**
  5883. * 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.
  5884. */
  5885. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5886. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5887. var n = znear;
  5888. var f = zfar;
  5889. var t = 1.0 / (Math.tan(fov * 0.5));
  5890. var a = isVerticalFovFixed ? (t / aspect) : t;
  5891. var b = isVerticalFovFixed ? t : (t * aspect);
  5892. var c = (f + n) / (f - n);
  5893. var d = -2.0 * f * n / (f - n);
  5894. 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);
  5895. };
  5896. /**
  5897. * 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.
  5898. */
  5899. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5900. var matrix = Matrix.Zero();
  5901. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5902. return matrix;
  5903. };
  5904. /**
  5905. * 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.
  5906. */
  5907. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5908. //alternatively this could be expressed as:
  5909. // m = PerspectiveFovLHToRef
  5910. // m[10] *= -1.0;
  5911. // m[11] *= -1.0;
  5912. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5913. var n = znear;
  5914. var f = zfar;
  5915. var t = 1.0 / (Math.tan(fov * 0.5));
  5916. var a = isVerticalFovFixed ? (t / aspect) : t;
  5917. var b = isVerticalFovFixed ? t : (t * aspect);
  5918. var c = -(f + n) / (f - n);
  5919. var d = -2 * f * n / (f - n);
  5920. 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);
  5921. };
  5922. /**
  5923. * 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.
  5924. */
  5925. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5926. if (rightHanded === void 0) { rightHanded = false; }
  5927. var rightHandedFactor = rightHanded ? -1 : 1;
  5928. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5929. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5930. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5931. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5932. var xScale = 2.0 / (leftTan + rightTan);
  5933. var yScale = 2.0 / (upTan + downTan);
  5934. result.m[0] = xScale;
  5935. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5936. result.m[5] = yScale;
  5937. result.m[6] = result.m[7] = 0.0;
  5938. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5939. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5940. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5941. result.m[10] = -zfar / (znear - zfar);
  5942. result.m[11] = 1.0 * rightHandedFactor;
  5943. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5944. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5945. // result.m[14] = (znear * zfar) / (znear - zfar);
  5946. result._markAsUpdated();
  5947. };
  5948. /**
  5949. * Returns the final transformation matrix : world * view * projection * viewport
  5950. */
  5951. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5952. var cw = viewport.width;
  5953. var ch = viewport.height;
  5954. var cx = viewport.x;
  5955. var cy = viewport.y;
  5956. 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);
  5957. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5958. };
  5959. /**
  5960. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5961. */
  5962. Matrix.GetAsMatrix2x2 = function (matrix) {
  5963. return new Float32Array([
  5964. matrix.m[0], matrix.m[1],
  5965. matrix.m[4], matrix.m[5]
  5966. ]);
  5967. };
  5968. /**
  5969. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5970. */
  5971. Matrix.GetAsMatrix3x3 = function (matrix) {
  5972. return new Float32Array([
  5973. matrix.m[0], matrix.m[1], matrix.m[2],
  5974. matrix.m[4], matrix.m[5], matrix.m[6],
  5975. matrix.m[8], matrix.m[9], matrix.m[10]
  5976. ]);
  5977. };
  5978. /**
  5979. * Compute the transpose of the passed Matrix.
  5980. * Returns a new Matrix.
  5981. */
  5982. Matrix.Transpose = function (matrix) {
  5983. var result = new Matrix();
  5984. Matrix.TransposeToRef(matrix, result);
  5985. return result;
  5986. };
  5987. /**
  5988. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5989. */
  5990. Matrix.TransposeToRef = function (matrix, result) {
  5991. result.m[0] = matrix.m[0];
  5992. result.m[1] = matrix.m[4];
  5993. result.m[2] = matrix.m[8];
  5994. result.m[3] = matrix.m[12];
  5995. result.m[4] = matrix.m[1];
  5996. result.m[5] = matrix.m[5];
  5997. result.m[6] = matrix.m[9];
  5998. result.m[7] = matrix.m[13];
  5999. result.m[8] = matrix.m[2];
  6000. result.m[9] = matrix.m[6];
  6001. result.m[10] = matrix.m[10];
  6002. result.m[11] = matrix.m[14];
  6003. result.m[12] = matrix.m[3];
  6004. result.m[13] = matrix.m[7];
  6005. result.m[14] = matrix.m[11];
  6006. result.m[15] = matrix.m[15];
  6007. };
  6008. /**
  6009. * Returns a new Matrix as the reflection matrix across the passed plane.
  6010. */
  6011. Matrix.Reflection = function (plane) {
  6012. var matrix = new Matrix();
  6013. Matrix.ReflectionToRef(plane, matrix);
  6014. return matrix;
  6015. };
  6016. /**
  6017. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  6018. */
  6019. Matrix.ReflectionToRef = function (plane, result) {
  6020. plane.normalize();
  6021. var x = plane.normal.x;
  6022. var y = plane.normal.y;
  6023. var z = plane.normal.z;
  6024. var temp = -2 * x;
  6025. var temp2 = -2 * y;
  6026. var temp3 = -2 * z;
  6027. result.m[0] = (temp * x) + 1;
  6028. result.m[1] = temp2 * x;
  6029. result.m[2] = temp3 * x;
  6030. result.m[3] = 0.0;
  6031. result.m[4] = temp * y;
  6032. result.m[5] = (temp2 * y) + 1;
  6033. result.m[6] = temp3 * y;
  6034. result.m[7] = 0.0;
  6035. result.m[8] = temp * z;
  6036. result.m[9] = temp2 * z;
  6037. result.m[10] = (temp3 * z) + 1;
  6038. result.m[11] = 0.0;
  6039. result.m[12] = temp * plane.d;
  6040. result.m[13] = temp2 * plane.d;
  6041. result.m[14] = temp3 * plane.d;
  6042. result.m[15] = 1.0;
  6043. result._markAsUpdated();
  6044. };
  6045. /**
  6046. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  6047. */
  6048. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6049. result.m[0] = xaxis.x;
  6050. result.m[1] = xaxis.y;
  6051. result.m[2] = xaxis.z;
  6052. result.m[3] = 0.0;
  6053. result.m[4] = yaxis.x;
  6054. result.m[5] = yaxis.y;
  6055. result.m[6] = yaxis.z;
  6056. result.m[7] = 0.0;
  6057. result.m[8] = zaxis.x;
  6058. result.m[9] = zaxis.y;
  6059. result.m[10] = zaxis.z;
  6060. result.m[11] = 0.0;
  6061. result.m[12] = 0.0;
  6062. result.m[13] = 0.0;
  6063. result.m[14] = 0.0;
  6064. result.m[15] = 1.0;
  6065. result._markAsUpdated();
  6066. };
  6067. /**
  6068. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  6069. */
  6070. Matrix.FromQuaternionToRef = function (quat, result) {
  6071. var xx = quat.x * quat.x;
  6072. var yy = quat.y * quat.y;
  6073. var zz = quat.z * quat.z;
  6074. var xy = quat.x * quat.y;
  6075. var zw = quat.z * quat.w;
  6076. var zx = quat.z * quat.x;
  6077. var yw = quat.y * quat.w;
  6078. var yz = quat.y * quat.z;
  6079. var xw = quat.x * quat.w;
  6080. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6081. result.m[1] = 2.0 * (xy + zw);
  6082. result.m[2] = 2.0 * (zx - yw);
  6083. result.m[3] = 0.0;
  6084. result.m[4] = 2.0 * (xy - zw);
  6085. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6086. result.m[6] = 2.0 * (yz + xw);
  6087. result.m[7] = 0.0;
  6088. result.m[8] = 2.0 * (zx + yw);
  6089. result.m[9] = 2.0 * (yz - xw);
  6090. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6091. result.m[11] = 0.0;
  6092. result.m[12] = 0.0;
  6093. result.m[13] = 0.0;
  6094. result.m[14] = 0.0;
  6095. result.m[15] = 1.0;
  6096. result._markAsUpdated();
  6097. };
  6098. Matrix._tempQuaternion = new Quaternion();
  6099. Matrix._xAxis = Vector3.Zero();
  6100. Matrix._yAxis = Vector3.Zero();
  6101. Matrix._zAxis = Vector3.Zero();
  6102. Matrix._updateFlagSeed = 0;
  6103. Matrix._identityReadOnly = Matrix.Identity();
  6104. return Matrix;
  6105. }());
  6106. BABYLON.Matrix = Matrix;
  6107. var Plane = /** @class */ (function () {
  6108. /**
  6109. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6110. */
  6111. function Plane(a, b, c, d) {
  6112. this.normal = new Vector3(a, b, c);
  6113. this.d = d;
  6114. }
  6115. /**
  6116. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6117. */
  6118. Plane.prototype.asArray = function () {
  6119. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6120. };
  6121. // Methods
  6122. /**
  6123. * Returns a new plane copied from the current Plane.
  6124. */
  6125. Plane.prototype.clone = function () {
  6126. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6127. };
  6128. /**
  6129. * Returns the string "Plane".
  6130. */
  6131. Plane.prototype.getClassName = function () {
  6132. return "Plane";
  6133. };
  6134. /**
  6135. * Returns the Plane hash code.
  6136. */
  6137. Plane.prototype.getHashCode = function () {
  6138. var hash = this.normal.getHashCode();
  6139. hash = (hash * 397) ^ (this.d || 0);
  6140. return hash;
  6141. };
  6142. /**
  6143. * Normalize the current Plane in place.
  6144. * Returns the updated Plane.
  6145. */
  6146. Plane.prototype.normalize = function () {
  6147. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6148. var magnitude = 0.0;
  6149. if (norm !== 0) {
  6150. magnitude = 1.0 / norm;
  6151. }
  6152. this.normal.x *= magnitude;
  6153. this.normal.y *= magnitude;
  6154. this.normal.z *= magnitude;
  6155. this.d *= magnitude;
  6156. return this;
  6157. };
  6158. /**
  6159. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  6160. */
  6161. Plane.prototype.transform = function (transformation) {
  6162. var transposedMatrix = Matrix.Transpose(transformation);
  6163. var x = this.normal.x;
  6164. var y = this.normal.y;
  6165. var z = this.normal.z;
  6166. var d = this.d;
  6167. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6168. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6169. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6170. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6171. return new Plane(normalX, normalY, normalZ, finalD);
  6172. };
  6173. /**
  6174. * Returns the dot product (float) of the point coordinates and the plane normal.
  6175. */
  6176. Plane.prototype.dotCoordinate = function (point) {
  6177. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6178. };
  6179. /**
  6180. * Updates the current Plane from the plane defined by the three passed points.
  6181. * Returns the updated Plane.
  6182. */
  6183. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6184. var x1 = point2.x - point1.x;
  6185. var y1 = point2.y - point1.y;
  6186. var z1 = point2.z - point1.z;
  6187. var x2 = point3.x - point1.x;
  6188. var y2 = point3.y - point1.y;
  6189. var z2 = point3.z - point1.z;
  6190. var yz = (y1 * z2) - (z1 * y2);
  6191. var xz = (z1 * x2) - (x1 * z2);
  6192. var xy = (x1 * y2) - (y1 * x2);
  6193. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6194. var invPyth;
  6195. if (pyth !== 0) {
  6196. invPyth = 1.0 / pyth;
  6197. }
  6198. else {
  6199. invPyth = 0.0;
  6200. }
  6201. this.normal.x = yz * invPyth;
  6202. this.normal.y = xz * invPyth;
  6203. this.normal.z = xy * invPyth;
  6204. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6205. return this;
  6206. };
  6207. /**
  6208. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6209. */
  6210. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6211. var dot = Vector3.Dot(this.normal, direction);
  6212. return (dot <= epsilon);
  6213. };
  6214. /**
  6215. * Returns the signed distance (float) from the passed point to the Plane.
  6216. */
  6217. Plane.prototype.signedDistanceTo = function (point) {
  6218. return Vector3.Dot(point, this.normal) + this.d;
  6219. };
  6220. // Statics
  6221. /**
  6222. * Returns a new Plane from the passed array.
  6223. */
  6224. Plane.FromArray = function (array) {
  6225. return new Plane(array[0], array[1], array[2], array[3]);
  6226. };
  6227. /**
  6228. * Returns a new Plane defined by the three passed points.
  6229. */
  6230. Plane.FromPoints = function (point1, point2, point3) {
  6231. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6232. result.copyFromPoints(point1, point2, point3);
  6233. return result;
  6234. };
  6235. /**
  6236. * Returns a new Plane the normal vector to this plane at the passed origin point.
  6237. * Note : the vector "normal" is updated because normalized.
  6238. */
  6239. Plane.FromPositionAndNormal = function (origin, normal) {
  6240. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6241. normal.normalize();
  6242. result.normal = normal;
  6243. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6244. return result;
  6245. };
  6246. /**
  6247. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6248. */
  6249. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6250. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6251. return Vector3.Dot(point, normal) + d;
  6252. };
  6253. return Plane;
  6254. }());
  6255. BABYLON.Plane = Plane;
  6256. var Viewport = /** @class */ (function () {
  6257. /**
  6258. * Creates a Viewport object located at (x, y) and sized (width, height).
  6259. */
  6260. function Viewport(x, y, width, height) {
  6261. this.x = x;
  6262. this.y = y;
  6263. this.width = width;
  6264. this.height = height;
  6265. }
  6266. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6267. if (renderWidthOrEngine.getRenderWidth) {
  6268. var engine = renderWidthOrEngine;
  6269. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6270. }
  6271. var renderWidth = renderWidthOrEngine;
  6272. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6273. };
  6274. /**
  6275. * Returns a new Viewport copied from the current one.
  6276. */
  6277. Viewport.prototype.clone = function () {
  6278. return new Viewport(this.x, this.y, this.width, this.height);
  6279. };
  6280. return Viewport;
  6281. }());
  6282. BABYLON.Viewport = Viewport;
  6283. var Frustum = /** @class */ (function () {
  6284. function Frustum() {
  6285. }
  6286. /**
  6287. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6288. */
  6289. Frustum.GetPlanes = function (transform) {
  6290. var frustumPlanes = [];
  6291. for (var index = 0; index < 6; index++) {
  6292. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6293. }
  6294. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6295. return frustumPlanes;
  6296. };
  6297. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6298. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6299. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6300. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6301. frustumPlane.d = transform.m[15] + transform.m[14];
  6302. frustumPlane.normalize();
  6303. };
  6304. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6305. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6306. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6307. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6308. frustumPlane.d = transform.m[15] - transform.m[14];
  6309. frustumPlane.normalize();
  6310. };
  6311. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6312. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6313. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6314. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6315. frustumPlane.d = transform.m[15] + transform.m[12];
  6316. frustumPlane.normalize();
  6317. };
  6318. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6319. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6320. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6321. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6322. frustumPlane.d = transform.m[15] - transform.m[12];
  6323. frustumPlane.normalize();
  6324. };
  6325. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6326. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6327. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6328. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6329. frustumPlane.d = transform.m[15] - transform.m[13];
  6330. frustumPlane.normalize();
  6331. };
  6332. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6333. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6334. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6335. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6336. frustumPlane.d = transform.m[15] + transform.m[13];
  6337. frustumPlane.normalize();
  6338. };
  6339. /**
  6340. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6341. */
  6342. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6343. // Near
  6344. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6345. // Far
  6346. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6347. // Left
  6348. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6349. // Right
  6350. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6351. // Top
  6352. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6353. // Bottom
  6354. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6355. };
  6356. return Frustum;
  6357. }());
  6358. BABYLON.Frustum = Frustum;
  6359. var Space;
  6360. (function (Space) {
  6361. Space[Space["LOCAL"] = 0] = "LOCAL";
  6362. Space[Space["WORLD"] = 1] = "WORLD";
  6363. Space[Space["BONE"] = 2] = "BONE";
  6364. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6365. var Axis = /** @class */ (function () {
  6366. function Axis() {
  6367. }
  6368. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6369. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6370. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6371. return Axis;
  6372. }());
  6373. BABYLON.Axis = Axis;
  6374. ;
  6375. var BezierCurve = /** @class */ (function () {
  6376. function BezierCurve() {
  6377. }
  6378. /**
  6379. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6380. */
  6381. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6382. // Extract X (which is equal to time here)
  6383. var f0 = 1 - 3 * x2 + 3 * x1;
  6384. var f1 = 3 * x2 - 6 * x1;
  6385. var f2 = 3 * x1;
  6386. var refinedT = t;
  6387. for (var i = 0; i < 5; i++) {
  6388. var refinedT2 = refinedT * refinedT;
  6389. var refinedT3 = refinedT2 * refinedT;
  6390. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6391. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6392. refinedT -= (x - t) * slope;
  6393. refinedT = Math.min(1, Math.max(0, refinedT));
  6394. }
  6395. // Resolve cubic bezier for the given x
  6396. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6397. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6398. Math.pow(refinedT, 3);
  6399. };
  6400. return BezierCurve;
  6401. }());
  6402. BABYLON.BezierCurve = BezierCurve;
  6403. var Orientation;
  6404. (function (Orientation) {
  6405. Orientation[Orientation["CW"] = 0] = "CW";
  6406. Orientation[Orientation["CCW"] = 1] = "CCW";
  6407. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6408. var Angle = /** @class */ (function () {
  6409. /**
  6410. * Creates an Angle object of "radians" radians (float).
  6411. */
  6412. function Angle(radians) {
  6413. var _this = this;
  6414. /**
  6415. * Returns the Angle value in degrees (float).
  6416. */
  6417. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6418. /**
  6419. * Returns the Angle value in radians (float).
  6420. */
  6421. this.radians = function () { return _this._radians; };
  6422. this._radians = radians;
  6423. if (this._radians < 0.0)
  6424. this._radians += (2.0 * Math.PI);
  6425. }
  6426. /**
  6427. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6428. */
  6429. Angle.BetweenTwoPoints = function (a, b) {
  6430. var delta = b.subtract(a);
  6431. var theta = Math.atan2(delta.y, delta.x);
  6432. return new Angle(theta);
  6433. };
  6434. /**
  6435. * Returns a new Angle object from the passed float in radians.
  6436. */
  6437. Angle.FromRadians = function (radians) {
  6438. return new Angle(radians);
  6439. };
  6440. /**
  6441. * Returns a new Angle object from the passed float in degrees.
  6442. */
  6443. Angle.FromDegrees = function (degrees) {
  6444. return new Angle(degrees * Math.PI / 180.0);
  6445. };
  6446. return Angle;
  6447. }());
  6448. BABYLON.Angle = Angle;
  6449. var Arc2 = /** @class */ (function () {
  6450. /**
  6451. * Creates an Arc object from the three passed points : start, middle and end.
  6452. */
  6453. function Arc2(startPoint, midPoint, endPoint) {
  6454. this.startPoint = startPoint;
  6455. this.midPoint = midPoint;
  6456. this.endPoint = endPoint;
  6457. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6458. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6459. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6460. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6461. 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);
  6462. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6463. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6464. var a1 = this.startAngle.degrees();
  6465. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6466. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6467. // angles correction
  6468. if (a2 - a1 > +180.0)
  6469. a2 -= 360.0;
  6470. if (a2 - a1 < -180.0)
  6471. a2 += 360.0;
  6472. if (a3 - a2 > +180.0)
  6473. a3 -= 360.0;
  6474. if (a3 - a2 < -180.0)
  6475. a3 += 360.0;
  6476. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6477. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6478. }
  6479. return Arc2;
  6480. }());
  6481. BABYLON.Arc2 = Arc2;
  6482. var Path2 = /** @class */ (function () {
  6483. /**
  6484. * Creates a Path2 object from the starting 2D coordinates x and y.
  6485. */
  6486. function Path2(x, y) {
  6487. this._points = new Array();
  6488. this._length = 0.0;
  6489. this.closed = false;
  6490. this._points.push(new Vector2(x, y));
  6491. }
  6492. /**
  6493. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6494. * Returns the updated Path2.
  6495. */
  6496. Path2.prototype.addLineTo = function (x, y) {
  6497. if (this.closed) {
  6498. return this;
  6499. }
  6500. var newPoint = new Vector2(x, y);
  6501. var previousPoint = this._points[this._points.length - 1];
  6502. this._points.push(newPoint);
  6503. this._length += newPoint.subtract(previousPoint).length();
  6504. return this;
  6505. };
  6506. /**
  6507. * 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.
  6508. * Returns the updated Path2.
  6509. */
  6510. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6511. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6512. if (this.closed) {
  6513. return this;
  6514. }
  6515. var startPoint = this._points[this._points.length - 1];
  6516. var midPoint = new Vector2(midX, midY);
  6517. var endPoint = new Vector2(endX, endY);
  6518. var arc = new Arc2(startPoint, midPoint, endPoint);
  6519. var increment = arc.angle.radians() / numberOfSegments;
  6520. if (arc.orientation === Orientation.CW)
  6521. increment *= -1;
  6522. var currentAngle = arc.startAngle.radians() + increment;
  6523. for (var i = 0; i < numberOfSegments; i++) {
  6524. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6525. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6526. this.addLineTo(x, y);
  6527. currentAngle += increment;
  6528. }
  6529. return this;
  6530. };
  6531. /**
  6532. * Closes the Path2.
  6533. * Returns the Path2.
  6534. */
  6535. Path2.prototype.close = function () {
  6536. this.closed = true;
  6537. return this;
  6538. };
  6539. /**
  6540. * Returns the Path2 total length (float).
  6541. */
  6542. Path2.prototype.length = function () {
  6543. var result = this._length;
  6544. if (!this.closed) {
  6545. var lastPoint = this._points[this._points.length - 1];
  6546. var firstPoint = this._points[0];
  6547. result += (firstPoint.subtract(lastPoint).length());
  6548. }
  6549. return result;
  6550. };
  6551. /**
  6552. * Returns the Path2 internal array of points.
  6553. */
  6554. Path2.prototype.getPoints = function () {
  6555. return this._points;
  6556. };
  6557. /**
  6558. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6559. */
  6560. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6561. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6562. return Vector2.Zero();
  6563. }
  6564. var lengthPosition = normalizedLengthPosition * this.length();
  6565. var previousOffset = 0;
  6566. for (var i = 0; i < this._points.length; i++) {
  6567. var j = (i + 1) % this._points.length;
  6568. var a = this._points[i];
  6569. var b = this._points[j];
  6570. var bToA = b.subtract(a);
  6571. var nextOffset = (bToA.length() + previousOffset);
  6572. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6573. var dir = bToA.normalize();
  6574. var localOffset = lengthPosition - previousOffset;
  6575. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6576. }
  6577. previousOffset = nextOffset;
  6578. }
  6579. return Vector2.Zero();
  6580. };
  6581. /**
  6582. * Returns a new Path2 starting at the coordinates (x, y).
  6583. */
  6584. Path2.StartingAt = function (x, y) {
  6585. return new Path2(x, y);
  6586. };
  6587. return Path2;
  6588. }());
  6589. BABYLON.Path2 = Path2;
  6590. var Path3D = /** @class */ (function () {
  6591. /**
  6592. * new Path3D(path, normal, raw)
  6593. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6594. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6595. * path : an array of Vector3, the curve axis of the Path3D
  6596. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6597. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6598. */
  6599. function Path3D(path, firstNormal, raw) {
  6600. if (firstNormal === void 0) { firstNormal = null; }
  6601. this.path = path;
  6602. this._curve = new Array();
  6603. this._distances = new Array();
  6604. this._tangents = new Array();
  6605. this._normals = new Array();
  6606. this._binormals = new Array();
  6607. for (var p = 0; p < path.length; p++) {
  6608. this._curve[p] = path[p].clone(); // hard copy
  6609. }
  6610. this._raw = raw || false;
  6611. this._compute(firstNormal);
  6612. }
  6613. /**
  6614. * Returns the Path3D array of successive Vector3 designing its curve.
  6615. */
  6616. Path3D.prototype.getCurve = function () {
  6617. return this._curve;
  6618. };
  6619. /**
  6620. * Returns an array populated with tangent vectors on each Path3D curve point.
  6621. */
  6622. Path3D.prototype.getTangents = function () {
  6623. return this._tangents;
  6624. };
  6625. /**
  6626. * Returns an array populated with normal vectors on each Path3D curve point.
  6627. */
  6628. Path3D.prototype.getNormals = function () {
  6629. return this._normals;
  6630. };
  6631. /**
  6632. * Returns an array populated with binormal vectors on each Path3D curve point.
  6633. */
  6634. Path3D.prototype.getBinormals = function () {
  6635. return this._binormals;
  6636. };
  6637. /**
  6638. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6639. */
  6640. Path3D.prototype.getDistances = function () {
  6641. return this._distances;
  6642. };
  6643. /**
  6644. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6645. * Returns the same object updated.
  6646. */
  6647. Path3D.prototype.update = function (path, firstNormal) {
  6648. if (firstNormal === void 0) { firstNormal = null; }
  6649. for (var p = 0; p < path.length; p++) {
  6650. this._curve[p].x = path[p].x;
  6651. this._curve[p].y = path[p].y;
  6652. this._curve[p].z = path[p].z;
  6653. }
  6654. this._compute(firstNormal);
  6655. return this;
  6656. };
  6657. // private function compute() : computes tangents, normals and binormals
  6658. Path3D.prototype._compute = function (firstNormal) {
  6659. var l = this._curve.length;
  6660. // first and last tangents
  6661. this._tangents[0] = this._getFirstNonNullVector(0);
  6662. if (!this._raw) {
  6663. this._tangents[0].normalize();
  6664. }
  6665. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6666. if (!this._raw) {
  6667. this._tangents[l - 1].normalize();
  6668. }
  6669. // normals and binormals at first point : arbitrary vector with _normalVector()
  6670. var tg0 = this._tangents[0];
  6671. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6672. this._normals[0] = pp0;
  6673. if (!this._raw) {
  6674. this._normals[0].normalize();
  6675. }
  6676. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6677. if (!this._raw) {
  6678. this._binormals[0].normalize();
  6679. }
  6680. this._distances[0] = 0.0;
  6681. // normals and binormals : next points
  6682. var prev; // previous vector (segment)
  6683. var cur; // current vector (segment)
  6684. var curTang; // current tangent
  6685. // previous normal
  6686. var prevBinor; // previous binormal
  6687. for (var i = 1; i < l; i++) {
  6688. // tangents
  6689. prev = this._getLastNonNullVector(i);
  6690. if (i < l - 1) {
  6691. cur = this._getFirstNonNullVector(i);
  6692. this._tangents[i] = prev.add(cur);
  6693. this._tangents[i].normalize();
  6694. }
  6695. this._distances[i] = this._distances[i - 1] + prev.length();
  6696. // normals and binormals
  6697. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6698. curTang = this._tangents[i];
  6699. prevBinor = this._binormals[i - 1];
  6700. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6701. if (!this._raw) {
  6702. this._normals[i].normalize();
  6703. }
  6704. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6705. if (!this._raw) {
  6706. this._binormals[i].normalize();
  6707. }
  6708. }
  6709. };
  6710. // private function getFirstNonNullVector(index)
  6711. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6712. Path3D.prototype._getFirstNonNullVector = function (index) {
  6713. var i = 1;
  6714. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6715. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6716. i++;
  6717. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6718. }
  6719. return nNVector;
  6720. };
  6721. // private function getLastNonNullVector(index)
  6722. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6723. Path3D.prototype._getLastNonNullVector = function (index) {
  6724. var i = 1;
  6725. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6726. while (nLVector.length() === 0 && index > i + 1) {
  6727. i++;
  6728. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6729. }
  6730. return nLVector;
  6731. };
  6732. // private function normalVector(v0, vt, va) :
  6733. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6734. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6735. Path3D.prototype._normalVector = function (v0, vt, va) {
  6736. var normal0;
  6737. var tgl = vt.length();
  6738. if (tgl === 0.0) {
  6739. tgl = 1.0;
  6740. }
  6741. if (va === undefined || va === null) {
  6742. var point;
  6743. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6744. point = new Vector3(0.0, -1.0, 0.0);
  6745. }
  6746. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6747. point = new Vector3(1.0, 0.0, 0.0);
  6748. }
  6749. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6750. point = new Vector3(0.0, 0.0, 1.0);
  6751. }
  6752. else {
  6753. point = Vector3.Zero();
  6754. }
  6755. normal0 = Vector3.Cross(vt, point);
  6756. }
  6757. else {
  6758. normal0 = Vector3.Cross(vt, va);
  6759. Vector3.CrossToRef(normal0, vt, normal0);
  6760. }
  6761. normal0.normalize();
  6762. return normal0;
  6763. };
  6764. return Path3D;
  6765. }());
  6766. BABYLON.Path3D = Path3D;
  6767. var Curve3 = /** @class */ (function () {
  6768. /**
  6769. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6770. * A Curve3 is designed from a series of successive Vector3.
  6771. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6772. */
  6773. function Curve3(points) {
  6774. this._length = 0.0;
  6775. this._points = points;
  6776. this._length = this._computeLength(points);
  6777. }
  6778. /**
  6779. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6780. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6781. * @param v1 (Vector3) the control point
  6782. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6783. * @param nbPoints (integer) the wanted number of points in the curve
  6784. */
  6785. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6786. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6787. var bez = new Array();
  6788. var equation = function (t, val0, val1, val2) {
  6789. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6790. return res;
  6791. };
  6792. for (var i = 0; i <= nbPoints; i++) {
  6793. 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)));
  6794. }
  6795. return new Curve3(bez);
  6796. };
  6797. /**
  6798. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6799. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6800. * @param v1 (Vector3) the first control point
  6801. * @param v2 (Vector3) the second control point
  6802. * @param v3 (Vector3) the end point of the Cubic Bezier
  6803. * @param nbPoints (integer) the wanted number of points in the curve
  6804. */
  6805. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6806. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6807. var bez = new Array();
  6808. var equation = function (t, val0, val1, val2, val3) {
  6809. 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;
  6810. return res;
  6811. };
  6812. for (var i = 0; i <= nbPoints; i++) {
  6813. 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)));
  6814. }
  6815. return new Curve3(bez);
  6816. };
  6817. /**
  6818. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6819. * @param p1 (Vector3) the origin point of the Hermite Spline
  6820. * @param t1 (Vector3) the tangent vector at the origin point
  6821. * @param p2 (Vector3) the end point of the Hermite Spline
  6822. * @param t2 (Vector3) the tangent vector at the end point
  6823. * @param nbPoints (integer) the wanted number of points in the curve
  6824. */
  6825. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6826. var hermite = new Array();
  6827. var step = 1.0 / nbPoints;
  6828. for (var i = 0; i <= nbPoints; i++) {
  6829. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6830. }
  6831. return new Curve3(hermite);
  6832. };
  6833. /**
  6834. * Returns a Curve3 object along a CatmullRom Spline curve :
  6835. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6836. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6837. */
  6838. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6839. var totalPoints = new Array();
  6840. totalPoints.push(points[0].clone());
  6841. Array.prototype.push.apply(totalPoints, points);
  6842. totalPoints.push(points[points.length - 1].clone());
  6843. var catmullRom = new Array();
  6844. var step = 1.0 / nbPoints;
  6845. var amount = 0.0;
  6846. for (var i = 0; i < totalPoints.length - 3; i++) {
  6847. amount = 0;
  6848. for (var c = 0; c < nbPoints; c++) {
  6849. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6850. amount += step;
  6851. }
  6852. }
  6853. i--;
  6854. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6855. return new Curve3(catmullRom);
  6856. };
  6857. /**
  6858. * Returns the Curve3 stored array of successive Vector3
  6859. */
  6860. Curve3.prototype.getPoints = function () {
  6861. return this._points;
  6862. };
  6863. /**
  6864. * Returns the computed length (float) of the curve.
  6865. */
  6866. Curve3.prototype.length = function () {
  6867. return this._length;
  6868. };
  6869. /**
  6870. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6871. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6872. * curveA and curveB keep unchanged.
  6873. */
  6874. Curve3.prototype.continue = function (curve) {
  6875. var lastPoint = this._points[this._points.length - 1];
  6876. var continuedPoints = this._points.slice();
  6877. var curvePoints = curve.getPoints();
  6878. for (var i = 1; i < curvePoints.length; i++) {
  6879. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6880. }
  6881. var continuedCurve = new Curve3(continuedPoints);
  6882. return continuedCurve;
  6883. };
  6884. Curve3.prototype._computeLength = function (path) {
  6885. var l = 0;
  6886. for (var i = 1; i < path.length; i++) {
  6887. l += (path[i].subtract(path[i - 1])).length();
  6888. }
  6889. return l;
  6890. };
  6891. return Curve3;
  6892. }());
  6893. BABYLON.Curve3 = Curve3;
  6894. // Vertex formats
  6895. var PositionNormalVertex = /** @class */ (function () {
  6896. function PositionNormalVertex(position, normal) {
  6897. if (position === void 0) { position = Vector3.Zero(); }
  6898. if (normal === void 0) { normal = Vector3.Up(); }
  6899. this.position = position;
  6900. this.normal = normal;
  6901. }
  6902. PositionNormalVertex.prototype.clone = function () {
  6903. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6904. };
  6905. return PositionNormalVertex;
  6906. }());
  6907. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6908. var PositionNormalTextureVertex = /** @class */ (function () {
  6909. function PositionNormalTextureVertex(position, normal, uv) {
  6910. if (position === void 0) { position = Vector3.Zero(); }
  6911. if (normal === void 0) { normal = Vector3.Up(); }
  6912. if (uv === void 0) { uv = Vector2.Zero(); }
  6913. this.position = position;
  6914. this.normal = normal;
  6915. this.uv = uv;
  6916. }
  6917. PositionNormalTextureVertex.prototype.clone = function () {
  6918. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6919. };
  6920. return PositionNormalTextureVertex;
  6921. }());
  6922. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6923. // Temporary pre-allocated objects for engine internal use
  6924. // usage in any internal function :
  6925. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6926. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6927. var Tmp = /** @class */ (function () {
  6928. function Tmp() {
  6929. }
  6930. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6931. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6932. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6933. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6934. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6935. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6936. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6937. Matrix.Zero(), Matrix.Zero(),
  6938. Matrix.Zero(), Matrix.Zero(),
  6939. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6940. return Tmp;
  6941. }());
  6942. BABYLON.Tmp = Tmp;
  6943. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6944. var MathTmp = /** @class */ (function () {
  6945. function MathTmp() {
  6946. }
  6947. MathTmp.Vector3 = [Vector3.Zero()];
  6948. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6949. MathTmp.Quaternion = [Quaternion.Zero()];
  6950. return MathTmp;
  6951. }());
  6952. })(BABYLON || (BABYLON = {}));
  6953. //# sourceMappingURL=babylon.math.js.map
  6954. "use strict";
  6955. var BABYLON;
  6956. (function (BABYLON) {
  6957. var Scalar = /** @class */ (function () {
  6958. function Scalar() {
  6959. }
  6960. /**
  6961. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6962. */
  6963. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6964. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6965. var num = a - b;
  6966. return -epsilon <= num && num <= epsilon;
  6967. };
  6968. /**
  6969. * Returns a string : the upper case translation of the number i to hexadecimal.
  6970. */
  6971. Scalar.ToHex = function (i) {
  6972. var str = i.toString(16);
  6973. if (i <= 15) {
  6974. return ("0" + str).toUpperCase();
  6975. }
  6976. return str.toUpperCase();
  6977. };
  6978. /**
  6979. * Returns -1 if value is negative and +1 is value is positive.
  6980. * Returns the value itself if it's equal to zero.
  6981. */
  6982. Scalar.Sign = function (value) {
  6983. value = +value; // convert to a number
  6984. if (value === 0 || isNaN(value))
  6985. return value;
  6986. return value > 0 ? 1 : -1;
  6987. };
  6988. /**
  6989. * Returns the value itself if it's between min and max.
  6990. * Returns min if the value is lower than min.
  6991. * Returns max if the value is greater than max.
  6992. */
  6993. Scalar.Clamp = function (value, min, max) {
  6994. if (min === void 0) { min = 0; }
  6995. if (max === void 0) { max = 1; }
  6996. return Math.min(max, Math.max(min, value));
  6997. };
  6998. /**
  6999. * Returns the log2 of value.
  7000. */
  7001. Scalar.Log2 = function (value) {
  7002. return Math.log(value) * Math.LOG2E;
  7003. };
  7004. /**
  7005. * Loops the value, so that it is never larger than length and never smaller than 0.
  7006. *
  7007. * This is similar to the modulo operator but it works with floating point numbers.
  7008. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7009. * With t = 5 and length = 2.5, the result would be 0.0.
  7010. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7011. */
  7012. Scalar.Repeat = function (value, length) {
  7013. return value - Math.floor(value / length) * length;
  7014. };
  7015. /**
  7016. * Normalize the value between 0.0 and 1.0 using min and max values
  7017. */
  7018. Scalar.Normalize = function (value, min, max) {
  7019. return (value - min) / (max - min);
  7020. };
  7021. /**
  7022. * Denormalize the value from 0.0 and 1.0 using min and max values
  7023. */
  7024. Scalar.Denormalize = function (normalized, min, max) {
  7025. return (normalized * (max - min) + min);
  7026. };
  7027. /**
  7028. * Calculates the shortest difference between two given angles given in degrees.
  7029. */
  7030. Scalar.DeltaAngle = function (current, target) {
  7031. var num = Scalar.Repeat(target - current, 360.0);
  7032. if (num > 180.0) {
  7033. num -= 360.0;
  7034. }
  7035. return num;
  7036. };
  7037. /**
  7038. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7039. *
  7040. * The returned value will move back and forth between 0 and length
  7041. */
  7042. Scalar.PingPong = function (tx, length) {
  7043. var t = Scalar.Repeat(tx, length * 2.0);
  7044. return length - Math.abs(t - length);
  7045. };
  7046. /**
  7047. * Interpolates between min and max with smoothing at the limits.
  7048. *
  7049. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7050. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7051. */
  7052. Scalar.SmoothStep = function (from, to, tx) {
  7053. var t = Scalar.Clamp(tx);
  7054. t = -2.0 * t * t * t + 3.0 * t * t;
  7055. return to * t + from * (1.0 - t);
  7056. };
  7057. /**
  7058. * Moves a value current towards target.
  7059. *
  7060. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7061. * Negative values of maxDelta pushes the value away from target.
  7062. */
  7063. Scalar.MoveTowards = function (current, target, maxDelta) {
  7064. var result = 0;
  7065. if (Math.abs(target - current) <= maxDelta) {
  7066. result = target;
  7067. }
  7068. else {
  7069. result = current + Scalar.Sign(target - current) * maxDelta;
  7070. }
  7071. return result;
  7072. };
  7073. /**
  7074. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7075. *
  7076. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7077. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7078. */
  7079. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7080. var num = Scalar.DeltaAngle(current, target);
  7081. var result = 0;
  7082. if (-maxDelta < num && num < maxDelta) {
  7083. result = target;
  7084. }
  7085. else {
  7086. target = current + num;
  7087. result = Scalar.MoveTowards(current, target, maxDelta);
  7088. }
  7089. return result;
  7090. };
  7091. /**
  7092. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7093. */
  7094. Scalar.Lerp = function (start, end, amount) {
  7095. return start + ((end - start) * amount);
  7096. };
  7097. /**
  7098. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7099. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7100. */
  7101. Scalar.LerpAngle = function (start, end, amount) {
  7102. var num = Scalar.Repeat(end - start, 360.0);
  7103. if (num > 180.0) {
  7104. num -= 360.0;
  7105. }
  7106. return start + num * Scalar.Clamp(amount);
  7107. };
  7108. /**
  7109. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7110. */
  7111. Scalar.InverseLerp = function (a, b, value) {
  7112. var result = 0;
  7113. if (a != b) {
  7114. result = Scalar.Clamp((value - a) / (b - a));
  7115. }
  7116. else {
  7117. result = 0.0;
  7118. }
  7119. return result;
  7120. };
  7121. /**
  7122. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7123. */
  7124. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7125. var squared = amount * amount;
  7126. var cubed = amount * squared;
  7127. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7128. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7129. var part3 = (cubed - (2.0 * squared)) + amount;
  7130. var part4 = cubed - squared;
  7131. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7132. };
  7133. /**
  7134. * Returns a random float number between and min and max values
  7135. */
  7136. Scalar.RandomRange = function (min, max) {
  7137. if (min === max)
  7138. return min;
  7139. return ((Math.random() * (max - min)) + min);
  7140. };
  7141. /**
  7142. * This function returns percentage of a number in a given range.
  7143. *
  7144. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7145. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7146. */
  7147. Scalar.RangeToPercent = function (number, min, max) {
  7148. return ((number - min) / (max - min));
  7149. };
  7150. /**
  7151. * This function returns number that corresponds to the percentage in a given range.
  7152. *
  7153. * PercentToRange(0.34,0,100) will return 34.
  7154. */
  7155. Scalar.PercentToRange = function (percent, min, max) {
  7156. return ((max - min) * percent + min);
  7157. };
  7158. /**
  7159. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7160. * @param angle The angle to normalize in radian.
  7161. * @return The converted angle.
  7162. */
  7163. Scalar.NormalizeRadians = function (angle) {
  7164. // More precise but slower version kept for reference.
  7165. // angle = angle % Tools.TwoPi;
  7166. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7167. //if (angle > Math.PI) {
  7168. // angle -= Tools.TwoPi;
  7169. //}
  7170. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7171. return angle;
  7172. };
  7173. /**
  7174. * Two pi constants convenient for computation.
  7175. */
  7176. Scalar.TwoPi = Math.PI * 2;
  7177. return Scalar;
  7178. }());
  7179. BABYLON.Scalar = Scalar;
  7180. })(BABYLON || (BABYLON = {}));
  7181. //# sourceMappingURL=babylon.math.scalar.js.map
  7182. "use strict";
  7183. //# sourceMappingURL=babylon.mixins.js.map
  7184. "use strict";
  7185. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7186. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7187. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7188. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7189. //# sourceMappingURL=babylon.webgl2.js.map
  7190. "use strict";
  7191. var BABYLON;
  7192. (function (BABYLON) {
  7193. var __decoratorInitialStore = {};
  7194. var __mergedStore = {};
  7195. var _copySource = function (creationFunction, source, instanciate) {
  7196. var destination = creationFunction();
  7197. // Tags
  7198. if (BABYLON.Tags) {
  7199. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7200. }
  7201. var classStore = getMergedStore(destination);
  7202. // Properties
  7203. for (var property in classStore) {
  7204. var propertyDescriptor = classStore[property];
  7205. var sourceProperty = source[property];
  7206. var propertyType = propertyDescriptor.type;
  7207. if (sourceProperty !== undefined && sourceProperty !== null) {
  7208. switch (propertyType) {
  7209. case 0: // Value
  7210. case 6:// Mesh reference
  7211. destination[property] = sourceProperty;
  7212. break;
  7213. case 1:// Texture
  7214. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7215. break;
  7216. case 2: // Color3
  7217. case 3: // FresnelParameters
  7218. case 4: // Vector2
  7219. case 5: // Vector3
  7220. case 7: // Color Curves
  7221. case 10:// Quaternion
  7222. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7223. break;
  7224. }
  7225. }
  7226. }
  7227. return destination;
  7228. };
  7229. function getDirectStore(target) {
  7230. var classKey = target.getClassName();
  7231. if (!__decoratorInitialStore[classKey]) {
  7232. __decoratorInitialStore[classKey] = {};
  7233. }
  7234. return __decoratorInitialStore[classKey];
  7235. }
  7236. /**
  7237. * Return the list of properties flagged as serializable
  7238. * @param target: host object
  7239. */
  7240. function getMergedStore(target) {
  7241. var classKey = target.getClassName();
  7242. if (__mergedStore[classKey]) {
  7243. return __mergedStore[classKey];
  7244. }
  7245. __mergedStore[classKey] = {};
  7246. var store = __mergedStore[classKey];
  7247. var currentTarget = target;
  7248. var currentKey = classKey;
  7249. while (currentKey) {
  7250. var initialStore = __decoratorInitialStore[currentKey];
  7251. for (var property in initialStore) {
  7252. store[property] = initialStore[property];
  7253. }
  7254. var parent_1 = void 0;
  7255. var done = false;
  7256. do {
  7257. parent_1 = Object.getPrototypeOf(currentTarget);
  7258. if (!parent_1.getClassName) {
  7259. done = true;
  7260. break;
  7261. }
  7262. if (parent_1.getClassName() !== currentKey) {
  7263. break;
  7264. }
  7265. currentTarget = parent_1;
  7266. } while (parent_1);
  7267. if (done) {
  7268. break;
  7269. }
  7270. currentKey = parent_1.getClassName();
  7271. currentTarget = parent_1;
  7272. }
  7273. return store;
  7274. }
  7275. function generateSerializableMember(type, sourceName) {
  7276. return function (target, propertyKey) {
  7277. var classStore = getDirectStore(target);
  7278. if (!classStore[propertyKey]) {
  7279. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7280. }
  7281. };
  7282. }
  7283. function generateExpandMember(setCallback, targetKey) {
  7284. if (targetKey === void 0) { targetKey = null; }
  7285. return function (target, propertyKey) {
  7286. var key = targetKey || ("_" + propertyKey);
  7287. Object.defineProperty(target, propertyKey, {
  7288. get: function () {
  7289. return this[key];
  7290. },
  7291. set: function (value) {
  7292. if (this[key] === value) {
  7293. return;
  7294. }
  7295. this[key] = value;
  7296. target[setCallback].apply(this);
  7297. },
  7298. enumerable: true,
  7299. configurable: true
  7300. });
  7301. };
  7302. }
  7303. function expandToProperty(callback, targetKey) {
  7304. if (targetKey === void 0) { targetKey = null; }
  7305. return generateExpandMember(callback, targetKey);
  7306. }
  7307. BABYLON.expandToProperty = expandToProperty;
  7308. function serialize(sourceName) {
  7309. return generateSerializableMember(0, sourceName); // value member
  7310. }
  7311. BABYLON.serialize = serialize;
  7312. function serializeAsTexture(sourceName) {
  7313. return generateSerializableMember(1, sourceName); // texture member
  7314. }
  7315. BABYLON.serializeAsTexture = serializeAsTexture;
  7316. function serializeAsColor3(sourceName) {
  7317. return generateSerializableMember(2, sourceName); // color3 member
  7318. }
  7319. BABYLON.serializeAsColor3 = serializeAsColor3;
  7320. function serializeAsFresnelParameters(sourceName) {
  7321. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7322. }
  7323. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7324. function serializeAsVector2(sourceName) {
  7325. return generateSerializableMember(4, sourceName); // vector2 member
  7326. }
  7327. BABYLON.serializeAsVector2 = serializeAsVector2;
  7328. function serializeAsVector3(sourceName) {
  7329. return generateSerializableMember(5, sourceName); // vector3 member
  7330. }
  7331. BABYLON.serializeAsVector3 = serializeAsVector3;
  7332. function serializeAsMeshReference(sourceName) {
  7333. return generateSerializableMember(6, sourceName); // mesh reference member
  7334. }
  7335. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7336. function serializeAsColorCurves(sourceName) {
  7337. return generateSerializableMember(7, sourceName); // color curves
  7338. }
  7339. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7340. function serializeAsColor4(sourceName) {
  7341. return generateSerializableMember(8, sourceName); // color 4
  7342. }
  7343. BABYLON.serializeAsColor4 = serializeAsColor4;
  7344. function serializeAsImageProcessingConfiguration(sourceName) {
  7345. return generateSerializableMember(9, sourceName); // image processing
  7346. }
  7347. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7348. function serializeAsQuaternion(sourceName) {
  7349. return generateSerializableMember(10, sourceName); // quaternion member
  7350. }
  7351. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7352. var SerializationHelper = /** @class */ (function () {
  7353. function SerializationHelper() {
  7354. }
  7355. SerializationHelper.Serialize = function (entity, serializationObject) {
  7356. if (!serializationObject) {
  7357. serializationObject = {};
  7358. }
  7359. // Tags
  7360. if (BABYLON.Tags) {
  7361. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7362. }
  7363. var serializedProperties = getMergedStore(entity);
  7364. // Properties
  7365. for (var property in serializedProperties) {
  7366. var propertyDescriptor = serializedProperties[property];
  7367. var targetPropertyName = propertyDescriptor.sourceName || property;
  7368. var propertyType = propertyDescriptor.type;
  7369. var sourceProperty = entity[property];
  7370. if (sourceProperty !== undefined && sourceProperty !== null) {
  7371. switch (propertyType) {
  7372. case 0:// Value
  7373. serializationObject[targetPropertyName] = sourceProperty;
  7374. break;
  7375. case 1:// Texture
  7376. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7377. break;
  7378. case 2:// Color3
  7379. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7380. break;
  7381. case 3:// FresnelParameters
  7382. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7383. break;
  7384. case 4:// Vector2
  7385. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7386. break;
  7387. case 5:// Vector3
  7388. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7389. break;
  7390. case 6:// Mesh reference
  7391. serializationObject[targetPropertyName] = sourceProperty.id;
  7392. break;
  7393. case 7:// Color Curves
  7394. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7395. break;
  7396. case 8:// Color 4
  7397. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7398. break;
  7399. case 9:// Image Processing
  7400. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7401. break;
  7402. }
  7403. }
  7404. }
  7405. return serializationObject;
  7406. };
  7407. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7408. if (rootUrl === void 0) { rootUrl = null; }
  7409. var destination = creationFunction();
  7410. if (!rootUrl) {
  7411. rootUrl = "";
  7412. }
  7413. // Tags
  7414. if (BABYLON.Tags) {
  7415. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7416. }
  7417. var classStore = getMergedStore(destination);
  7418. // Properties
  7419. for (var property in classStore) {
  7420. var propertyDescriptor = classStore[property];
  7421. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7422. var propertyType = propertyDescriptor.type;
  7423. if (sourceProperty !== undefined && sourceProperty !== null) {
  7424. var dest = destination;
  7425. switch (propertyType) {
  7426. case 0:// Value
  7427. dest[property] = sourceProperty;
  7428. break;
  7429. case 1:// Texture
  7430. if (scene) {
  7431. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7432. }
  7433. break;
  7434. case 2:// Color3
  7435. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7436. break;
  7437. case 3:// FresnelParameters
  7438. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7439. break;
  7440. case 4:// Vector2
  7441. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7442. break;
  7443. case 5:// Vector3
  7444. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7445. break;
  7446. case 6:// Mesh reference
  7447. if (scene) {
  7448. dest[property] = scene.getLastMeshByID(sourceProperty);
  7449. }
  7450. break;
  7451. case 7:// Color Curves
  7452. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7453. break;
  7454. case 8:// Color 4
  7455. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7456. break;
  7457. case 9:// Image Processing
  7458. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7459. break;
  7460. }
  7461. }
  7462. }
  7463. return destination;
  7464. };
  7465. SerializationHelper.Clone = function (creationFunction, source) {
  7466. return _copySource(creationFunction, source, false);
  7467. };
  7468. SerializationHelper.Instanciate = function (creationFunction, source) {
  7469. return _copySource(creationFunction, source, true);
  7470. };
  7471. return SerializationHelper;
  7472. }());
  7473. BABYLON.SerializationHelper = SerializationHelper;
  7474. })(BABYLON || (BABYLON = {}));
  7475. //# sourceMappingURL=babylon.decorators.js.map
  7476. "use strict";
  7477. var BABYLON;
  7478. (function (BABYLON) {
  7479. /**
  7480. * Wrapper class for promise with external resolve and reject.
  7481. */
  7482. var Deferred = /** @class */ (function () {
  7483. /**
  7484. * Constructor for this deferred object.
  7485. */
  7486. function Deferred() {
  7487. var _this = this;
  7488. this.promise = new Promise(function (resolve, reject) {
  7489. _this._resolve = resolve;
  7490. _this._reject = reject;
  7491. });
  7492. }
  7493. Object.defineProperty(Deferred.prototype, "resolve", {
  7494. /**
  7495. * The resolve method of the promise associated with this deferred object.
  7496. */
  7497. get: function () {
  7498. return this._resolve;
  7499. },
  7500. enumerable: true,
  7501. configurable: true
  7502. });
  7503. Object.defineProperty(Deferred.prototype, "reject", {
  7504. /**
  7505. * The reject method of the promise associated with this deferred object.
  7506. */
  7507. get: function () {
  7508. return this._reject;
  7509. },
  7510. enumerable: true,
  7511. configurable: true
  7512. });
  7513. return Deferred;
  7514. }());
  7515. BABYLON.Deferred = Deferred;
  7516. })(BABYLON || (BABYLON = {}));
  7517. //# sourceMappingURL=babylon.deferred.js.map
  7518. "use strict";
  7519. var BABYLON;
  7520. (function (BABYLON) {
  7521. /**
  7522. * A class serves as a medium between the observable and its observers
  7523. */
  7524. var EventState = /** @class */ (function () {
  7525. /**
  7526. * Create a new EventState
  7527. * @param mask defines the mask associated with this state
  7528. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7529. * @param target defines the original target of the state
  7530. * @param currentTarget defines the current target of the state
  7531. */
  7532. function EventState(mask, skipNextObservers, target, currentTarget) {
  7533. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7534. this.initalize(mask, skipNextObservers, target, currentTarget);
  7535. }
  7536. /**
  7537. * Initialize the current event state
  7538. * @param mask defines the mask associated with this state
  7539. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7540. * @param target defines the original target of the state
  7541. * @param currentTarget defines the current target of the state
  7542. * @returns the current event state
  7543. */
  7544. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7545. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7546. this.mask = mask;
  7547. this.skipNextObservers = skipNextObservers;
  7548. this.target = target;
  7549. this.currentTarget = currentTarget;
  7550. return this;
  7551. };
  7552. return EventState;
  7553. }());
  7554. BABYLON.EventState = EventState;
  7555. /**
  7556. * Represent an Observer registered to a given Observable object.
  7557. */
  7558. var Observer = /** @class */ (function () {
  7559. /**
  7560. * Creates a new observer
  7561. * @param callback defines the callback to call when the observer is notified
  7562. * @param mask defines the mask of the observer (used to filter notifications)
  7563. * @param scope defines the current scope used to restore the JS context
  7564. */
  7565. function Observer(
  7566. /**
  7567. * Defines the callback to call when the observer is notified
  7568. */
  7569. callback,
  7570. /**
  7571. * Defines the mask of the observer (used to filter notifications)
  7572. */
  7573. mask,
  7574. /**
  7575. * Defines the current scope used to restore the JS context
  7576. */
  7577. scope) {
  7578. if (scope === void 0) { scope = null; }
  7579. this.callback = callback;
  7580. this.mask = mask;
  7581. this.scope = scope;
  7582. /** @ignore */
  7583. this._willBeUnregistered = false;
  7584. /**
  7585. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7586. */
  7587. this.unregisterOnNextCall = false;
  7588. }
  7589. return Observer;
  7590. }());
  7591. BABYLON.Observer = Observer;
  7592. /**
  7593. * Represent a list of observers registered to multiple Observables object.
  7594. */
  7595. var MultiObserver = /** @class */ (function () {
  7596. function MultiObserver() {
  7597. }
  7598. /**
  7599. * Release associated resources
  7600. */
  7601. MultiObserver.prototype.dispose = function () {
  7602. if (this._observers && this._observables) {
  7603. for (var index = 0; index < this._observers.length; index++) {
  7604. this._observables[index].remove(this._observers[index]);
  7605. }
  7606. }
  7607. this._observers = null;
  7608. this._observables = null;
  7609. };
  7610. /**
  7611. * Raise a callback when one of the observable will notify
  7612. * @param observables defines a list of observables to watch
  7613. * @param callback defines the callback to call on notification
  7614. * @param mask defines the mask used to filter notifications
  7615. * @param scope defines the current scope used to restore the JS context
  7616. * @returns the new MultiObserver
  7617. */
  7618. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7619. if (mask === void 0) { mask = -1; }
  7620. if (scope === void 0) { scope = null; }
  7621. var result = new MultiObserver();
  7622. result._observers = new Array();
  7623. result._observables = observables;
  7624. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7625. var observable = observables_1[_i];
  7626. var observer = observable.add(callback, mask, false, scope);
  7627. if (observer) {
  7628. result._observers.push(observer);
  7629. }
  7630. }
  7631. return result;
  7632. };
  7633. return MultiObserver;
  7634. }());
  7635. BABYLON.MultiObserver = MultiObserver;
  7636. /**
  7637. * The Observable class is a simple implementation of the Observable pattern.
  7638. * 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.
  7639. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7640. * 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).
  7641. * 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.
  7642. */
  7643. var Observable = /** @class */ (function () {
  7644. /**
  7645. * Creates a new observable
  7646. * @param onObserverAdded defines a callback to call when a new observer is added
  7647. */
  7648. function Observable(onObserverAdded) {
  7649. this._observers = new Array();
  7650. this._eventState = new EventState(0);
  7651. if (onObserverAdded) {
  7652. this._onObserverAdded = onObserverAdded;
  7653. }
  7654. }
  7655. /**
  7656. * Create a new Observer with the specified callback
  7657. * @param callback the callback that will be executed for that Observer
  7658. * @param mask the mask used to filter observers
  7659. * @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.
  7660. * @param scope optional scope for the callback to be called from
  7661. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7662. * @returns the new observer created for the callback
  7663. */
  7664. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7665. if (mask === void 0) { mask = -1; }
  7666. if (insertFirst === void 0) { insertFirst = false; }
  7667. if (scope === void 0) { scope = null; }
  7668. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7669. if (!callback) {
  7670. return null;
  7671. }
  7672. var observer = new Observer(callback, mask, scope);
  7673. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7674. if (insertFirst) {
  7675. this._observers.unshift(observer);
  7676. }
  7677. else {
  7678. this._observers.push(observer);
  7679. }
  7680. if (this._onObserverAdded) {
  7681. this._onObserverAdded(observer);
  7682. }
  7683. return observer;
  7684. };
  7685. /**
  7686. * Remove an Observer from the Observable object
  7687. * @param observer the instance of the Observer to remove
  7688. * @returns false if it doesn't belong to this Observable
  7689. */
  7690. Observable.prototype.remove = function (observer) {
  7691. if (!observer) {
  7692. return false;
  7693. }
  7694. var index = this._observers.indexOf(observer);
  7695. if (index !== -1) {
  7696. this._observers.splice(index, 1);
  7697. return true;
  7698. }
  7699. return false;
  7700. };
  7701. /**
  7702. * Remove a callback from the Observable object
  7703. * @param callback the callback to remove
  7704. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7705. * @returns false if it doesn't belong to this Observable
  7706. */
  7707. Observable.prototype.removeCallback = function (callback, scope) {
  7708. for (var index = 0; index < this._observers.length; index++) {
  7709. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7710. this._observers.splice(index, 1);
  7711. return true;
  7712. }
  7713. }
  7714. return false;
  7715. };
  7716. Observable.prototype._deferUnregister = function (observer) {
  7717. var _this = this;
  7718. observer.unregisterOnNextCall = false;
  7719. observer._willBeUnregistered = true;
  7720. BABYLON.Tools.SetImmediate(function () {
  7721. _this.remove(observer);
  7722. });
  7723. };
  7724. /**
  7725. * Notify all Observers by calling their respective callback with the given data
  7726. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7727. * @param eventData defines the data to send to all observers
  7728. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7729. * @param target defines the original target of the state
  7730. * @param currentTarget defines the current target of the state
  7731. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7732. */
  7733. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7734. if (mask === void 0) { mask = -1; }
  7735. if (!this._observers.length) {
  7736. return true;
  7737. }
  7738. var state = this._eventState;
  7739. state.mask = mask;
  7740. state.target = target;
  7741. state.currentTarget = currentTarget;
  7742. state.skipNextObservers = false;
  7743. state.lastReturnValue = eventData;
  7744. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7745. var obs = _a[_i];
  7746. if (obs._willBeUnregistered) {
  7747. continue;
  7748. }
  7749. if (obs.mask & mask) {
  7750. if (obs.scope) {
  7751. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7752. }
  7753. else {
  7754. state.lastReturnValue = obs.callback(eventData, state);
  7755. }
  7756. if (obs.unregisterOnNextCall) {
  7757. this._deferUnregister(obs);
  7758. }
  7759. }
  7760. if (state.skipNextObservers) {
  7761. return false;
  7762. }
  7763. }
  7764. return true;
  7765. };
  7766. /**
  7767. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7768. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7769. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7770. * and it is crucial that all callbacks will be executed.
  7771. * The order of the callbacks is kept, callbacks are not executed parallel.
  7772. *
  7773. * @param eventData The data to be sent to each callback
  7774. * @param mask is used to filter observers defaults to -1
  7775. * @param target defines the callback target (see EventState)
  7776. * @param currentTarget defines he current object in the bubbling phase
  7777. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7778. */
  7779. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7780. var _this = this;
  7781. if (mask === void 0) { mask = -1; }
  7782. // create an empty promise
  7783. var p = Promise.resolve(eventData);
  7784. // no observers? return this promise.
  7785. if (!this._observers.length) {
  7786. return p;
  7787. }
  7788. var state = this._eventState;
  7789. state.mask = mask;
  7790. state.target = target;
  7791. state.currentTarget = currentTarget;
  7792. state.skipNextObservers = false;
  7793. // execute one callback after another (not using Promise.all, the order is important)
  7794. this._observers.forEach(function (obs) {
  7795. if (state.skipNextObservers) {
  7796. return;
  7797. }
  7798. if (obs._willBeUnregistered) {
  7799. return;
  7800. }
  7801. if (obs.mask & mask) {
  7802. if (obs.scope) {
  7803. p = p.then(function (lastReturnedValue) {
  7804. state.lastReturnValue = lastReturnedValue;
  7805. return obs.callback.apply(obs.scope, [eventData, state]);
  7806. });
  7807. }
  7808. else {
  7809. p = p.then(function (lastReturnedValue) {
  7810. state.lastReturnValue = lastReturnedValue;
  7811. return obs.callback(eventData, state);
  7812. });
  7813. }
  7814. if (obs.unregisterOnNextCall) {
  7815. _this._deferUnregister(obs);
  7816. }
  7817. }
  7818. });
  7819. // return the eventData
  7820. return p.then(function () { return eventData; });
  7821. };
  7822. /**
  7823. * Notify a specific observer
  7824. * @param observer defines the observer to notify
  7825. * @param eventData defines the data to be sent to each callback
  7826. * @param mask is used to filter observers defaults to -1
  7827. */
  7828. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7829. if (mask === void 0) { mask = -1; }
  7830. var state = this._eventState;
  7831. state.mask = mask;
  7832. state.skipNextObservers = false;
  7833. observer.callback(eventData, state);
  7834. };
  7835. /**
  7836. * Gets a boolean indicating if the observable has at least one observer
  7837. * @returns true is the Observable has at least one Observer registered
  7838. */
  7839. Observable.prototype.hasObservers = function () {
  7840. return this._observers.length > 0;
  7841. };
  7842. /**
  7843. * Clear the list of observers
  7844. */
  7845. Observable.prototype.clear = function () {
  7846. this._observers = new Array();
  7847. this._onObserverAdded = null;
  7848. };
  7849. /**
  7850. * Clone the current observable
  7851. * @returns a new observable
  7852. */
  7853. Observable.prototype.clone = function () {
  7854. var result = new Observable();
  7855. result._observers = this._observers.slice(0);
  7856. return result;
  7857. };
  7858. /**
  7859. * Does this observable handles observer registered with a given mask
  7860. * @param mask defines the mask to be tested
  7861. * @return whether or not one observer registered with the given mask is handeled
  7862. **/
  7863. Observable.prototype.hasSpecificMask = function (mask) {
  7864. if (mask === void 0) { mask = -1; }
  7865. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7866. var obs = _a[_i];
  7867. if (obs.mask & mask || obs.mask === mask) {
  7868. return true;
  7869. }
  7870. }
  7871. return false;
  7872. };
  7873. return Observable;
  7874. }());
  7875. BABYLON.Observable = Observable;
  7876. })(BABYLON || (BABYLON = {}));
  7877. //# sourceMappingURL=babylon.observable.js.map
  7878. "use strict";
  7879. var BABYLON;
  7880. (function (BABYLON) {
  7881. var SmartArray = /** @class */ (function () {
  7882. function SmartArray(capacity) {
  7883. this.length = 0;
  7884. this.data = new Array(capacity);
  7885. this._id = SmartArray._GlobalId++;
  7886. }
  7887. SmartArray.prototype.push = function (value) {
  7888. this.data[this.length++] = value;
  7889. if (this.length > this.data.length) {
  7890. this.data.length *= 2;
  7891. }
  7892. };
  7893. SmartArray.prototype.forEach = function (func) {
  7894. for (var index = 0; index < this.length; index++) {
  7895. func(this.data[index]);
  7896. }
  7897. };
  7898. SmartArray.prototype.sort = function (compareFn) {
  7899. this.data.sort(compareFn);
  7900. };
  7901. SmartArray.prototype.reset = function () {
  7902. this.length = 0;
  7903. };
  7904. SmartArray.prototype.dispose = function () {
  7905. this.reset();
  7906. if (this.data) {
  7907. this.data.length = 0;
  7908. this.data = [];
  7909. }
  7910. };
  7911. SmartArray.prototype.concat = function (array) {
  7912. if (array.length === 0) {
  7913. return;
  7914. }
  7915. if (this.length + array.length > this.data.length) {
  7916. this.data.length = (this.length + array.length) * 2;
  7917. }
  7918. for (var index = 0; index < array.length; index++) {
  7919. this.data[this.length++] = (array.data || array)[index];
  7920. }
  7921. };
  7922. SmartArray.prototype.indexOf = function (value) {
  7923. var position = this.data.indexOf(value);
  7924. if (position >= this.length) {
  7925. return -1;
  7926. }
  7927. return position;
  7928. };
  7929. SmartArray.prototype.contains = function (value) {
  7930. return this.data.indexOf(value) !== -1;
  7931. };
  7932. // Statics
  7933. SmartArray._GlobalId = 0;
  7934. return SmartArray;
  7935. }());
  7936. BABYLON.SmartArray = SmartArray;
  7937. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7938. __extends(SmartArrayNoDuplicate, _super);
  7939. function SmartArrayNoDuplicate() {
  7940. var _this = _super !== null && _super.apply(this, arguments) || this;
  7941. _this._duplicateId = 0;
  7942. return _this;
  7943. }
  7944. SmartArrayNoDuplicate.prototype.push = function (value) {
  7945. _super.prototype.push.call(this, value);
  7946. if (!value.__smartArrayFlags) {
  7947. value.__smartArrayFlags = {};
  7948. }
  7949. value.__smartArrayFlags[this._id] = this._duplicateId;
  7950. };
  7951. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7952. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7953. return false;
  7954. }
  7955. this.push(value);
  7956. return true;
  7957. };
  7958. SmartArrayNoDuplicate.prototype.reset = function () {
  7959. _super.prototype.reset.call(this);
  7960. this._duplicateId++;
  7961. };
  7962. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7963. if (array.length === 0) {
  7964. return;
  7965. }
  7966. if (this.length + array.length > this.data.length) {
  7967. this.data.length = (this.length + array.length) * 2;
  7968. }
  7969. for (var index = 0; index < array.length; index++) {
  7970. var item = (array.data || array)[index];
  7971. this.pushNoDuplicate(item);
  7972. }
  7973. };
  7974. return SmartArrayNoDuplicate;
  7975. }(SmartArray));
  7976. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7977. })(BABYLON || (BABYLON = {}));
  7978. //# sourceMappingURL=babylon.smartArray.js.map
  7979. "use strict";
  7980. var BABYLON;
  7981. (function (BABYLON) {
  7982. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7983. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7984. var LoadFileError = /** @class */ (function (_super) {
  7985. __extends(LoadFileError, _super);
  7986. function LoadFileError(message, request) {
  7987. var _this = _super.call(this, message) || this;
  7988. _this.request = request;
  7989. _this.name = "LoadFileError";
  7990. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7991. return _this;
  7992. }
  7993. // Polyfill for Object.setPrototypeOf if necessary.
  7994. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7995. return LoadFileError;
  7996. }(Error));
  7997. BABYLON.LoadFileError = LoadFileError;
  7998. var RetryStrategy = /** @class */ (function () {
  7999. function RetryStrategy() {
  8000. }
  8001. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8002. if (maxRetries === void 0) { maxRetries = 3; }
  8003. if (baseInterval === void 0) { baseInterval = 500; }
  8004. return function (url, request, retryIndex) {
  8005. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8006. return -1;
  8007. }
  8008. return Math.pow(2, retryIndex) * baseInterval;
  8009. };
  8010. };
  8011. return RetryStrategy;
  8012. }());
  8013. BABYLON.RetryStrategy = RetryStrategy;
  8014. // Screenshots
  8015. var screenshotCanvas;
  8016. var cloneValue = function (source, destinationObject) {
  8017. if (!source)
  8018. return null;
  8019. if (source instanceof BABYLON.Mesh) {
  8020. return null;
  8021. }
  8022. if (source instanceof BABYLON.SubMesh) {
  8023. return source.clone(destinationObject);
  8024. }
  8025. else if (source.clone) {
  8026. return source.clone();
  8027. }
  8028. return null;
  8029. };
  8030. var Tools = /** @class */ (function () {
  8031. function Tools() {
  8032. }
  8033. /**
  8034. * Interpolates between a and b via alpha
  8035. * @param a The lower value (returned when alpha = 0)
  8036. * @param b The upper value (returned when alpha = 1)
  8037. * @param alpha The interpolation-factor
  8038. * @return The mixed value
  8039. */
  8040. Tools.Mix = function (a, b, alpha) {
  8041. return a * (1 - alpha) + b * alpha;
  8042. };
  8043. Tools.Instantiate = function (className) {
  8044. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8045. return Tools.RegisteredExternalClasses[className];
  8046. }
  8047. var arr = className.split(".");
  8048. var fn = (window || this);
  8049. for (var i = 0, len = arr.length; i < len; i++) {
  8050. fn = fn[arr[i]];
  8051. }
  8052. if (typeof fn !== "function") {
  8053. return null;
  8054. }
  8055. return fn;
  8056. };
  8057. /**
  8058. * Provides a slice function that will work even on IE
  8059. * @param data defines the array to slice
  8060. * @returns the new sliced array
  8061. */
  8062. Tools.Slice = function (data) {
  8063. if (data.slice) {
  8064. return data.slice();
  8065. }
  8066. return Array.prototype.slice.call(data);
  8067. };
  8068. Tools.SetImmediate = function (action) {
  8069. if (window.setImmediate) {
  8070. window.setImmediate(action);
  8071. }
  8072. else {
  8073. setTimeout(action, 1);
  8074. }
  8075. };
  8076. Tools.IsExponentOfTwo = function (value) {
  8077. var count = 1;
  8078. do {
  8079. count *= 2;
  8080. } while (count < value);
  8081. return count === value;
  8082. };
  8083. /**
  8084. * Find the next highest power of two.
  8085. * @param x Number to start search from.
  8086. * @return Next highest power of two.
  8087. */
  8088. Tools.CeilingPOT = function (x) {
  8089. x--;
  8090. x |= x >> 1;
  8091. x |= x >> 2;
  8092. x |= x >> 4;
  8093. x |= x >> 8;
  8094. x |= x >> 16;
  8095. x++;
  8096. return x;
  8097. };
  8098. /**
  8099. * Find the next lowest power of two.
  8100. * @param x Number to start search from.
  8101. * @return Next lowest power of two.
  8102. */
  8103. Tools.FloorPOT = function (x) {
  8104. x = x | (x >> 1);
  8105. x = x | (x >> 2);
  8106. x = x | (x >> 4);
  8107. x = x | (x >> 8);
  8108. x = x | (x >> 16);
  8109. return x - (x >> 1);
  8110. };
  8111. /**
  8112. * Find the nearest power of two.
  8113. * @param x Number to start search from.
  8114. * @return Next nearest power of two.
  8115. */
  8116. Tools.NearestPOT = function (x) {
  8117. var c = Tools.CeilingPOT(x);
  8118. var f = Tools.FloorPOT(x);
  8119. return (c - x) > (x - f) ? f : c;
  8120. };
  8121. Tools.GetExponentOfTwo = function (value, max, mode) {
  8122. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8123. var pot;
  8124. switch (mode) {
  8125. case BABYLON.Engine.SCALEMODE_FLOOR:
  8126. pot = Tools.FloorPOT(value);
  8127. break;
  8128. case BABYLON.Engine.SCALEMODE_NEAREST:
  8129. pot = Tools.NearestPOT(value);
  8130. break;
  8131. case BABYLON.Engine.SCALEMODE_CEILING:
  8132. default:
  8133. pot = Tools.CeilingPOT(value);
  8134. break;
  8135. }
  8136. return Math.min(pot, max);
  8137. };
  8138. Tools.GetFilename = function (path) {
  8139. var index = path.lastIndexOf("/");
  8140. if (index < 0)
  8141. return path;
  8142. return path.substring(index + 1);
  8143. };
  8144. /**
  8145. * Extracts the "folder" part of a path (everything before the filename).
  8146. * @param uri The URI to extract the info from
  8147. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8148. * @returns The "folder" part of the path
  8149. */
  8150. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8151. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8152. var index = uri.lastIndexOf("/");
  8153. if (index < 0) {
  8154. if (returnUnchangedIfNoSlash) {
  8155. return uri;
  8156. }
  8157. return "";
  8158. }
  8159. return uri.substring(0, index + 1);
  8160. };
  8161. Tools.GetDOMTextContent = function (element) {
  8162. var result = "";
  8163. var child = element.firstChild;
  8164. while (child) {
  8165. if (child.nodeType === 3) {
  8166. result += child.textContent;
  8167. }
  8168. child = child.nextSibling;
  8169. }
  8170. return result;
  8171. };
  8172. Tools.ToDegrees = function (angle) {
  8173. return angle * 180 / Math.PI;
  8174. };
  8175. Tools.ToRadians = function (angle) {
  8176. return angle * Math.PI / 180;
  8177. };
  8178. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8179. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8180. var output = "";
  8181. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8182. var i = 0;
  8183. var bytes = new Uint8Array(buffer);
  8184. while (i < bytes.length) {
  8185. chr1 = bytes[i++];
  8186. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8187. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8188. enc1 = chr1 >> 2;
  8189. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8190. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8191. enc4 = chr3 & 63;
  8192. if (isNaN(chr2)) {
  8193. enc3 = enc4 = 64;
  8194. }
  8195. else if (isNaN(chr3)) {
  8196. enc4 = 64;
  8197. }
  8198. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8199. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8200. }
  8201. return "data:image/png;base64," + output;
  8202. };
  8203. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  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. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8208. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8209. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8210. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8211. }
  8212. if (bias) {
  8213. minimum.x -= minimum.x * bias.x + bias.y;
  8214. minimum.y -= minimum.y * bias.x + bias.y;
  8215. minimum.z -= minimum.z * bias.x + bias.y;
  8216. maximum.x += maximum.x * bias.x + bias.y;
  8217. maximum.y += maximum.y * bias.x + bias.y;
  8218. maximum.z += maximum.z * bias.x + bias.y;
  8219. }
  8220. return {
  8221. minimum: minimum,
  8222. maximum: maximum
  8223. };
  8224. };
  8225. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8226. if (bias === void 0) { bias = null; }
  8227. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8228. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8229. if (!stride) {
  8230. stride = 3;
  8231. }
  8232. for (var index = start; index < start + count; index++) {
  8233. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8234. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8235. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8236. }
  8237. if (bias) {
  8238. minimum.x -= minimum.x * bias.x + bias.y;
  8239. minimum.y -= minimum.y * bias.x + bias.y;
  8240. minimum.z -= minimum.z * bias.x + bias.y;
  8241. maximum.x += maximum.x * bias.x + bias.y;
  8242. maximum.y += maximum.y * bias.x + bias.y;
  8243. maximum.z += maximum.z * bias.x + bias.y;
  8244. }
  8245. return {
  8246. minimum: minimum,
  8247. maximum: maximum
  8248. };
  8249. };
  8250. Tools.Vector2ArrayFeeder = function (array) {
  8251. return function (index) {
  8252. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8253. var length = isFloatArray ? array.length / 2 : array.length;
  8254. if (index >= length) {
  8255. return null;
  8256. }
  8257. if (isFloatArray) {
  8258. var fa = array;
  8259. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8260. }
  8261. var a = array;
  8262. return a[index];
  8263. };
  8264. };
  8265. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8266. if (bias === void 0) { bias = null; }
  8267. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8268. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8269. var i = 0;
  8270. var cur = feeder(i++);
  8271. while (cur) {
  8272. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8273. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8274. cur = feeder(i++);
  8275. }
  8276. if (bias) {
  8277. minimum.x -= minimum.x * bias.x + bias.y;
  8278. minimum.y -= minimum.y * bias.x + bias.y;
  8279. maximum.x += maximum.x * bias.x + bias.y;
  8280. maximum.y += maximum.y * bias.x + bias.y;
  8281. }
  8282. return {
  8283. minimum: minimum,
  8284. maximum: maximum
  8285. };
  8286. };
  8287. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8288. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8289. return null;
  8290. return Array.isArray(obj) ? obj : [obj];
  8291. };
  8292. // Misc.
  8293. Tools.GetPointerPrefix = function () {
  8294. var eventPrefix = "pointer";
  8295. // Check if pointer events are supported
  8296. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8297. eventPrefix = "mouse";
  8298. }
  8299. return eventPrefix;
  8300. };
  8301. /**
  8302. * @param func - the function to be called
  8303. * @param requester - the object that will request the next frame. Falls back to window.
  8304. */
  8305. Tools.QueueNewFrame = function (func, requester) {
  8306. if (!Tools.IsWindowObjectExist()) {
  8307. return setTimeout(func, 16);
  8308. }
  8309. if (!requester) {
  8310. requester = window;
  8311. }
  8312. if (requester.requestAnimationFrame) {
  8313. return requester.requestAnimationFrame(func);
  8314. }
  8315. else if (requester.msRequestAnimationFrame) {
  8316. return requester.msRequestAnimationFrame(func);
  8317. }
  8318. else if (requester.webkitRequestAnimationFrame) {
  8319. return requester.webkitRequestAnimationFrame(func);
  8320. }
  8321. else if (requester.mozRequestAnimationFrame) {
  8322. return requester.mozRequestAnimationFrame(func);
  8323. }
  8324. else if (requester.oRequestAnimationFrame) {
  8325. return requester.oRequestAnimationFrame(func);
  8326. }
  8327. else {
  8328. return window.setTimeout(func, 16);
  8329. }
  8330. };
  8331. Tools.RequestFullscreen = function (element) {
  8332. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8333. if (!requestFunction)
  8334. return;
  8335. requestFunction.call(element);
  8336. };
  8337. Tools.ExitFullscreen = function () {
  8338. if (document.exitFullscreen) {
  8339. document.exitFullscreen();
  8340. }
  8341. else if (document.mozCancelFullScreen) {
  8342. document.mozCancelFullScreen();
  8343. }
  8344. else if (document.webkitCancelFullScreen) {
  8345. document.webkitCancelFullScreen();
  8346. }
  8347. else if (document.msCancelFullScreen) {
  8348. document.msCancelFullScreen();
  8349. }
  8350. };
  8351. Tools.SetCorsBehavior = function (url, element) {
  8352. if (url && url.indexOf("data:") === 0) {
  8353. return;
  8354. }
  8355. if (Tools.CorsBehavior) {
  8356. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8357. element.crossOrigin = Tools.CorsBehavior;
  8358. }
  8359. else {
  8360. var result = Tools.CorsBehavior(url);
  8361. if (result) {
  8362. element.crossOrigin = result;
  8363. }
  8364. }
  8365. }
  8366. };
  8367. // External files
  8368. Tools.CleanUrl = function (url) {
  8369. url = url.replace(/#/mg, "%23");
  8370. return url;
  8371. };
  8372. Tools.LoadImage = function (url, onLoad, onError, database) {
  8373. if (url instanceof ArrayBuffer) {
  8374. url = Tools.EncodeArrayBufferTobase64(url);
  8375. }
  8376. url = Tools.CleanUrl(url);
  8377. url = Tools.PreprocessUrl(url);
  8378. var img = new Image();
  8379. Tools.SetCorsBehavior(url, img);
  8380. var loadHandler = function () {
  8381. img.removeEventListener("load", loadHandler);
  8382. img.removeEventListener("error", errorHandler);
  8383. onLoad(img);
  8384. };
  8385. var errorHandler = function (err) {
  8386. img.removeEventListener("load", loadHandler);
  8387. img.removeEventListener("error", errorHandler);
  8388. Tools.Error("Error while trying to load image: " + url);
  8389. if (onError) {
  8390. onError("Error while trying to load image: " + url, err);
  8391. }
  8392. };
  8393. img.addEventListener("load", loadHandler);
  8394. img.addEventListener("error", errorHandler);
  8395. var noIndexedDB = function () {
  8396. img.src = url;
  8397. };
  8398. var loadFromIndexedDB = function () {
  8399. if (database) {
  8400. database.loadImageFromDB(url, img);
  8401. }
  8402. };
  8403. //ANY database to do!
  8404. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8405. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8406. }
  8407. else {
  8408. if (url.indexOf("file:") !== -1) {
  8409. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8410. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8411. try {
  8412. var blobURL;
  8413. try {
  8414. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8415. }
  8416. catch (ex) {
  8417. // Chrome doesn't support oneTimeOnly parameter
  8418. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8419. }
  8420. img.src = blobURL;
  8421. }
  8422. catch (e) {
  8423. img.src = "";
  8424. }
  8425. return img;
  8426. }
  8427. }
  8428. noIndexedDB();
  8429. }
  8430. return img;
  8431. };
  8432. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8433. url = Tools.CleanUrl(url);
  8434. url = Tools.PreprocessUrl(url);
  8435. // If file and file input are set
  8436. if (url.indexOf("file:") !== -1) {
  8437. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8438. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8439. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8440. }
  8441. }
  8442. var loadUrl = Tools.BaseUrl + url;
  8443. var aborted = false;
  8444. var fileRequest = {
  8445. onCompleteObservable: new BABYLON.Observable(),
  8446. abort: function () { return aborted = true; },
  8447. };
  8448. var requestFile = function () {
  8449. var request = new XMLHttpRequest();
  8450. var retryHandle = null;
  8451. fileRequest.abort = function () {
  8452. aborted = true;
  8453. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8454. request.abort();
  8455. }
  8456. if (retryHandle !== null) {
  8457. clearTimeout(retryHandle);
  8458. retryHandle = null;
  8459. }
  8460. };
  8461. var retryLoop = function (retryIndex) {
  8462. request.open('GET', loadUrl, true);
  8463. if (useArrayBuffer) {
  8464. request.responseType = "arraybuffer";
  8465. }
  8466. if (onProgress) {
  8467. request.addEventListener("progress", onProgress);
  8468. }
  8469. var onLoadEnd = function () {
  8470. request.removeEventListener("loadend", onLoadEnd);
  8471. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8472. fileRequest.onCompleteObservable.clear();
  8473. };
  8474. request.addEventListener("loadend", onLoadEnd);
  8475. var onReadyStateChange = function () {
  8476. if (aborted) {
  8477. return;
  8478. }
  8479. // In case of undefined state in some browsers.
  8480. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8481. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8482. request.removeEventListener("readystatechange", onReadyStateChange);
  8483. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8484. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8485. return;
  8486. }
  8487. var retryStrategy = Tools.DefaultRetryStrategy;
  8488. if (retryStrategy) {
  8489. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8490. if (waitTime !== -1) {
  8491. // Prevent the request from completing for retry.
  8492. request.removeEventListener("loadend", onLoadEnd);
  8493. request = new XMLHttpRequest();
  8494. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8495. return;
  8496. }
  8497. }
  8498. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8499. if (onError) {
  8500. onError(request, e);
  8501. }
  8502. else {
  8503. throw e;
  8504. }
  8505. }
  8506. };
  8507. request.addEventListener("readystatechange", onReadyStateChange);
  8508. request.send();
  8509. };
  8510. retryLoop(0);
  8511. };
  8512. // Caching all files
  8513. if (database && database.enableSceneOffline) {
  8514. var noIndexedDB_1 = function () {
  8515. if (!aborted) {
  8516. requestFile();
  8517. }
  8518. };
  8519. var loadFromIndexedDB = function () {
  8520. // TODO: database needs to support aborting and should return a IFileRequest
  8521. if (aborted) {
  8522. return;
  8523. }
  8524. if (database) {
  8525. database.loadFileFromDB(url, function (data) {
  8526. if (!aborted) {
  8527. onSuccess(data);
  8528. }
  8529. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8530. }, onProgress ? function (event) {
  8531. if (!aborted) {
  8532. onProgress(event);
  8533. }
  8534. } : undefined, noIndexedDB_1, useArrayBuffer);
  8535. }
  8536. };
  8537. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8538. }
  8539. else {
  8540. requestFile();
  8541. }
  8542. return fileRequest;
  8543. };
  8544. /**
  8545. * Load a script (identified by an url). When the url returns, the
  8546. * content of this file is added into a new script element, attached to the DOM (body element)
  8547. */
  8548. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8549. var head = document.getElementsByTagName('head')[0];
  8550. var script = document.createElement('script');
  8551. script.type = 'text/javascript';
  8552. script.src = scriptUrl;
  8553. script.onload = function () {
  8554. if (onSuccess) {
  8555. onSuccess();
  8556. }
  8557. };
  8558. script.onerror = function (e) {
  8559. if (onError) {
  8560. onError("Unable to load script", e);
  8561. }
  8562. };
  8563. head.appendChild(script);
  8564. };
  8565. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8566. var reader = new FileReader();
  8567. var request = {
  8568. onCompleteObservable: new BABYLON.Observable(),
  8569. abort: function () { return reader.abort(); },
  8570. };
  8571. reader.onloadend = function (e) {
  8572. request.onCompleteObservable.notifyObservers(request);
  8573. };
  8574. reader.onload = function (e) {
  8575. //target doesn't have result from ts 1.3
  8576. callback(e.target['result']);
  8577. };
  8578. reader.onprogress = progressCallback;
  8579. reader.readAsDataURL(fileToLoad);
  8580. return request;
  8581. };
  8582. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8583. var reader = new FileReader();
  8584. var request = {
  8585. onCompleteObservable: new BABYLON.Observable(),
  8586. abort: function () { return reader.abort(); },
  8587. };
  8588. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8589. reader.onerror = function (e) {
  8590. Tools.Log("Error while reading file: " + fileToLoad.name);
  8591. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8592. };
  8593. reader.onload = function (e) {
  8594. //target doesn't have result from ts 1.3
  8595. callback(e.target['result']);
  8596. };
  8597. if (progressCallBack) {
  8598. reader.onprogress = progressCallBack;
  8599. }
  8600. if (!useArrayBuffer) {
  8601. // Asynchronous read
  8602. reader.readAsText(fileToLoad);
  8603. }
  8604. else {
  8605. reader.readAsArrayBuffer(fileToLoad);
  8606. }
  8607. return request;
  8608. };
  8609. //returns a downloadable url to a file content.
  8610. Tools.FileAsURL = function (content) {
  8611. var fileBlob = new Blob([content]);
  8612. var url = window.URL || window.webkitURL;
  8613. var link = url.createObjectURL(fileBlob);
  8614. return link;
  8615. };
  8616. // Misc.
  8617. Tools.Format = function (value, decimals) {
  8618. if (decimals === void 0) { decimals = 2; }
  8619. return value.toFixed(decimals);
  8620. };
  8621. Tools.CheckExtends = function (v, min, max) {
  8622. if (v.x < min.x)
  8623. min.x = v.x;
  8624. if (v.y < min.y)
  8625. min.y = v.y;
  8626. if (v.z < min.z)
  8627. min.z = v.z;
  8628. if (v.x > max.x)
  8629. max.x = v.x;
  8630. if (v.y > max.y)
  8631. max.y = v.y;
  8632. if (v.z > max.z)
  8633. max.z = v.z;
  8634. };
  8635. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8636. for (var prop in source) {
  8637. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8638. continue;
  8639. }
  8640. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8641. continue;
  8642. }
  8643. var sourceValue = source[prop];
  8644. var typeOfSourceValue = typeof sourceValue;
  8645. if (typeOfSourceValue === "function") {
  8646. continue;
  8647. }
  8648. try {
  8649. if (typeOfSourceValue === "object") {
  8650. if (sourceValue instanceof Array) {
  8651. destination[prop] = [];
  8652. if (sourceValue.length > 0) {
  8653. if (typeof sourceValue[0] == "object") {
  8654. for (var index = 0; index < sourceValue.length; index++) {
  8655. var clonedValue = cloneValue(sourceValue[index], destination);
  8656. if (destination[prop].indexOf(clonedValue) === -1) {
  8657. destination[prop].push(clonedValue);
  8658. }
  8659. }
  8660. }
  8661. else {
  8662. destination[prop] = sourceValue.slice(0);
  8663. }
  8664. }
  8665. }
  8666. else {
  8667. destination[prop] = cloneValue(sourceValue, destination);
  8668. }
  8669. }
  8670. else {
  8671. destination[prop] = sourceValue;
  8672. }
  8673. }
  8674. catch (e) {
  8675. // Just ignore error (it could be because of a read-only property)
  8676. }
  8677. }
  8678. };
  8679. Tools.IsEmpty = function (obj) {
  8680. for (var i in obj) {
  8681. if (obj.hasOwnProperty(i)) {
  8682. return false;
  8683. }
  8684. }
  8685. return true;
  8686. };
  8687. Tools.RegisterTopRootEvents = function (events) {
  8688. for (var index = 0; index < events.length; index++) {
  8689. var event = events[index];
  8690. window.addEventListener(event.name, event.handler, false);
  8691. try {
  8692. if (window.parent) {
  8693. window.parent.addEventListener(event.name, event.handler, false);
  8694. }
  8695. }
  8696. catch (e) {
  8697. // Silently fails...
  8698. }
  8699. }
  8700. };
  8701. Tools.UnregisterTopRootEvents = function (events) {
  8702. for (var index = 0; index < events.length; index++) {
  8703. var event = events[index];
  8704. window.removeEventListener(event.name, event.handler);
  8705. try {
  8706. if (window.parent) {
  8707. window.parent.removeEventListener(event.name, event.handler);
  8708. }
  8709. }
  8710. catch (e) {
  8711. // Silently fails...
  8712. }
  8713. }
  8714. };
  8715. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8716. if (mimeType === void 0) { mimeType = "image/png"; }
  8717. // Read the contents of the framebuffer
  8718. var numberOfChannelsByLine = width * 4;
  8719. var halfHeight = height / 2;
  8720. //Reading datas from WebGL
  8721. var data = engine.readPixels(0, 0, width, height);
  8722. //To flip image on Y axis.
  8723. for (var i = 0; i < halfHeight; i++) {
  8724. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8725. var currentCell = j + i * numberOfChannelsByLine;
  8726. var targetLine = height - i - 1;
  8727. var targetCell = j + targetLine * numberOfChannelsByLine;
  8728. var temp = data[currentCell];
  8729. data[currentCell] = data[targetCell];
  8730. data[targetCell] = temp;
  8731. }
  8732. }
  8733. // Create a 2D canvas to store the result
  8734. if (!screenshotCanvas) {
  8735. screenshotCanvas = document.createElement('canvas');
  8736. }
  8737. screenshotCanvas.width = width;
  8738. screenshotCanvas.height = height;
  8739. var context = screenshotCanvas.getContext('2d');
  8740. if (context) {
  8741. // Copy the pixels to a 2D canvas
  8742. var imageData = context.createImageData(width, height);
  8743. var castData = (imageData.data);
  8744. castData.set(data);
  8745. context.putImageData(imageData, 0, 0);
  8746. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8747. }
  8748. };
  8749. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8750. if (mimeType === void 0) { mimeType = "image/png"; }
  8751. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8752. if (successCallback) {
  8753. successCallback(base64Image);
  8754. }
  8755. else {
  8756. // We need HTMLCanvasElement.toBlob for HD screenshots
  8757. if (!screenshotCanvas.toBlob) {
  8758. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8759. screenshotCanvas.toBlob = function (callback, type, quality) {
  8760. var _this = this;
  8761. setTimeout(function () {
  8762. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8763. for (var i = 0; i < len; i++) {
  8764. arr[i] = binStr.charCodeAt(i);
  8765. }
  8766. callback(new Blob([arr], { type: type || 'image/png' }));
  8767. });
  8768. };
  8769. }
  8770. screenshotCanvas.toBlob(function (blob) {
  8771. var url = URL.createObjectURL(blob);
  8772. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8773. if (("download" in document.createElement("a"))) {
  8774. var a = window.document.createElement("a");
  8775. a.href = url;
  8776. if (fileName) {
  8777. a.setAttribute("download", fileName);
  8778. }
  8779. else {
  8780. var date = new Date();
  8781. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8782. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8783. }
  8784. window.document.body.appendChild(a);
  8785. a.addEventListener("click", function () {
  8786. if (a.parentElement) {
  8787. a.parentElement.removeChild(a);
  8788. }
  8789. });
  8790. a.click();
  8791. }
  8792. else {
  8793. var newWindow = window.open("");
  8794. if (!newWindow)
  8795. return;
  8796. var img = newWindow.document.createElement("img");
  8797. img.onload = function () {
  8798. // no longer need to read the blob so it's revoked
  8799. URL.revokeObjectURL(url);
  8800. };
  8801. img.src = url;
  8802. newWindow.document.body.appendChild(img);
  8803. }
  8804. });
  8805. }
  8806. };
  8807. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8808. if (mimeType === void 0) { mimeType = "image/png"; }
  8809. var width;
  8810. var height;
  8811. // If a precision value is specified
  8812. if (size.precision) {
  8813. width = Math.round(engine.getRenderWidth() * size.precision);
  8814. height = Math.round(width / engine.getAspectRatio(camera));
  8815. }
  8816. else if (size.width && size.height) {
  8817. width = size.width;
  8818. height = size.height;
  8819. }
  8820. else if (size.width && !size.height) {
  8821. width = size.width;
  8822. height = Math.round(width / engine.getAspectRatio(camera));
  8823. }
  8824. else if (size.height && !size.width) {
  8825. height = size.height;
  8826. width = Math.round(height * engine.getAspectRatio(camera));
  8827. }
  8828. else if (!isNaN(size)) {
  8829. height = size;
  8830. width = size;
  8831. }
  8832. else {
  8833. Tools.Error("Invalid 'size' parameter !");
  8834. return;
  8835. }
  8836. if (!screenshotCanvas) {
  8837. screenshotCanvas = document.createElement('canvas');
  8838. }
  8839. screenshotCanvas.width = width;
  8840. screenshotCanvas.height = height;
  8841. var renderContext = screenshotCanvas.getContext("2d");
  8842. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8843. var newWidth = width;
  8844. var newHeight = newWidth / ratio;
  8845. if (newHeight > height) {
  8846. newHeight = height;
  8847. newWidth = newHeight * ratio;
  8848. }
  8849. var offsetX = Math.max(0, width - newWidth) / 2;
  8850. var offsetY = Math.max(0, height - newHeight) / 2;
  8851. var renderingCanvas = engine.getRenderingCanvas();
  8852. if (renderContext && renderingCanvas) {
  8853. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8854. }
  8855. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8856. };
  8857. /**
  8858. * Generates an image screenshot from the specified camera.
  8859. *
  8860. * @param engine The engine to use for rendering
  8861. * @param camera The camera to use for rendering
  8862. * @param size This parameter can be set to a single number or to an object with the
  8863. * following (optional) properties: precision, width, height. If a single number is passed,
  8864. * it will be used for both width and height. If an object is passed, the screenshot size
  8865. * will be derived from the parameters. The precision property is a multiplier allowing
  8866. * rendering at a higher or lower resolution.
  8867. * @param successCallback The callback receives a single parameter which contains the
  8868. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8869. * src parameter of an <img> to display it.
  8870. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8871. * Check your browser for supported MIME types.
  8872. * @param samples Texture samples (default: 1)
  8873. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8874. * @param fileName A name for for the downloaded file.
  8875. * @constructor
  8876. */
  8877. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8878. if (mimeType === void 0) { mimeType = "image/png"; }
  8879. if (samples === void 0) { samples = 1; }
  8880. if (antialiasing === void 0) { antialiasing = false; }
  8881. var width;
  8882. var height;
  8883. //If a precision value is specified
  8884. if (size.precision) {
  8885. width = Math.round(engine.getRenderWidth() * size.precision);
  8886. height = Math.round(width / engine.getAspectRatio(camera));
  8887. size = { width: width, height: height };
  8888. }
  8889. else if (size.width && size.height) {
  8890. width = size.width;
  8891. height = size.height;
  8892. }
  8893. else if (size.width && !size.height) {
  8894. width = size.width;
  8895. height = Math.round(width / engine.getAspectRatio(camera));
  8896. size = { width: width, height: height };
  8897. }
  8898. else if (size.height && !size.width) {
  8899. height = size.height;
  8900. width = Math.round(height * engine.getAspectRatio(camera));
  8901. size = { width: width, height: height };
  8902. }
  8903. else if (!isNaN(size)) {
  8904. height = size;
  8905. width = size;
  8906. }
  8907. else {
  8908. Tools.Error("Invalid 'size' parameter !");
  8909. return;
  8910. }
  8911. var scene = camera.getScene();
  8912. var previousCamera = null;
  8913. if (scene.activeCamera !== camera) {
  8914. previousCamera = scene.activeCamera;
  8915. scene.activeCamera = camera;
  8916. }
  8917. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8918. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8919. texture.renderList = null;
  8920. texture.samples = samples;
  8921. if (antialiasing) {
  8922. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8923. }
  8924. texture.onAfterRenderObservable.add(function () {
  8925. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8926. });
  8927. scene.incrementRenderId();
  8928. scene.resetCachedMaterial();
  8929. texture.render(true);
  8930. texture.dispose();
  8931. if (previousCamera) {
  8932. scene.activeCamera = previousCamera;
  8933. }
  8934. camera.getProjectionMatrix(true); // Force cache refresh;
  8935. };
  8936. // XHR response validator for local file scenario
  8937. Tools.ValidateXHRData = function (xhr, dataType) {
  8938. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8939. if (dataType === void 0) { dataType = 7; }
  8940. try {
  8941. if (dataType & 1) {
  8942. if (xhr.responseText && xhr.responseText.length > 0) {
  8943. return true;
  8944. }
  8945. else if (dataType === 1) {
  8946. return false;
  8947. }
  8948. }
  8949. if (dataType & 2) {
  8950. // Check header width and height since there is no "TGA" magic number
  8951. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8952. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8953. return true;
  8954. }
  8955. else if (dataType === 2) {
  8956. return false;
  8957. }
  8958. }
  8959. if (dataType & 4) {
  8960. // Check for the "DDS" magic number
  8961. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8962. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8963. return true;
  8964. }
  8965. else {
  8966. return false;
  8967. }
  8968. }
  8969. }
  8970. catch (e) {
  8971. // Global protection
  8972. }
  8973. return false;
  8974. };
  8975. /**
  8976. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8977. * Be aware Math.random() could cause collisions, but:
  8978. * "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"
  8979. */
  8980. Tools.RandomId = function () {
  8981. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8982. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8983. return v.toString(16);
  8984. });
  8985. };
  8986. /**
  8987. * Test if the given uri is a base64 string.
  8988. * @param uri The uri to test
  8989. * @return True if the uri is a base64 string or false otherwise.
  8990. */
  8991. Tools.IsBase64 = function (uri) {
  8992. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8993. };
  8994. /**
  8995. * Decode the given base64 uri.
  8996. * @param uri The uri to decode
  8997. * @return The decoded base64 data.
  8998. */
  8999. Tools.DecodeBase64 = function (uri) {
  9000. var decodedString = atob(uri.split(",")[1]);
  9001. var bufferLength = decodedString.length;
  9002. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9003. for (var i = 0; i < bufferLength; i++) {
  9004. bufferView[i] = decodedString.charCodeAt(i);
  9005. }
  9006. return bufferView.buffer;
  9007. };
  9008. Object.defineProperty(Tools, "NoneLogLevel", {
  9009. get: function () {
  9010. return Tools._NoneLogLevel;
  9011. },
  9012. enumerable: true,
  9013. configurable: true
  9014. });
  9015. Object.defineProperty(Tools, "MessageLogLevel", {
  9016. get: function () {
  9017. return Tools._MessageLogLevel;
  9018. },
  9019. enumerable: true,
  9020. configurable: true
  9021. });
  9022. Object.defineProperty(Tools, "WarningLogLevel", {
  9023. get: function () {
  9024. return Tools._WarningLogLevel;
  9025. },
  9026. enumerable: true,
  9027. configurable: true
  9028. });
  9029. Object.defineProperty(Tools, "ErrorLogLevel", {
  9030. get: function () {
  9031. return Tools._ErrorLogLevel;
  9032. },
  9033. enumerable: true,
  9034. configurable: true
  9035. });
  9036. Object.defineProperty(Tools, "AllLogLevel", {
  9037. get: function () {
  9038. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9039. },
  9040. enumerable: true,
  9041. configurable: true
  9042. });
  9043. Tools._AddLogEntry = function (entry) {
  9044. Tools._LogCache = entry + Tools._LogCache;
  9045. if (Tools.OnNewCacheEntry) {
  9046. Tools.OnNewCacheEntry(entry);
  9047. }
  9048. };
  9049. Tools._FormatMessage = function (message) {
  9050. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9051. var date = new Date();
  9052. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9053. };
  9054. Tools._LogDisabled = function (message) {
  9055. // nothing to do
  9056. };
  9057. Tools._LogEnabled = function (message) {
  9058. var formattedMessage = Tools._FormatMessage(message);
  9059. console.log("BJS - " + formattedMessage);
  9060. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9061. Tools._AddLogEntry(entry);
  9062. };
  9063. Tools._WarnDisabled = function (message) {
  9064. // nothing to do
  9065. };
  9066. Tools._WarnEnabled = function (message) {
  9067. var formattedMessage = Tools._FormatMessage(message);
  9068. console.warn("BJS - " + formattedMessage);
  9069. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9070. Tools._AddLogEntry(entry);
  9071. };
  9072. Tools._ErrorDisabled = function (message) {
  9073. // nothing to do
  9074. };
  9075. Tools._ErrorEnabled = function (message) {
  9076. Tools.errorsCount++;
  9077. var formattedMessage = Tools._FormatMessage(message);
  9078. console.error("BJS - " + formattedMessage);
  9079. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9080. Tools._AddLogEntry(entry);
  9081. };
  9082. Object.defineProperty(Tools, "LogCache", {
  9083. get: function () {
  9084. return Tools._LogCache;
  9085. },
  9086. enumerable: true,
  9087. configurable: true
  9088. });
  9089. Tools.ClearLogCache = function () {
  9090. Tools._LogCache = "";
  9091. Tools.errorsCount = 0;
  9092. };
  9093. Object.defineProperty(Tools, "LogLevels", {
  9094. set: function (level) {
  9095. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9096. Tools.Log = Tools._LogEnabled;
  9097. }
  9098. else {
  9099. Tools.Log = Tools._LogDisabled;
  9100. }
  9101. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9102. Tools.Warn = Tools._WarnEnabled;
  9103. }
  9104. else {
  9105. Tools.Warn = Tools._WarnDisabled;
  9106. }
  9107. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9108. Tools.Error = Tools._ErrorEnabled;
  9109. }
  9110. else {
  9111. Tools.Error = Tools._ErrorDisabled;
  9112. }
  9113. },
  9114. enumerable: true,
  9115. configurable: true
  9116. });
  9117. Tools.IsWindowObjectExist = function () {
  9118. return (typeof window) !== "undefined";
  9119. };
  9120. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9121. get: function () {
  9122. return Tools._PerformanceNoneLogLevel;
  9123. },
  9124. enumerable: true,
  9125. configurable: true
  9126. });
  9127. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9128. get: function () {
  9129. return Tools._PerformanceUserMarkLogLevel;
  9130. },
  9131. enumerable: true,
  9132. configurable: true
  9133. });
  9134. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9135. get: function () {
  9136. return Tools._PerformanceConsoleLogLevel;
  9137. },
  9138. enumerable: true,
  9139. configurable: true
  9140. });
  9141. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9142. set: function (level) {
  9143. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9144. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9145. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9146. return;
  9147. }
  9148. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9149. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9150. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9151. return;
  9152. }
  9153. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9154. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9155. },
  9156. enumerable: true,
  9157. configurable: true
  9158. });
  9159. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9160. };
  9161. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9162. };
  9163. Tools._StartUserMark = function (counterName, condition) {
  9164. if (condition === void 0) { condition = true; }
  9165. if (!Tools._performance) {
  9166. if (!Tools.IsWindowObjectExist()) {
  9167. return;
  9168. }
  9169. Tools._performance = window.performance;
  9170. }
  9171. if (!condition || !Tools._performance.mark) {
  9172. return;
  9173. }
  9174. Tools._performance.mark(counterName + "-Begin");
  9175. };
  9176. Tools._EndUserMark = function (counterName, condition) {
  9177. if (condition === void 0) { condition = true; }
  9178. if (!condition || !Tools._performance.mark) {
  9179. return;
  9180. }
  9181. Tools._performance.mark(counterName + "-End");
  9182. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9183. };
  9184. Tools._StartPerformanceConsole = function (counterName, condition) {
  9185. if (condition === void 0) { condition = true; }
  9186. if (!condition) {
  9187. return;
  9188. }
  9189. Tools._StartUserMark(counterName, condition);
  9190. if (console.time) {
  9191. console.time(counterName);
  9192. }
  9193. };
  9194. Tools._EndPerformanceConsole = function (counterName, condition) {
  9195. if (condition === void 0) { condition = true; }
  9196. if (!condition) {
  9197. return;
  9198. }
  9199. Tools._EndUserMark(counterName, condition);
  9200. if (console.time) {
  9201. console.timeEnd(counterName);
  9202. }
  9203. };
  9204. Object.defineProperty(Tools, "Now", {
  9205. get: function () {
  9206. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9207. return window.performance.now();
  9208. }
  9209. return new Date().getTime();
  9210. },
  9211. enumerable: true,
  9212. configurable: true
  9213. });
  9214. /**
  9215. * This method will return the name of the class used to create the instance of the given object.
  9216. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9217. * @param object the object to get the class name from
  9218. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9219. */
  9220. Tools.GetClassName = function (object, isType) {
  9221. if (isType === void 0) { isType = false; }
  9222. var name = null;
  9223. if (!isType && object.getClassName) {
  9224. name = object.getClassName();
  9225. }
  9226. else {
  9227. if (object instanceof Object) {
  9228. var classObj = isType ? object : Object.getPrototypeOf(object);
  9229. name = classObj.constructor["__bjsclassName__"];
  9230. }
  9231. if (!name) {
  9232. name = typeof object;
  9233. }
  9234. }
  9235. return name;
  9236. };
  9237. Tools.First = function (array, predicate) {
  9238. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9239. var el = array_1[_i];
  9240. if (predicate(el)) {
  9241. return el;
  9242. }
  9243. }
  9244. return null;
  9245. };
  9246. /**
  9247. * This method will return the name of the full name of the class, including its owning module (if any).
  9248. * 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).
  9249. * @param object the object to get the class name from
  9250. * @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.
  9251. */
  9252. Tools.getFullClassName = function (object, isType) {
  9253. if (isType === void 0) { isType = false; }
  9254. var className = null;
  9255. var moduleName = null;
  9256. if (!isType && object.getClassName) {
  9257. className = object.getClassName();
  9258. }
  9259. else {
  9260. if (object instanceof Object) {
  9261. var classObj = isType ? object : Object.getPrototypeOf(object);
  9262. className = classObj.constructor["__bjsclassName__"];
  9263. moduleName = classObj.constructor["__bjsmoduleName__"];
  9264. }
  9265. if (!className) {
  9266. className = typeof object;
  9267. }
  9268. }
  9269. if (!className) {
  9270. return null;
  9271. }
  9272. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9273. };
  9274. /**
  9275. * 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.
  9276. * @param array
  9277. */
  9278. Tools.arrayOrStringFeeder = function (array) {
  9279. return function (index) {
  9280. if (index >= array.length) {
  9281. return null;
  9282. }
  9283. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9284. if (val && val.getHashCode) {
  9285. val = val.getHashCode();
  9286. }
  9287. if (typeof val === "string") {
  9288. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9289. }
  9290. return val;
  9291. };
  9292. };
  9293. /**
  9294. * Compute the hashCode of a stream of number
  9295. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9296. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9297. * @return the hash code computed
  9298. */
  9299. Tools.hashCodeFromStream = function (feeder) {
  9300. // Based from here: http://stackoverflow.com/a/7616484/802124
  9301. var hash = 0;
  9302. var index = 0;
  9303. var chr = feeder(index++);
  9304. while (chr != null) {
  9305. hash = ((hash << 5) - hash) + chr;
  9306. hash |= 0; // Convert to 32bit integer
  9307. chr = feeder(index++);
  9308. }
  9309. return hash;
  9310. };
  9311. /**
  9312. * Returns a promise that resolves after the given amount of time.
  9313. * @param delay Number of milliseconds to delay
  9314. * @returns Promise that resolves after the given amount of time
  9315. */
  9316. Tools.DelayAsync = function (delay) {
  9317. return new Promise(function (resolve) {
  9318. setTimeout(function () {
  9319. resolve();
  9320. }, delay);
  9321. });
  9322. };
  9323. Tools.BaseUrl = "";
  9324. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9325. /**
  9326. * Default behaviour for cors in the application.
  9327. * It can be a string if the expected behavior is identical in the entire app.
  9328. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9329. */
  9330. Tools.CorsBehavior = "anonymous";
  9331. Tools.UseFallbackTexture = true;
  9332. /**
  9333. * Use this object to register external classes like custom textures or material
  9334. * to allow the laoders to instantiate them
  9335. */
  9336. Tools.RegisteredExternalClasses = {};
  9337. // Used in case of a texture loading problem
  9338. 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";
  9339. Tools.PreprocessUrl = function (url) {
  9340. return url;
  9341. };
  9342. // Logs
  9343. Tools._NoneLogLevel = 0;
  9344. Tools._MessageLogLevel = 1;
  9345. Tools._WarningLogLevel = 2;
  9346. Tools._ErrorLogLevel = 4;
  9347. Tools._LogCache = "";
  9348. Tools.errorsCount = 0;
  9349. Tools.Log = Tools._LogEnabled;
  9350. Tools.Warn = Tools._WarnEnabled;
  9351. Tools.Error = Tools._ErrorEnabled;
  9352. // Performances
  9353. Tools._PerformanceNoneLogLevel = 0;
  9354. Tools._PerformanceUserMarkLogLevel = 1;
  9355. Tools._PerformanceConsoleLogLevel = 2;
  9356. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9357. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9358. return Tools;
  9359. }());
  9360. BABYLON.Tools = Tools;
  9361. /**
  9362. * This class is used to track a performance counter which is number based.
  9363. * The user has access to many properties which give statistics of different nature
  9364. *
  9365. * The implementer can track two kinds of Performance Counter: time and count
  9366. * 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.
  9367. * 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.
  9368. */
  9369. var PerfCounter = /** @class */ (function () {
  9370. function PerfCounter() {
  9371. this._startMonitoringTime = 0;
  9372. this._min = 0;
  9373. this._max = 0;
  9374. this._average = 0;
  9375. this._lastSecAverage = 0;
  9376. this._current = 0;
  9377. this._totalValueCount = 0;
  9378. this._totalAccumulated = 0;
  9379. this._lastSecAccumulated = 0;
  9380. this._lastSecTime = 0;
  9381. this._lastSecValueCount = 0;
  9382. }
  9383. Object.defineProperty(PerfCounter.prototype, "min", {
  9384. /**
  9385. * Returns the smallest value ever
  9386. */
  9387. get: function () {
  9388. return this._min;
  9389. },
  9390. enumerable: true,
  9391. configurable: true
  9392. });
  9393. Object.defineProperty(PerfCounter.prototype, "max", {
  9394. /**
  9395. * Returns the biggest value ever
  9396. */
  9397. get: function () {
  9398. return this._max;
  9399. },
  9400. enumerable: true,
  9401. configurable: true
  9402. });
  9403. Object.defineProperty(PerfCounter.prototype, "average", {
  9404. /**
  9405. * Returns the average value since the performance counter is running
  9406. */
  9407. get: function () {
  9408. return this._average;
  9409. },
  9410. enumerable: true,
  9411. configurable: true
  9412. });
  9413. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9414. /**
  9415. * Returns the average value of the last second the counter was monitored
  9416. */
  9417. get: function () {
  9418. return this._lastSecAverage;
  9419. },
  9420. enumerable: true,
  9421. configurable: true
  9422. });
  9423. Object.defineProperty(PerfCounter.prototype, "current", {
  9424. /**
  9425. * Returns the current value
  9426. */
  9427. get: function () {
  9428. return this._current;
  9429. },
  9430. enumerable: true,
  9431. configurable: true
  9432. });
  9433. Object.defineProperty(PerfCounter.prototype, "total", {
  9434. get: function () {
  9435. return this._totalAccumulated;
  9436. },
  9437. enumerable: true,
  9438. configurable: true
  9439. });
  9440. Object.defineProperty(PerfCounter.prototype, "count", {
  9441. get: function () {
  9442. return this._totalValueCount;
  9443. },
  9444. enumerable: true,
  9445. configurable: true
  9446. });
  9447. /**
  9448. * Call this method to start monitoring a new frame.
  9449. * 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.
  9450. */
  9451. PerfCounter.prototype.fetchNewFrame = function () {
  9452. this._totalValueCount++;
  9453. this._current = 0;
  9454. this._lastSecValueCount++;
  9455. };
  9456. /**
  9457. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9458. * @param newCount the count value to add to the monitored count
  9459. * @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.
  9460. */
  9461. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9462. if (!PerfCounter.Enabled) {
  9463. return;
  9464. }
  9465. this._current += newCount;
  9466. if (fetchResult) {
  9467. this._fetchResult();
  9468. }
  9469. };
  9470. /**
  9471. * Start monitoring this performance counter
  9472. */
  9473. PerfCounter.prototype.beginMonitoring = function () {
  9474. if (!PerfCounter.Enabled) {
  9475. return;
  9476. }
  9477. this._startMonitoringTime = Tools.Now;
  9478. };
  9479. /**
  9480. * Compute the time lapsed since the previous beginMonitoring() call.
  9481. * @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
  9482. */
  9483. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9484. if (newFrame === void 0) { newFrame = true; }
  9485. if (!PerfCounter.Enabled) {
  9486. return;
  9487. }
  9488. if (newFrame) {
  9489. this.fetchNewFrame();
  9490. }
  9491. var currentTime = Tools.Now;
  9492. this._current = currentTime - this._startMonitoringTime;
  9493. if (newFrame) {
  9494. this._fetchResult();
  9495. }
  9496. };
  9497. PerfCounter.prototype._fetchResult = function () {
  9498. this._totalAccumulated += this._current;
  9499. this._lastSecAccumulated += this._current;
  9500. // Min/Max update
  9501. this._min = Math.min(this._min, this._current);
  9502. this._max = Math.max(this._max, this._current);
  9503. this._average = this._totalAccumulated / this._totalValueCount;
  9504. // Reset last sec?
  9505. var now = Tools.Now;
  9506. if ((now - this._lastSecTime) > 1000) {
  9507. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9508. this._lastSecTime = now;
  9509. this._lastSecAccumulated = 0;
  9510. this._lastSecValueCount = 0;
  9511. }
  9512. };
  9513. PerfCounter.Enabled = true;
  9514. return PerfCounter;
  9515. }());
  9516. BABYLON.PerfCounter = PerfCounter;
  9517. /**
  9518. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9519. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9520. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9521. * @param name The name of the class, case should be preserved
  9522. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9523. */
  9524. function className(name, module) {
  9525. return function (target) {
  9526. target["__bjsclassName__"] = name;
  9527. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9528. };
  9529. }
  9530. BABYLON.className = className;
  9531. /**
  9532. * An implementation of a loop for asynchronous functions.
  9533. */
  9534. var AsyncLoop = /** @class */ (function () {
  9535. /**
  9536. * Constroctor.
  9537. * @param iterations the number of iterations.
  9538. * @param _fn the function to run each iteration
  9539. * @param _successCallback the callback that will be called upon succesful execution
  9540. * @param offset starting offset.
  9541. */
  9542. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9543. if (offset === void 0) { offset = 0; }
  9544. this.iterations = iterations;
  9545. this._fn = _fn;
  9546. this._successCallback = _successCallback;
  9547. this.index = offset - 1;
  9548. this._done = false;
  9549. }
  9550. /**
  9551. * Execute the next iteration. Must be called after the last iteration was finished.
  9552. */
  9553. AsyncLoop.prototype.executeNext = function () {
  9554. if (!this._done) {
  9555. if (this.index + 1 < this.iterations) {
  9556. ++this.index;
  9557. this._fn(this);
  9558. }
  9559. else {
  9560. this.breakLoop();
  9561. }
  9562. }
  9563. };
  9564. /**
  9565. * Break the loop and run the success callback.
  9566. */
  9567. AsyncLoop.prototype.breakLoop = function () {
  9568. this._done = true;
  9569. this._successCallback();
  9570. };
  9571. /**
  9572. * Helper function
  9573. */
  9574. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9575. if (offset === void 0) { offset = 0; }
  9576. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9577. loop.executeNext();
  9578. return loop;
  9579. };
  9580. /**
  9581. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9582. * @param iterations total number of iterations
  9583. * @param syncedIterations number of synchronous iterations in each async iteration.
  9584. * @param fn the function to call each iteration.
  9585. * @param callback a success call back that will be called when iterating stops.
  9586. * @param breakFunction a break condition (optional)
  9587. * @param timeout timeout settings for the setTimeout function. default - 0.
  9588. * @constructor
  9589. */
  9590. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9591. if (timeout === void 0) { timeout = 0; }
  9592. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9593. if (breakFunction && breakFunction())
  9594. loop.breakLoop();
  9595. else {
  9596. setTimeout(function () {
  9597. for (var i = 0; i < syncedIterations; ++i) {
  9598. var iteration = (loop.index * syncedIterations) + i;
  9599. if (iteration >= iterations)
  9600. break;
  9601. fn(iteration);
  9602. if (breakFunction && breakFunction()) {
  9603. loop.breakLoop();
  9604. break;
  9605. }
  9606. }
  9607. loop.executeNext();
  9608. }, timeout);
  9609. }
  9610. }, callback);
  9611. };
  9612. return AsyncLoop;
  9613. }());
  9614. BABYLON.AsyncLoop = AsyncLoop;
  9615. })(BABYLON || (BABYLON = {}));
  9616. //# sourceMappingURL=babylon.tools.js.map
  9617. "use strict";
  9618. var BABYLON;
  9619. (function (BABYLON) {
  9620. var PromiseStates;
  9621. (function (PromiseStates) {
  9622. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9623. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9624. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9625. })(PromiseStates || (PromiseStates = {}));
  9626. var FulFillmentAgregator = /** @class */ (function () {
  9627. function FulFillmentAgregator() {
  9628. this.count = 0;
  9629. this.target = 0;
  9630. this.results = [];
  9631. }
  9632. return FulFillmentAgregator;
  9633. }());
  9634. var InternalPromise = /** @class */ (function () {
  9635. function InternalPromise(resolver) {
  9636. var _this = this;
  9637. this._state = PromiseStates.Pending;
  9638. this._children = new Array();
  9639. this._rejectWasConsumed = false;
  9640. if (!resolver) {
  9641. return;
  9642. }
  9643. try {
  9644. resolver(function (value) {
  9645. _this._resolve(value);
  9646. }, function (reason) {
  9647. _this._reject(reason);
  9648. });
  9649. }
  9650. catch (e) {
  9651. this._reject(e);
  9652. }
  9653. }
  9654. InternalPromise.prototype.catch = function (onRejected) {
  9655. return this.then(undefined, onRejected);
  9656. };
  9657. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9658. var _this = this;
  9659. var newPromise = new InternalPromise();
  9660. newPromise._onFulfilled = onFulfilled;
  9661. newPromise._onRejected = onRejected;
  9662. // Composition
  9663. this._children.push(newPromise);
  9664. if (this._state !== PromiseStates.Pending) {
  9665. BABYLON.Tools.SetImmediate(function () {
  9666. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9667. var returnedValue = newPromise._resolve(_this._result);
  9668. if (returnedValue !== undefined && returnedValue !== null) {
  9669. if (returnedValue._state !== undefined) {
  9670. var returnedPromise = returnedValue;
  9671. newPromise._children.push(returnedPromise);
  9672. newPromise = returnedPromise;
  9673. }
  9674. else {
  9675. newPromise._result = returnedValue;
  9676. }
  9677. }
  9678. }
  9679. else {
  9680. newPromise._reject(_this._reason);
  9681. }
  9682. });
  9683. }
  9684. return newPromise;
  9685. };
  9686. InternalPromise.prototype._moveChildren = function (children) {
  9687. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9688. if (this._state === PromiseStates.Fulfilled) {
  9689. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9690. var child = _b[_i];
  9691. child._resolve(this._result);
  9692. }
  9693. }
  9694. else if (this._state === PromiseStates.Rejected) {
  9695. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9696. var child = _d[_c];
  9697. child._reject(this._reason);
  9698. }
  9699. }
  9700. var _a;
  9701. };
  9702. InternalPromise.prototype._resolve = function (value) {
  9703. try {
  9704. this._state = PromiseStates.Fulfilled;
  9705. this._result = value;
  9706. var returnedValue = null;
  9707. if (this._onFulfilled) {
  9708. returnedValue = this._onFulfilled(value);
  9709. }
  9710. if (returnedValue !== undefined && returnedValue !== null) {
  9711. if (returnedValue._state !== undefined) {
  9712. // Transmit children
  9713. var returnedPromise = returnedValue;
  9714. returnedPromise._moveChildren(this._children);
  9715. }
  9716. else {
  9717. value = returnedValue;
  9718. }
  9719. }
  9720. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9721. var child = _a[_i];
  9722. child._resolve(value);
  9723. }
  9724. this._children.length = 0;
  9725. delete this._onFulfilled;
  9726. delete this._onRejected;
  9727. return returnedValue;
  9728. }
  9729. catch (e) {
  9730. this._reject(e, true);
  9731. }
  9732. return null;
  9733. };
  9734. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9735. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9736. this._state = PromiseStates.Rejected;
  9737. this._reason = reason;
  9738. if (this._onRejected && !onLocalThrow) {
  9739. try {
  9740. this._onRejected(reason);
  9741. this._rejectWasConsumed = true;
  9742. }
  9743. catch (e) {
  9744. reason = e;
  9745. }
  9746. }
  9747. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9748. var child = _a[_i];
  9749. if (this._rejectWasConsumed) {
  9750. child._resolve(null);
  9751. }
  9752. else {
  9753. child._reject(reason);
  9754. }
  9755. }
  9756. this._children.length = 0;
  9757. delete this._onFulfilled;
  9758. delete this._onRejected;
  9759. };
  9760. InternalPromise.resolve = function (value) {
  9761. var newPromise = new InternalPromise();
  9762. newPromise._resolve(value);
  9763. return newPromise;
  9764. };
  9765. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9766. promise.then(function (value) {
  9767. agregator.results[index] = value;
  9768. agregator.count++;
  9769. if (agregator.count === agregator.target) {
  9770. agregator.rootPromise._resolve(agregator.results);
  9771. }
  9772. return null;
  9773. }, function (reason) {
  9774. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9775. agregator.rootPromise._reject(reason);
  9776. }
  9777. });
  9778. };
  9779. InternalPromise.all = function (promises) {
  9780. var newPromise = new InternalPromise();
  9781. var agregator = new FulFillmentAgregator();
  9782. agregator.target = promises.length;
  9783. agregator.rootPromise = newPromise;
  9784. if (promises.length) {
  9785. for (var index = 0; index < promises.length; index++) {
  9786. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9787. }
  9788. }
  9789. else {
  9790. newPromise._resolve([]);
  9791. }
  9792. return newPromise;
  9793. };
  9794. InternalPromise.race = function (promises) {
  9795. var newPromise = new InternalPromise();
  9796. if (promises.length) {
  9797. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9798. var promise = promises_1[_i];
  9799. promise.then(function (value) {
  9800. if (newPromise) {
  9801. newPromise._resolve(value);
  9802. newPromise = null;
  9803. }
  9804. return null;
  9805. }, function (reason) {
  9806. if (newPromise) {
  9807. newPromise._reject(reason);
  9808. newPromise = null;
  9809. }
  9810. });
  9811. }
  9812. }
  9813. return newPromise;
  9814. };
  9815. return InternalPromise;
  9816. }());
  9817. /**
  9818. * Helper class that provides a small promise polyfill
  9819. */
  9820. var PromisePolyfill = /** @class */ (function () {
  9821. function PromisePolyfill() {
  9822. }
  9823. /**
  9824. * Static function used to check if the polyfill is required
  9825. * If this is the case then the function will inject the polyfill to window.Promise
  9826. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9827. */
  9828. PromisePolyfill.Apply = function (force) {
  9829. if (force === void 0) { force = false; }
  9830. if (force || typeof Promise === 'undefined') {
  9831. var root = window;
  9832. root.Promise = InternalPromise;
  9833. }
  9834. };
  9835. return PromisePolyfill;
  9836. }());
  9837. BABYLON.PromisePolyfill = PromisePolyfill;
  9838. })(BABYLON || (BABYLON = {}));
  9839. //# sourceMappingURL=babylon.promise.js.map
  9840. "use strict";
  9841. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9842. var BABYLON;
  9843. (function (BABYLON) {
  9844. /**
  9845. * Helper class to push actions to a pool of workers.
  9846. */
  9847. var WorkerPool = /** @class */ (function () {
  9848. /**
  9849. * Constructor
  9850. * @param workers Array of workers to use for actions
  9851. */
  9852. function WorkerPool(workers) {
  9853. this._pendingActions = new Array();
  9854. this._workerInfos = workers.map(function (worker) { return ({
  9855. worker: worker,
  9856. active: false
  9857. }); });
  9858. }
  9859. /**
  9860. * Terminates all workers and clears any pending actions.
  9861. */
  9862. WorkerPool.prototype.dispose = function () {
  9863. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9864. var workerInfo = _a[_i];
  9865. workerInfo.worker.terminate();
  9866. }
  9867. delete this._workerInfos;
  9868. delete this._pendingActions;
  9869. };
  9870. /**
  9871. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9872. * pended until a worker has completed its action.
  9873. * @param action The action to perform. Call onComplete when the action is complete.
  9874. */
  9875. WorkerPool.prototype.push = function (action) {
  9876. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9877. var workerInfo = _a[_i];
  9878. if (!workerInfo.active) {
  9879. this._execute(workerInfo, action);
  9880. return;
  9881. }
  9882. }
  9883. this._pendingActions.push(action);
  9884. };
  9885. WorkerPool.prototype._execute = function (workerInfo, action) {
  9886. var _this = this;
  9887. workerInfo.active = true;
  9888. action(workerInfo.worker, function () {
  9889. workerInfo.active = false;
  9890. var nextAction = _this._pendingActions.shift();
  9891. if (nextAction) {
  9892. _this._execute(workerInfo, nextAction);
  9893. }
  9894. });
  9895. };
  9896. return WorkerPool;
  9897. }());
  9898. BABYLON.WorkerPool = WorkerPool;
  9899. })(BABYLON || (BABYLON = {}));
  9900. //# sourceMappingURL=babylon.workerPool.js.map
  9901. "use strict";
  9902. var BABYLON;
  9903. (function (BABYLON) {
  9904. var _AlphaState = /** @class */ (function () {
  9905. /**
  9906. * Initializes the state.
  9907. */
  9908. function _AlphaState() {
  9909. this._isAlphaBlendDirty = false;
  9910. this._isBlendFunctionParametersDirty = false;
  9911. this._isBlendEquationParametersDirty = false;
  9912. this._isBlendConstantsDirty = false;
  9913. this._alphaBlend = false;
  9914. this._blendFunctionParameters = new Array(4);
  9915. this._blendEquationParameters = new Array(2);
  9916. this._blendConstants = new Array(4);
  9917. this.reset();
  9918. }
  9919. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9920. get: function () {
  9921. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9922. },
  9923. enumerable: true,
  9924. configurable: true
  9925. });
  9926. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9927. get: function () {
  9928. return this._alphaBlend;
  9929. },
  9930. set: function (value) {
  9931. if (this._alphaBlend === value) {
  9932. return;
  9933. }
  9934. this._alphaBlend = value;
  9935. this._isAlphaBlendDirty = true;
  9936. },
  9937. enumerable: true,
  9938. configurable: true
  9939. });
  9940. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9941. if (this._blendConstants[0] === r &&
  9942. this._blendConstants[1] === g &&
  9943. this._blendConstants[2] === b &&
  9944. this._blendConstants[3] === a) {
  9945. return;
  9946. }
  9947. this._blendConstants[0] = r;
  9948. this._blendConstants[1] = g;
  9949. this._blendConstants[2] = b;
  9950. this._blendConstants[3] = a;
  9951. this._isBlendConstantsDirty = true;
  9952. };
  9953. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9954. if (this._blendFunctionParameters[0] === value0 &&
  9955. this._blendFunctionParameters[1] === value1 &&
  9956. this._blendFunctionParameters[2] === value2 &&
  9957. this._blendFunctionParameters[3] === value3) {
  9958. return;
  9959. }
  9960. this._blendFunctionParameters[0] = value0;
  9961. this._blendFunctionParameters[1] = value1;
  9962. this._blendFunctionParameters[2] = value2;
  9963. this._blendFunctionParameters[3] = value3;
  9964. this._isBlendFunctionParametersDirty = true;
  9965. };
  9966. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9967. if (this._blendEquationParameters[0] === rgb &&
  9968. this._blendEquationParameters[1] === alpha) {
  9969. return;
  9970. }
  9971. this._blendEquationParameters[0] = rgb;
  9972. this._blendEquationParameters[1] = alpha;
  9973. this._isBlendEquationParametersDirty = true;
  9974. };
  9975. _AlphaState.prototype.reset = function () {
  9976. this._alphaBlend = false;
  9977. this._blendFunctionParameters[0] = null;
  9978. this._blendFunctionParameters[1] = null;
  9979. this._blendFunctionParameters[2] = null;
  9980. this._blendFunctionParameters[3] = null;
  9981. this._blendEquationParameters[0] = null;
  9982. this._blendEquationParameters[1] = null;
  9983. this._blendConstants[0] = null;
  9984. this._blendConstants[1] = null;
  9985. this._blendConstants[2] = null;
  9986. this._blendConstants[3] = null;
  9987. this._isAlphaBlendDirty = true;
  9988. this._isBlendFunctionParametersDirty = false;
  9989. this._isBlendEquationParametersDirty = false;
  9990. this._isBlendConstantsDirty = false;
  9991. };
  9992. _AlphaState.prototype.apply = function (gl) {
  9993. if (!this.isDirty) {
  9994. return;
  9995. }
  9996. // Alpha blend
  9997. if (this._isAlphaBlendDirty) {
  9998. if (this._alphaBlend) {
  9999. gl.enable(gl.BLEND);
  10000. }
  10001. else {
  10002. gl.disable(gl.BLEND);
  10003. }
  10004. this._isAlphaBlendDirty = false;
  10005. }
  10006. // Alpha function
  10007. if (this._isBlendFunctionParametersDirty) {
  10008. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10009. this._isBlendFunctionParametersDirty = false;
  10010. }
  10011. // Alpha equation
  10012. if (this._isBlendEquationParametersDirty) {
  10013. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10014. this._isBlendEquationParametersDirty = false;
  10015. }
  10016. // Constants
  10017. if (this._isBlendConstantsDirty) {
  10018. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10019. this._isBlendConstantsDirty = false;
  10020. }
  10021. };
  10022. return _AlphaState;
  10023. }());
  10024. BABYLON._AlphaState = _AlphaState;
  10025. })(BABYLON || (BABYLON = {}));
  10026. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10027. "use strict";
  10028. var BABYLON;
  10029. (function (BABYLON) {
  10030. var _DepthCullingState = /** @class */ (function () {
  10031. /**
  10032. * Initializes the state.
  10033. */
  10034. function _DepthCullingState() {
  10035. this._isDepthTestDirty = false;
  10036. this._isDepthMaskDirty = false;
  10037. this._isDepthFuncDirty = false;
  10038. this._isCullFaceDirty = false;
  10039. this._isCullDirty = false;
  10040. this._isZOffsetDirty = false;
  10041. this._isFrontFaceDirty = false;
  10042. this.reset();
  10043. }
  10044. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10045. get: function () {
  10046. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10047. },
  10048. enumerable: true,
  10049. configurable: true
  10050. });
  10051. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10052. get: function () {
  10053. return this._zOffset;
  10054. },
  10055. set: function (value) {
  10056. if (this._zOffset === value) {
  10057. return;
  10058. }
  10059. this._zOffset = value;
  10060. this._isZOffsetDirty = true;
  10061. },
  10062. enumerable: true,
  10063. configurable: true
  10064. });
  10065. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10066. get: function () {
  10067. return this._cullFace;
  10068. },
  10069. set: function (value) {
  10070. if (this._cullFace === value) {
  10071. return;
  10072. }
  10073. this._cullFace = value;
  10074. this._isCullFaceDirty = true;
  10075. },
  10076. enumerable: true,
  10077. configurable: true
  10078. });
  10079. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10080. get: function () {
  10081. return this._cull;
  10082. },
  10083. set: function (value) {
  10084. if (this._cull === value) {
  10085. return;
  10086. }
  10087. this._cull = value;
  10088. this._isCullDirty = true;
  10089. },
  10090. enumerable: true,
  10091. configurable: true
  10092. });
  10093. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10094. get: function () {
  10095. return this._depthFunc;
  10096. },
  10097. set: function (value) {
  10098. if (this._depthFunc === value) {
  10099. return;
  10100. }
  10101. this._depthFunc = value;
  10102. this._isDepthFuncDirty = true;
  10103. },
  10104. enumerable: true,
  10105. configurable: true
  10106. });
  10107. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10108. get: function () {
  10109. return this._depthMask;
  10110. },
  10111. set: function (value) {
  10112. if (this._depthMask === value) {
  10113. return;
  10114. }
  10115. this._depthMask = value;
  10116. this._isDepthMaskDirty = true;
  10117. },
  10118. enumerable: true,
  10119. configurable: true
  10120. });
  10121. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10122. get: function () {
  10123. return this._depthTest;
  10124. },
  10125. set: function (value) {
  10126. if (this._depthTest === value) {
  10127. return;
  10128. }
  10129. this._depthTest = value;
  10130. this._isDepthTestDirty = true;
  10131. },
  10132. enumerable: true,
  10133. configurable: true
  10134. });
  10135. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10136. get: function () {
  10137. return this._frontFace;
  10138. },
  10139. set: function (value) {
  10140. if (this._frontFace === value) {
  10141. return;
  10142. }
  10143. this._frontFace = value;
  10144. this._isFrontFaceDirty = true;
  10145. },
  10146. enumerable: true,
  10147. configurable: true
  10148. });
  10149. _DepthCullingState.prototype.reset = function () {
  10150. this._depthMask = true;
  10151. this._depthTest = true;
  10152. this._depthFunc = null;
  10153. this._cullFace = null;
  10154. this._cull = null;
  10155. this._zOffset = 0;
  10156. this._frontFace = null;
  10157. this._isDepthTestDirty = true;
  10158. this._isDepthMaskDirty = true;
  10159. this._isDepthFuncDirty = false;
  10160. this._isCullFaceDirty = false;
  10161. this._isCullDirty = false;
  10162. this._isZOffsetDirty = false;
  10163. this._isFrontFaceDirty = false;
  10164. };
  10165. _DepthCullingState.prototype.apply = function (gl) {
  10166. if (!this.isDirty) {
  10167. return;
  10168. }
  10169. // Cull
  10170. if (this._isCullDirty) {
  10171. if (this.cull) {
  10172. gl.enable(gl.CULL_FACE);
  10173. }
  10174. else {
  10175. gl.disable(gl.CULL_FACE);
  10176. }
  10177. this._isCullDirty = false;
  10178. }
  10179. // Cull face
  10180. if (this._isCullFaceDirty) {
  10181. gl.cullFace(this.cullFace);
  10182. this._isCullFaceDirty = false;
  10183. }
  10184. // Depth mask
  10185. if (this._isDepthMaskDirty) {
  10186. gl.depthMask(this.depthMask);
  10187. this._isDepthMaskDirty = false;
  10188. }
  10189. // Depth test
  10190. if (this._isDepthTestDirty) {
  10191. if (this.depthTest) {
  10192. gl.enable(gl.DEPTH_TEST);
  10193. }
  10194. else {
  10195. gl.disable(gl.DEPTH_TEST);
  10196. }
  10197. this._isDepthTestDirty = false;
  10198. }
  10199. // Depth func
  10200. if (this._isDepthFuncDirty) {
  10201. gl.depthFunc(this.depthFunc);
  10202. this._isDepthFuncDirty = false;
  10203. }
  10204. // zOffset
  10205. if (this._isZOffsetDirty) {
  10206. if (this.zOffset) {
  10207. gl.enable(gl.POLYGON_OFFSET_FILL);
  10208. gl.polygonOffset(this.zOffset, 0);
  10209. }
  10210. else {
  10211. gl.disable(gl.POLYGON_OFFSET_FILL);
  10212. }
  10213. this._isZOffsetDirty = false;
  10214. }
  10215. // Front face
  10216. if (this._isFrontFaceDirty) {
  10217. gl.frontFace(this.frontFace);
  10218. this._isFrontFaceDirty = false;
  10219. }
  10220. };
  10221. return _DepthCullingState;
  10222. }());
  10223. BABYLON._DepthCullingState = _DepthCullingState;
  10224. })(BABYLON || (BABYLON = {}));
  10225. //# sourceMappingURL=babylon.depthCullingState.js.map
  10226. "use strict";
  10227. var BABYLON;
  10228. (function (BABYLON) {
  10229. var _StencilState = /** @class */ (function () {
  10230. function _StencilState() {
  10231. this._isStencilTestDirty = false;
  10232. this._isStencilMaskDirty = false;
  10233. this._isStencilFuncDirty = false;
  10234. this._isStencilOpDirty = false;
  10235. this.reset();
  10236. }
  10237. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10238. get: function () {
  10239. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10240. },
  10241. enumerable: true,
  10242. configurable: true
  10243. });
  10244. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10245. get: function () {
  10246. return this._stencilFunc;
  10247. },
  10248. set: function (value) {
  10249. if (this._stencilFunc === value) {
  10250. return;
  10251. }
  10252. this._stencilFunc = value;
  10253. this._isStencilFuncDirty = true;
  10254. },
  10255. enumerable: true,
  10256. configurable: true
  10257. });
  10258. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10259. get: function () {
  10260. return this._stencilFuncRef;
  10261. },
  10262. set: function (value) {
  10263. if (this._stencilFuncRef === value) {
  10264. return;
  10265. }
  10266. this._stencilFuncRef = value;
  10267. this._isStencilFuncDirty = true;
  10268. },
  10269. enumerable: true,
  10270. configurable: true
  10271. });
  10272. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10273. get: function () {
  10274. return this._stencilFuncMask;
  10275. },
  10276. set: function (value) {
  10277. if (this._stencilFuncMask === value) {
  10278. return;
  10279. }
  10280. this._stencilFuncMask = value;
  10281. this._isStencilFuncDirty = true;
  10282. },
  10283. enumerable: true,
  10284. configurable: true
  10285. });
  10286. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10287. get: function () {
  10288. return this._stencilOpStencilFail;
  10289. },
  10290. set: function (value) {
  10291. if (this._stencilOpStencilFail === value) {
  10292. return;
  10293. }
  10294. this._stencilOpStencilFail = value;
  10295. this._isStencilOpDirty = true;
  10296. },
  10297. enumerable: true,
  10298. configurable: true
  10299. });
  10300. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10301. get: function () {
  10302. return this._stencilOpDepthFail;
  10303. },
  10304. set: function (value) {
  10305. if (this._stencilOpDepthFail === value) {
  10306. return;
  10307. }
  10308. this._stencilOpDepthFail = value;
  10309. this._isStencilOpDirty = true;
  10310. },
  10311. enumerable: true,
  10312. configurable: true
  10313. });
  10314. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10315. get: function () {
  10316. return this._stencilOpStencilDepthPass;
  10317. },
  10318. set: function (value) {
  10319. if (this._stencilOpStencilDepthPass === value) {
  10320. return;
  10321. }
  10322. this._stencilOpStencilDepthPass = value;
  10323. this._isStencilOpDirty = true;
  10324. },
  10325. enumerable: true,
  10326. configurable: true
  10327. });
  10328. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10329. get: function () {
  10330. return this._stencilMask;
  10331. },
  10332. set: function (value) {
  10333. if (this._stencilMask === value) {
  10334. return;
  10335. }
  10336. this._stencilMask = value;
  10337. this._isStencilMaskDirty = true;
  10338. },
  10339. enumerable: true,
  10340. configurable: true
  10341. });
  10342. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10343. get: function () {
  10344. return this._stencilTest;
  10345. },
  10346. set: function (value) {
  10347. if (this._stencilTest === value) {
  10348. return;
  10349. }
  10350. this._stencilTest = value;
  10351. this._isStencilTestDirty = true;
  10352. },
  10353. enumerable: true,
  10354. configurable: true
  10355. });
  10356. _StencilState.prototype.reset = function () {
  10357. this._stencilTest = false;
  10358. this._stencilMask = 0xFF;
  10359. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10360. this._stencilFuncRef = 1;
  10361. this._stencilFuncMask = 0xFF;
  10362. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10363. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10364. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10365. this._isStencilTestDirty = true;
  10366. this._isStencilMaskDirty = true;
  10367. this._isStencilFuncDirty = true;
  10368. this._isStencilOpDirty = true;
  10369. };
  10370. _StencilState.prototype.apply = function (gl) {
  10371. if (!this.isDirty) {
  10372. return;
  10373. }
  10374. // Stencil test
  10375. if (this._isStencilTestDirty) {
  10376. if (this.stencilTest) {
  10377. gl.enable(gl.STENCIL_TEST);
  10378. }
  10379. else {
  10380. gl.disable(gl.STENCIL_TEST);
  10381. }
  10382. this._isStencilTestDirty = false;
  10383. }
  10384. // Stencil mask
  10385. if (this._isStencilMaskDirty) {
  10386. gl.stencilMask(this.stencilMask);
  10387. this._isStencilMaskDirty = false;
  10388. }
  10389. // Stencil func
  10390. if (this._isStencilFuncDirty) {
  10391. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10392. this._isStencilFuncDirty = false;
  10393. }
  10394. // Stencil op
  10395. if (this._isStencilOpDirty) {
  10396. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10397. this._isStencilOpDirty = false;
  10398. }
  10399. };
  10400. return _StencilState;
  10401. }());
  10402. BABYLON._StencilState = _StencilState;
  10403. })(BABYLON || (BABYLON = {}));
  10404. //# sourceMappingURL=babylon.stencilState.js.map
  10405. "use strict";
  10406. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10407. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10408. s = arguments[i];
  10409. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10410. t[p] = s[p];
  10411. }
  10412. return t;
  10413. };
  10414. var BABYLON;
  10415. (function (BABYLON) {
  10416. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10417. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10418. };
  10419. var compileRawShader = function (gl, source, type) {
  10420. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10421. gl.shaderSource(shader, source);
  10422. gl.compileShader(shader);
  10423. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10424. var log = gl.getShaderInfoLog(shader);
  10425. if (log) {
  10426. throw new Error(log);
  10427. }
  10428. }
  10429. if (!shader) {
  10430. throw new Error("Something went wrong while compile the shader.");
  10431. }
  10432. return shader;
  10433. };
  10434. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10435. var magFilter = gl.NEAREST;
  10436. var minFilter = gl.NEAREST;
  10437. switch (samplingMode) {
  10438. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10439. magFilter = gl.LINEAR;
  10440. if (generateMipMaps) {
  10441. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10442. }
  10443. else {
  10444. minFilter = gl.LINEAR;
  10445. }
  10446. break;
  10447. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10448. magFilter = gl.LINEAR;
  10449. if (generateMipMaps) {
  10450. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10451. }
  10452. else {
  10453. minFilter = gl.LINEAR;
  10454. }
  10455. break;
  10456. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10457. magFilter = gl.NEAREST;
  10458. if (generateMipMaps) {
  10459. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10460. }
  10461. else {
  10462. minFilter = gl.NEAREST;
  10463. }
  10464. break;
  10465. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10466. magFilter = gl.NEAREST;
  10467. if (generateMipMaps) {
  10468. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10469. }
  10470. else {
  10471. minFilter = gl.NEAREST;
  10472. }
  10473. break;
  10474. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10475. magFilter = gl.NEAREST;
  10476. if (generateMipMaps) {
  10477. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10478. }
  10479. else {
  10480. minFilter = gl.LINEAR;
  10481. }
  10482. break;
  10483. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10484. magFilter = gl.NEAREST;
  10485. if (generateMipMaps) {
  10486. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10487. }
  10488. else {
  10489. minFilter = gl.LINEAR;
  10490. }
  10491. break;
  10492. case BABYLON.Texture.NEAREST_LINEAR:
  10493. magFilter = gl.NEAREST;
  10494. minFilter = gl.LINEAR;
  10495. break;
  10496. case BABYLON.Texture.NEAREST_NEAREST:
  10497. magFilter = gl.NEAREST;
  10498. minFilter = gl.NEAREST;
  10499. break;
  10500. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10501. magFilter = gl.LINEAR;
  10502. if (generateMipMaps) {
  10503. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10504. }
  10505. else {
  10506. minFilter = gl.NEAREST;
  10507. }
  10508. break;
  10509. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10510. magFilter = gl.LINEAR;
  10511. if (generateMipMaps) {
  10512. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10513. }
  10514. else {
  10515. minFilter = gl.NEAREST;
  10516. }
  10517. break;
  10518. case BABYLON.Texture.LINEAR_LINEAR:
  10519. magFilter = gl.LINEAR;
  10520. minFilter = gl.LINEAR;
  10521. break;
  10522. case BABYLON.Texture.LINEAR_NEAREST:
  10523. magFilter = gl.LINEAR;
  10524. minFilter = gl.NEAREST;
  10525. break;
  10526. }
  10527. return {
  10528. min: minFilter,
  10529. mag: magFilter
  10530. };
  10531. };
  10532. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10533. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10534. var img;
  10535. var onload = function () {
  10536. loadedImages[index] = img;
  10537. loadedImages._internalCount++;
  10538. if (scene) {
  10539. scene._removePendingData(img);
  10540. }
  10541. if (loadedImages._internalCount === 6) {
  10542. onfinish(loadedImages);
  10543. }
  10544. };
  10545. var onerror = function (message, exception) {
  10546. if (scene) {
  10547. scene._removePendingData(img);
  10548. }
  10549. if (onErrorCallBack) {
  10550. onErrorCallBack(message, exception);
  10551. }
  10552. };
  10553. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10554. if (scene) {
  10555. scene._addPendingData(img);
  10556. }
  10557. };
  10558. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10559. if (onError === void 0) { onError = null; }
  10560. var loadedImages = [];
  10561. loadedImages._internalCount = 0;
  10562. for (var index = 0; index < 6; index++) {
  10563. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10564. }
  10565. };
  10566. var BufferPointer = /** @class */ (function () {
  10567. function BufferPointer() {
  10568. }
  10569. return BufferPointer;
  10570. }());
  10571. var InstancingAttributeInfo = /** @class */ (function () {
  10572. function InstancingAttributeInfo() {
  10573. }
  10574. return InstancingAttributeInfo;
  10575. }());
  10576. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10577. /**
  10578. * Define options used to create a render target texture
  10579. */
  10580. var RenderTargetCreationOptions = /** @class */ (function () {
  10581. function RenderTargetCreationOptions() {
  10582. }
  10583. return RenderTargetCreationOptions;
  10584. }());
  10585. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10586. /**
  10587. * Define options used to create a depth texture
  10588. */
  10589. var DepthTextureCreationOptions = /** @class */ (function () {
  10590. function DepthTextureCreationOptions() {
  10591. }
  10592. return DepthTextureCreationOptions;
  10593. }());
  10594. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10595. /**
  10596. * Regroup several parameters relative to the browser in use
  10597. */
  10598. var EngineCapabilities = /** @class */ (function () {
  10599. function EngineCapabilities() {
  10600. }
  10601. return EngineCapabilities;
  10602. }());
  10603. BABYLON.EngineCapabilities = EngineCapabilities;
  10604. /**
  10605. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10606. */
  10607. var Engine = /** @class */ (function () {
  10608. /**
  10609. * @constructor
  10610. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10611. * @param antialias defines enable antialiasing (default: false)
  10612. * @param options defines further options to be sent to the getContext() function
  10613. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10614. */
  10615. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10616. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10617. var _this = this;
  10618. // Public members
  10619. this.forcePOTTextures = false;
  10620. this.isFullscreen = false;
  10621. this.isPointerLock = false;
  10622. this.cullBackFaces = true;
  10623. this.renderEvenInBackground = true;
  10624. this.preventCacheWipeBetweenFrames = false;
  10625. // To enable/disable IDB support and avoid XHR on .manifest
  10626. this.enableOfflineSupport = false;
  10627. this.scenes = new Array();
  10628. this.postProcesses = new Array();
  10629. // Observables
  10630. /**
  10631. * Observable event triggered each time the rendering canvas is resized
  10632. */
  10633. this.onResizeObservable = new BABYLON.Observable();
  10634. /**
  10635. * Observable event triggered each time the canvas loses focus
  10636. */
  10637. this.onCanvasBlurObservable = new BABYLON.Observable();
  10638. /**
  10639. * Observable event triggered each time the canvas gains focus
  10640. */
  10641. this.onCanvasFocusObservable = new BABYLON.Observable();
  10642. /**
  10643. * Observable event triggered each time the canvas receives pointerout event
  10644. */
  10645. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10646. /**
  10647. * Observable event triggered before each texture is initialized
  10648. */
  10649. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10650. //WebVR
  10651. this._vrDisplay = undefined;
  10652. this._vrSupported = false;
  10653. this._vrExclusivePointerMode = false;
  10654. // Uniform buffers list
  10655. this.disableUniformBuffers = false;
  10656. this._uniformBuffers = new Array();
  10657. // Observables
  10658. /**
  10659. * Observable raised when the engine begins a new frame
  10660. */
  10661. this.onBeginFrameObservable = new BABYLON.Observable();
  10662. /**
  10663. * Observable raised when the engine ends the current frame
  10664. */
  10665. this.onEndFrameObservable = new BABYLON.Observable();
  10666. /**
  10667. * Observable raised when the engine is about to compile a shader
  10668. */
  10669. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10670. /**
  10671. * Observable raised when the engine has jsut compiled a shader
  10672. */
  10673. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10674. this._windowIsBackground = false;
  10675. this._webGLVersion = 1.0;
  10676. this._badOS = false;
  10677. this._badDesktopOS = false;
  10678. /**
  10679. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10680. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10681. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10682. */
  10683. this.disableTextureBindingOptimization = false;
  10684. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10685. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10686. this.onVRRequestPresentStart = new BABYLON.Observable();
  10687. this._colorWrite = true;
  10688. this._drawCalls = new BABYLON.PerfCounter();
  10689. this._textureCollisions = new BABYLON.PerfCounter();
  10690. this._renderingQueueLaunched = false;
  10691. this._activeRenderLoops = new Array();
  10692. // Deterministic lockstepMaxSteps
  10693. this._deterministicLockstep = false;
  10694. this._lockstepMaxSteps = 4;
  10695. // Lost context
  10696. this.onContextLostObservable = new BABYLON.Observable();
  10697. this.onContextRestoredObservable = new BABYLON.Observable();
  10698. this._contextWasLost = false;
  10699. this._doNotHandleContextLost = false;
  10700. // FPS
  10701. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10702. this._fps = 60;
  10703. this._deltaTime = 0;
  10704. /**
  10705. * Turn this value on if you want to pause FPS computation when in background
  10706. */
  10707. this.disablePerformanceMonitorInBackground = false;
  10708. // States
  10709. this._depthCullingState = new BABYLON._DepthCullingState();
  10710. this._stencilState = new BABYLON._StencilState();
  10711. this._alphaState = new BABYLON._AlphaState();
  10712. this._alphaMode = Engine.ALPHA_DISABLE;
  10713. // Cache
  10714. this._internalTexturesCache = new Array();
  10715. this._activeChannel = 0;
  10716. this._currentTextureChannel = -1;
  10717. this._boundTexturesCache = {};
  10718. this._compiledEffects = {};
  10719. this._vertexAttribArraysEnabled = [];
  10720. this._uintIndicesCurrentlySet = false;
  10721. this._currentBoundBuffer = new Array();
  10722. this._currentBufferPointers = new Array();
  10723. this._currentInstanceLocations = new Array();
  10724. this._currentInstanceBuffers = new Array();
  10725. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10726. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10727. this._vaoRecordInProgress = false;
  10728. this._mustWipeVertexAttributes = false;
  10729. this._nextFreeTextureSlots = new Array();
  10730. this._maxSimultaneousTextures = 0;
  10731. this._activeRequests = new Array();
  10732. // Hardware supported Compressed Textures
  10733. this._texturesSupported = new Array();
  10734. this._onVRFullScreenTriggered = function () {
  10735. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10736. //get the old size before we change
  10737. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10738. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10739. //get the width and height, change the render size
  10740. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10741. _this.setHardwareScalingLevel(1);
  10742. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10743. }
  10744. else {
  10745. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10746. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10747. }
  10748. };
  10749. this._boundUniforms = {};
  10750. // Register promises
  10751. BABYLON.PromisePolyfill.Apply();
  10752. var canvas = null;
  10753. Engine.Instances.push(this);
  10754. if (!canvasOrContext) {
  10755. return;
  10756. }
  10757. options = options || {};
  10758. if (canvasOrContext.getContext) {
  10759. canvas = canvasOrContext;
  10760. this._renderingCanvas = canvas;
  10761. if (antialias != null) {
  10762. options.antialias = antialias;
  10763. }
  10764. if (options.deterministicLockstep === undefined) {
  10765. options.deterministicLockstep = false;
  10766. }
  10767. if (options.lockstepMaxSteps === undefined) {
  10768. options.lockstepMaxSteps = 4;
  10769. }
  10770. if (options.preserveDrawingBuffer === undefined) {
  10771. options.preserveDrawingBuffer = false;
  10772. }
  10773. if (options.audioEngine === undefined) {
  10774. options.audioEngine = true;
  10775. }
  10776. if (options.stencil === undefined) {
  10777. options.stencil = true;
  10778. }
  10779. this._deterministicLockstep = options.deterministicLockstep;
  10780. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10781. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10782. // Exceptions
  10783. if (navigator && navigator.userAgent) {
  10784. var ua = navigator.userAgent;
  10785. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10786. var exception = _a[_i];
  10787. var key = exception.key;
  10788. var targets = exception.targets;
  10789. if (ua.indexOf(key) > -1) {
  10790. if (exception.capture && exception.captureConstraint) {
  10791. var capture = exception.capture;
  10792. var constraint = exception.captureConstraint;
  10793. var regex = new RegExp(capture);
  10794. var matches = regex.exec(ua);
  10795. if (matches && matches.length > 0) {
  10796. var capturedValue = parseInt(matches[matches.length - 1]);
  10797. if (capturedValue >= constraint) {
  10798. continue;
  10799. }
  10800. }
  10801. }
  10802. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10803. var target = targets_1[_b];
  10804. switch (target) {
  10805. case "uniformBuffer":
  10806. this.disableUniformBuffers = true;
  10807. break;
  10808. case "textureBindingOptimization":
  10809. this.disableTextureBindingOptimization = true;
  10810. break;
  10811. }
  10812. }
  10813. }
  10814. }
  10815. }
  10816. // GL
  10817. if (!options.disableWebGL2Support) {
  10818. try {
  10819. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10820. if (this._gl) {
  10821. this._webGLVersion = 2.0;
  10822. }
  10823. }
  10824. catch (e) {
  10825. // Do nothing
  10826. }
  10827. }
  10828. if (!this._gl) {
  10829. if (!canvas) {
  10830. throw new Error("The provided canvas is null or undefined.");
  10831. }
  10832. try {
  10833. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10834. }
  10835. catch (e) {
  10836. throw new Error("WebGL not supported");
  10837. }
  10838. }
  10839. if (!this._gl) {
  10840. throw new Error("WebGL not supported");
  10841. }
  10842. this._onCanvasFocus = function () {
  10843. _this.onCanvasFocusObservable.notifyObservers(_this);
  10844. };
  10845. this._onCanvasBlur = function () {
  10846. _this.onCanvasBlurObservable.notifyObservers(_this);
  10847. };
  10848. canvas.addEventListener("focus", this._onCanvasFocus);
  10849. canvas.addEventListener("blur", this._onCanvasBlur);
  10850. this._onBlur = function () {
  10851. if (_this.disablePerformanceMonitorInBackground) {
  10852. _this._performanceMonitor.disable();
  10853. }
  10854. _this._windowIsBackground = true;
  10855. };
  10856. this._onFocus = function () {
  10857. if (_this.disablePerformanceMonitorInBackground) {
  10858. _this._performanceMonitor.enable();
  10859. }
  10860. _this._windowIsBackground = false;
  10861. };
  10862. this._onCanvasPointerOut = function (ev) {
  10863. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10864. };
  10865. window.addEventListener("blur", this._onBlur);
  10866. window.addEventListener("focus", this._onFocus);
  10867. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10868. // Context lost
  10869. if (!this._doNotHandleContextLost) {
  10870. this._onContextLost = function (evt) {
  10871. evt.preventDefault();
  10872. _this._contextWasLost = true;
  10873. BABYLON.Tools.Warn("WebGL context lost.");
  10874. _this.onContextLostObservable.notifyObservers(_this);
  10875. };
  10876. this._onContextRestored = function (evt) {
  10877. // Adding a timeout to avoid race condition at browser level
  10878. setTimeout(function () {
  10879. // Rebuild gl context
  10880. _this._initGLContext();
  10881. // Rebuild effects
  10882. _this._rebuildEffects();
  10883. // Rebuild textures
  10884. _this._rebuildInternalTextures();
  10885. // Rebuild buffers
  10886. _this._rebuildBuffers();
  10887. // Cache
  10888. _this.wipeCaches(true);
  10889. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10890. _this.onContextRestoredObservable.notifyObservers(_this);
  10891. _this._contextWasLost = false;
  10892. }, 0);
  10893. };
  10894. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10895. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10896. }
  10897. }
  10898. else {
  10899. this._gl = canvasOrContext;
  10900. this._renderingCanvas = this._gl.canvas;
  10901. if (this._gl.renderbufferStorageMultisample) {
  10902. this._webGLVersion = 2.0;
  10903. }
  10904. options.stencil = this._gl.getContextAttributes().stencil;
  10905. }
  10906. // Viewport
  10907. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10908. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10909. this.resize();
  10910. this._isStencilEnable = options.stencil ? true : false;
  10911. this._initGLContext();
  10912. if (canvas) {
  10913. // Fullscreen
  10914. this._onFullscreenChange = function () {
  10915. if (document.fullscreen !== undefined) {
  10916. _this.isFullscreen = document.fullscreen;
  10917. }
  10918. else if (document.mozFullScreen !== undefined) {
  10919. _this.isFullscreen = document.mozFullScreen;
  10920. }
  10921. else if (document.webkitIsFullScreen !== undefined) {
  10922. _this.isFullscreen = document.webkitIsFullScreen;
  10923. }
  10924. else if (document.msIsFullScreen !== undefined) {
  10925. _this.isFullscreen = document.msIsFullScreen;
  10926. }
  10927. // Pointer lock
  10928. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10929. canvas.requestPointerLock = canvas.requestPointerLock ||
  10930. canvas.msRequestPointerLock ||
  10931. canvas.mozRequestPointerLock ||
  10932. canvas.webkitRequestPointerLock;
  10933. if (canvas.requestPointerLock) {
  10934. canvas.requestPointerLock();
  10935. }
  10936. }
  10937. };
  10938. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10939. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10940. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10941. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10942. // Pointer lock
  10943. this._onPointerLockChange = function () {
  10944. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10945. document.webkitPointerLockElement === canvas ||
  10946. document.msPointerLockElement === canvas ||
  10947. document.pointerLockElement === canvas);
  10948. };
  10949. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10950. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10951. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10952. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10953. this._onVRDisplayPointerRestricted = function () {
  10954. if (canvas) {
  10955. canvas.requestPointerLock();
  10956. }
  10957. };
  10958. this._onVRDisplayPointerUnrestricted = function () {
  10959. document.exitPointerLock();
  10960. };
  10961. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10962. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10963. }
  10964. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10965. Engine.audioEngine = new BABYLON.AudioEngine();
  10966. }
  10967. // Prepare buffer pointers
  10968. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10969. this._currentBufferPointers[i] = new BufferPointer();
  10970. }
  10971. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10972. // Load WebVR Devices
  10973. if (options.autoEnableWebVR) {
  10974. this.initWebVR();
  10975. }
  10976. // Detect if we are running on a faulty buggy OS.
  10977. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10978. // Detect if we are running on a faulty buggy desktop OS.
  10979. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10980. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  10981. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10982. }
  10983. Object.defineProperty(Engine, "LastCreatedEngine", {
  10984. get: function () {
  10985. if (Engine.Instances.length === 0) {
  10986. return null;
  10987. }
  10988. return Engine.Instances[Engine.Instances.length - 1];
  10989. },
  10990. enumerable: true,
  10991. configurable: true
  10992. });
  10993. Object.defineProperty(Engine, "LastCreatedScene", {
  10994. get: function () {
  10995. var lastCreatedEngine = Engine.LastCreatedEngine;
  10996. if (!lastCreatedEngine) {
  10997. return null;
  10998. }
  10999. if (lastCreatedEngine.scenes.length === 0) {
  11000. return null;
  11001. }
  11002. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11003. },
  11004. enumerable: true,
  11005. configurable: true
  11006. });
  11007. /**
  11008. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11009. */
  11010. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11011. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11012. var engine = Engine.Instances[engineIndex];
  11013. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11014. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11015. }
  11016. }
  11017. };
  11018. Object.defineProperty(Engine, "NEVER", {
  11019. get: function () {
  11020. return Engine._NEVER;
  11021. },
  11022. enumerable: true,
  11023. configurable: true
  11024. });
  11025. Object.defineProperty(Engine, "ALWAYS", {
  11026. get: function () {
  11027. return Engine._ALWAYS;
  11028. },
  11029. enumerable: true,
  11030. configurable: true
  11031. });
  11032. Object.defineProperty(Engine, "LESS", {
  11033. get: function () {
  11034. return Engine._LESS;
  11035. },
  11036. enumerable: true,
  11037. configurable: true
  11038. });
  11039. Object.defineProperty(Engine, "EQUAL", {
  11040. get: function () {
  11041. return Engine._EQUAL;
  11042. },
  11043. enumerable: true,
  11044. configurable: true
  11045. });
  11046. Object.defineProperty(Engine, "LEQUAL", {
  11047. get: function () {
  11048. return Engine._LEQUAL;
  11049. },
  11050. enumerable: true,
  11051. configurable: true
  11052. });
  11053. Object.defineProperty(Engine, "GREATER", {
  11054. get: function () {
  11055. return Engine._GREATER;
  11056. },
  11057. enumerable: true,
  11058. configurable: true
  11059. });
  11060. Object.defineProperty(Engine, "GEQUAL", {
  11061. get: function () {
  11062. return Engine._GEQUAL;
  11063. },
  11064. enumerable: true,
  11065. configurable: true
  11066. });
  11067. Object.defineProperty(Engine, "NOTEQUAL", {
  11068. get: function () {
  11069. return Engine._NOTEQUAL;
  11070. },
  11071. enumerable: true,
  11072. configurable: true
  11073. });
  11074. Object.defineProperty(Engine, "KEEP", {
  11075. get: function () {
  11076. return Engine._KEEP;
  11077. },
  11078. enumerable: true,
  11079. configurable: true
  11080. });
  11081. Object.defineProperty(Engine, "REPLACE", {
  11082. get: function () {
  11083. return Engine._REPLACE;
  11084. },
  11085. enumerable: true,
  11086. configurable: true
  11087. });
  11088. Object.defineProperty(Engine, "INCR", {
  11089. get: function () {
  11090. return Engine._INCR;
  11091. },
  11092. enumerable: true,
  11093. configurable: true
  11094. });
  11095. Object.defineProperty(Engine, "DECR", {
  11096. get: function () {
  11097. return Engine._DECR;
  11098. },
  11099. enumerable: true,
  11100. configurable: true
  11101. });
  11102. Object.defineProperty(Engine, "INVERT", {
  11103. get: function () {
  11104. return Engine._INVERT;
  11105. },
  11106. enumerable: true,
  11107. configurable: true
  11108. });
  11109. Object.defineProperty(Engine, "INCR_WRAP", {
  11110. get: function () {
  11111. return Engine._INCR_WRAP;
  11112. },
  11113. enumerable: true,
  11114. configurable: true
  11115. });
  11116. Object.defineProperty(Engine, "DECR_WRAP", {
  11117. get: function () {
  11118. return Engine._DECR_WRAP;
  11119. },
  11120. enumerable: true,
  11121. configurable: true
  11122. });
  11123. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11124. get: function () {
  11125. return Engine._ALPHA_DISABLE;
  11126. },
  11127. enumerable: true,
  11128. configurable: true
  11129. });
  11130. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11131. get: function () {
  11132. return Engine._ALPHA_ONEONE;
  11133. },
  11134. enumerable: true,
  11135. configurable: true
  11136. });
  11137. Object.defineProperty(Engine, "ALPHA_ADD", {
  11138. get: function () {
  11139. return Engine._ALPHA_ADD;
  11140. },
  11141. enumerable: true,
  11142. configurable: true
  11143. });
  11144. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11145. get: function () {
  11146. return Engine._ALPHA_COMBINE;
  11147. },
  11148. enumerable: true,
  11149. configurable: true
  11150. });
  11151. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11152. get: function () {
  11153. return Engine._ALPHA_SUBTRACT;
  11154. },
  11155. enumerable: true,
  11156. configurable: true
  11157. });
  11158. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11159. get: function () {
  11160. return Engine._ALPHA_MULTIPLY;
  11161. },
  11162. enumerable: true,
  11163. configurable: true
  11164. });
  11165. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11166. get: function () {
  11167. return Engine._ALPHA_MAXIMIZED;
  11168. },
  11169. enumerable: true,
  11170. configurable: true
  11171. });
  11172. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11173. get: function () {
  11174. return Engine._ALPHA_PREMULTIPLIED;
  11175. },
  11176. enumerable: true,
  11177. configurable: true
  11178. });
  11179. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11180. get: function () {
  11181. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11182. },
  11183. enumerable: true,
  11184. configurable: true
  11185. });
  11186. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11187. get: function () {
  11188. return Engine._ALPHA_INTERPOLATE;
  11189. },
  11190. enumerable: true,
  11191. configurable: true
  11192. });
  11193. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11194. get: function () {
  11195. return Engine._ALPHA_SCREENMODE;
  11196. },
  11197. enumerable: true,
  11198. configurable: true
  11199. });
  11200. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11201. get: function () {
  11202. return Engine._DELAYLOADSTATE_NONE;
  11203. },
  11204. enumerable: true,
  11205. configurable: true
  11206. });
  11207. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11208. get: function () {
  11209. return Engine._DELAYLOADSTATE_LOADED;
  11210. },
  11211. enumerable: true,
  11212. configurable: true
  11213. });
  11214. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11215. get: function () {
  11216. return Engine._DELAYLOADSTATE_LOADING;
  11217. },
  11218. enumerable: true,
  11219. configurable: true
  11220. });
  11221. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11222. get: function () {
  11223. return Engine._DELAYLOADSTATE_NOTLOADED;
  11224. },
  11225. enumerable: true,
  11226. configurable: true
  11227. });
  11228. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11229. get: function () {
  11230. return Engine._TEXTUREFORMAT_ALPHA;
  11231. },
  11232. enumerable: true,
  11233. configurable: true
  11234. });
  11235. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11236. get: function () {
  11237. return Engine._TEXTUREFORMAT_LUMINANCE;
  11238. },
  11239. enumerable: true,
  11240. configurable: true
  11241. });
  11242. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11243. /**
  11244. * R32F
  11245. */
  11246. get: function () {
  11247. return Engine._TEXTUREFORMAT_R32F;
  11248. },
  11249. enumerable: true,
  11250. configurable: true
  11251. });
  11252. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11253. /**
  11254. * RG32F
  11255. */
  11256. get: function () {
  11257. return Engine._TEXTUREFORMAT_RG32F;
  11258. },
  11259. enumerable: true,
  11260. configurable: true
  11261. });
  11262. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11263. /**
  11264. * RGB32F
  11265. */
  11266. get: function () {
  11267. return Engine._TEXTUREFORMAT_RGB32F;
  11268. },
  11269. enumerable: true,
  11270. configurable: true
  11271. });
  11272. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11273. /**
  11274. * RGBA32F
  11275. */
  11276. get: function () {
  11277. return Engine._TEXTUREFORMAT_RGBA32F;
  11278. },
  11279. enumerable: true,
  11280. configurable: true
  11281. });
  11282. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11283. get: function () {
  11284. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11285. },
  11286. enumerable: true,
  11287. configurable: true
  11288. });
  11289. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11290. get: function () {
  11291. return Engine._TEXTUREFORMAT_RGB;
  11292. },
  11293. enumerable: true,
  11294. configurable: true
  11295. });
  11296. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11297. get: function () {
  11298. return Engine._TEXTUREFORMAT_RGBA;
  11299. },
  11300. enumerable: true,
  11301. configurable: true
  11302. });
  11303. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11304. get: function () {
  11305. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11306. },
  11307. enumerable: true,
  11308. configurable: true
  11309. });
  11310. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11311. get: function () {
  11312. return Engine._TEXTURETYPE_FLOAT;
  11313. },
  11314. enumerable: true,
  11315. configurable: true
  11316. });
  11317. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11318. get: function () {
  11319. return Engine._TEXTURETYPE_HALF_FLOAT;
  11320. },
  11321. enumerable: true,
  11322. configurable: true
  11323. });
  11324. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11325. get: function () {
  11326. return Engine._SCALEMODE_FLOOR;
  11327. },
  11328. enumerable: true,
  11329. configurable: true
  11330. });
  11331. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11332. get: function () {
  11333. return Engine._SCALEMODE_NEAREST;
  11334. },
  11335. enumerable: true,
  11336. configurable: true
  11337. });
  11338. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11339. get: function () {
  11340. return Engine._SCALEMODE_CEILING;
  11341. },
  11342. enumerable: true,
  11343. configurable: true
  11344. });
  11345. Object.defineProperty(Engine, "Version", {
  11346. get: function () {
  11347. return "3.2.0-beta.1";
  11348. },
  11349. enumerable: true,
  11350. configurable: true
  11351. });
  11352. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11353. get: function () {
  11354. return this._vrExclusivePointerMode;
  11355. },
  11356. enumerable: true,
  11357. configurable: true
  11358. });
  11359. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11360. get: function () {
  11361. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11362. },
  11363. enumerable: true,
  11364. configurable: true
  11365. });
  11366. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11367. get: function () {
  11368. return this._webGLVersion < 2 || this.forcePOTTextures;
  11369. },
  11370. enumerable: true,
  11371. configurable: true
  11372. });
  11373. Object.defineProperty(Engine.prototype, "badOS", {
  11374. get: function () {
  11375. return this._badOS;
  11376. },
  11377. enumerable: true,
  11378. configurable: true
  11379. });
  11380. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11381. get: function () {
  11382. return this._badDesktopOS;
  11383. },
  11384. enumerable: true,
  11385. configurable: true
  11386. });
  11387. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11388. get: function () {
  11389. return this._performanceMonitor;
  11390. },
  11391. enumerable: true,
  11392. configurable: true
  11393. });
  11394. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11395. get: function () {
  11396. return this._texturesSupported;
  11397. },
  11398. enumerable: true,
  11399. configurable: true
  11400. });
  11401. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11402. get: function () {
  11403. return this._textureFormatInUse;
  11404. },
  11405. enumerable: true,
  11406. configurable: true
  11407. });
  11408. Object.defineProperty(Engine.prototype, "currentViewport", {
  11409. get: function () {
  11410. return this._cachedViewport;
  11411. },
  11412. enumerable: true,
  11413. configurable: true
  11414. });
  11415. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11416. // Empty texture
  11417. get: function () {
  11418. if (!this._emptyTexture) {
  11419. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11420. }
  11421. return this._emptyTexture;
  11422. },
  11423. enumerable: true,
  11424. configurable: true
  11425. });
  11426. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11427. get: function () {
  11428. if (!this._emptyTexture3D) {
  11429. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11430. }
  11431. return this._emptyTexture3D;
  11432. },
  11433. enumerable: true,
  11434. configurable: true
  11435. });
  11436. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11437. get: function () {
  11438. if (!this._emptyCubeTexture) {
  11439. var faceData = new Uint8Array(4);
  11440. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11441. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11442. }
  11443. return this._emptyCubeTexture;
  11444. },
  11445. enumerable: true,
  11446. configurable: true
  11447. });
  11448. Engine.prototype._rebuildInternalTextures = function () {
  11449. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11450. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11451. var internalTexture = currentState_1[_i];
  11452. internalTexture._rebuild();
  11453. }
  11454. };
  11455. Engine.prototype._rebuildEffects = function () {
  11456. for (var key in this._compiledEffects) {
  11457. var effect = this._compiledEffects[key];
  11458. effect._prepareEffect();
  11459. }
  11460. BABYLON.Effect.ResetCache();
  11461. };
  11462. Engine.prototype._rebuildBuffers = function () {
  11463. // Index / Vertex
  11464. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11465. var scene = _a[_i];
  11466. scene.resetCachedMaterial();
  11467. scene._rebuildGeometries();
  11468. scene._rebuildTextures();
  11469. }
  11470. // Uniforms
  11471. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11472. var uniformBuffer = _c[_b];
  11473. uniformBuffer._rebuild();
  11474. }
  11475. };
  11476. Engine.prototype._initGLContext = function () {
  11477. // Caps
  11478. this._caps = new EngineCapabilities();
  11479. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11480. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11481. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11482. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11483. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11484. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11485. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11486. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11487. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11488. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11489. // Infos
  11490. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11491. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11492. if (rendererInfo != null) {
  11493. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11494. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11495. }
  11496. if (!this._glVendor) {
  11497. this._glVendor = "Unknown vendor";
  11498. }
  11499. if (!this._glRenderer) {
  11500. this._glRenderer = "Unknown renderer";
  11501. }
  11502. // Constants
  11503. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11504. if (this._gl.RGBA16F !== 0x881A) {
  11505. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11506. }
  11507. if (this._gl.RGBA32F !== 0x8814) {
  11508. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11509. }
  11510. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11511. this._gl.DEPTH24_STENCIL8 = 35056;
  11512. }
  11513. // Extensions
  11514. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11515. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11516. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11517. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11518. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11519. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11520. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11521. 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');
  11522. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11523. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11524. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11525. this._caps.highPrecisionShaderSupported = true;
  11526. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11527. if (this._caps.timerQuery) {
  11528. if (this._webGLVersion === 1) {
  11529. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11530. }
  11531. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11532. }
  11533. // Checks if some of the format renders first to allow the use of webgl inspector.
  11534. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11535. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11536. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11537. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11538. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11539. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11540. if (this._webGLVersion > 1) {
  11541. this._gl.HALF_FLOAT_OES = 0x140B;
  11542. }
  11543. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11544. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11545. // Draw buffers
  11546. if (this._webGLVersion > 1) {
  11547. this._caps.drawBuffersExtension = true;
  11548. }
  11549. else {
  11550. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11551. if (drawBuffersExtension !== null) {
  11552. this._caps.drawBuffersExtension = true;
  11553. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11554. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11555. for (var i = 0; i < 16; i++) {
  11556. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11557. }
  11558. }
  11559. else {
  11560. this._caps.drawBuffersExtension = false;
  11561. }
  11562. }
  11563. // Depth Texture
  11564. if (this._webGLVersion > 1) {
  11565. this._caps.depthTextureExtension = true;
  11566. }
  11567. else {
  11568. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11569. if (depthTextureExtension != null) {
  11570. this._caps.depthTextureExtension = true;
  11571. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11572. }
  11573. }
  11574. // Vertex array object
  11575. if (this._webGLVersion > 1) {
  11576. this._caps.vertexArrayObject = true;
  11577. }
  11578. else {
  11579. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11580. if (vertexArrayObjectExtension != null) {
  11581. this._caps.vertexArrayObject = true;
  11582. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11583. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11584. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11585. }
  11586. else {
  11587. this._caps.vertexArrayObject = false;
  11588. }
  11589. }
  11590. // Instances count
  11591. if (this._webGLVersion > 1) {
  11592. this._caps.instancedArrays = true;
  11593. }
  11594. else {
  11595. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11596. if (instanceExtension != null) {
  11597. this._caps.instancedArrays = true;
  11598. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11599. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11600. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11601. }
  11602. else {
  11603. this._caps.instancedArrays = false;
  11604. }
  11605. }
  11606. // Intelligently add supported compressed formats in order to check for.
  11607. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11608. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11609. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11610. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11611. if (this._caps.astc)
  11612. this.texturesSupported.push('-astc.ktx');
  11613. if (this._caps.s3tc)
  11614. this.texturesSupported.push('-dxt.ktx');
  11615. if (this._caps.pvrtc)
  11616. this.texturesSupported.push('-pvrtc.ktx');
  11617. if (this._caps.etc2)
  11618. this.texturesSupported.push('-etc2.ktx');
  11619. if (this._caps.etc1)
  11620. this.texturesSupported.push('-etc1.ktx');
  11621. if (this._gl.getShaderPrecisionFormat) {
  11622. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11623. if (highp) {
  11624. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11625. }
  11626. }
  11627. // Depth buffer
  11628. this.setDepthBuffer(true);
  11629. this.setDepthFunctionToLessOrEqual();
  11630. this.setDepthWrite(true);
  11631. // Texture maps
  11632. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11633. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11634. this._nextFreeTextureSlots.push(slot);
  11635. }
  11636. };
  11637. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11638. get: function () {
  11639. return this._webGLVersion;
  11640. },
  11641. enumerable: true,
  11642. configurable: true
  11643. });
  11644. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11645. /**
  11646. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11647. */
  11648. get: function () {
  11649. return this._isStencilEnable;
  11650. },
  11651. enumerable: true,
  11652. configurable: true
  11653. });
  11654. Engine.prototype._prepareWorkingCanvas = function () {
  11655. if (this._workingCanvas) {
  11656. return;
  11657. }
  11658. this._workingCanvas = document.createElement("canvas");
  11659. var context = this._workingCanvas.getContext("2d");
  11660. if (context) {
  11661. this._workingContext = context;
  11662. }
  11663. };
  11664. Engine.prototype.resetTextureCache = function () {
  11665. for (var key in this._boundTexturesCache) {
  11666. var boundTexture = this._boundTexturesCache[key];
  11667. if (boundTexture) {
  11668. this._removeDesignatedSlot(boundTexture);
  11669. }
  11670. this._boundTexturesCache[key] = null;
  11671. }
  11672. if (!this.disableTextureBindingOptimization) {
  11673. this._nextFreeTextureSlots = [];
  11674. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11675. this._nextFreeTextureSlots.push(slot);
  11676. }
  11677. }
  11678. this._currentTextureChannel = -1;
  11679. };
  11680. Engine.prototype.isDeterministicLockStep = function () {
  11681. return this._deterministicLockstep;
  11682. };
  11683. Engine.prototype.getLockstepMaxSteps = function () {
  11684. return this._lockstepMaxSteps;
  11685. };
  11686. Engine.prototype.getGlInfo = function () {
  11687. return {
  11688. vendor: this._glVendor,
  11689. renderer: this._glRenderer,
  11690. version: this._glVersion
  11691. };
  11692. };
  11693. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11694. if (useScreen === void 0) { useScreen = false; }
  11695. var viewport = camera.viewport;
  11696. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11697. };
  11698. Engine.prototype.getRenderWidth = function (useScreen) {
  11699. if (useScreen === void 0) { useScreen = false; }
  11700. if (!useScreen && this._currentRenderTarget) {
  11701. return this._currentRenderTarget.width;
  11702. }
  11703. return this._gl.drawingBufferWidth;
  11704. };
  11705. Engine.prototype.getRenderHeight = function (useScreen) {
  11706. if (useScreen === void 0) { useScreen = false; }
  11707. if (!useScreen && this._currentRenderTarget) {
  11708. return this._currentRenderTarget.height;
  11709. }
  11710. return this._gl.drawingBufferHeight;
  11711. };
  11712. Engine.prototype.getRenderingCanvas = function () {
  11713. return this._renderingCanvas;
  11714. };
  11715. Engine.prototype.getRenderingCanvasClientRect = function () {
  11716. if (!this._renderingCanvas) {
  11717. return null;
  11718. }
  11719. return this._renderingCanvas.getBoundingClientRect();
  11720. };
  11721. Engine.prototype.setHardwareScalingLevel = function (level) {
  11722. this._hardwareScalingLevel = level;
  11723. this.resize();
  11724. };
  11725. Engine.prototype.getHardwareScalingLevel = function () {
  11726. return this._hardwareScalingLevel;
  11727. };
  11728. Engine.prototype.getLoadedTexturesCache = function () {
  11729. return this._internalTexturesCache;
  11730. };
  11731. Engine.prototype.getCaps = function () {
  11732. return this._caps;
  11733. };
  11734. Object.defineProperty(Engine.prototype, "drawCalls", {
  11735. /** The number of draw calls submitted last frame */
  11736. get: function () {
  11737. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11738. return 0;
  11739. },
  11740. enumerable: true,
  11741. configurable: true
  11742. });
  11743. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11744. get: function () {
  11745. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11746. return null;
  11747. },
  11748. enumerable: true,
  11749. configurable: true
  11750. });
  11751. Engine.prototype.getDepthFunction = function () {
  11752. return this._depthCullingState.depthFunc;
  11753. };
  11754. Engine.prototype.setDepthFunction = function (depthFunc) {
  11755. this._depthCullingState.depthFunc = depthFunc;
  11756. };
  11757. Engine.prototype.setDepthFunctionToGreater = function () {
  11758. this._depthCullingState.depthFunc = this._gl.GREATER;
  11759. };
  11760. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11761. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11762. };
  11763. Engine.prototype.setDepthFunctionToLess = function () {
  11764. this._depthCullingState.depthFunc = this._gl.LESS;
  11765. };
  11766. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11767. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11768. };
  11769. Engine.prototype.getStencilBuffer = function () {
  11770. return this._stencilState.stencilTest;
  11771. };
  11772. Engine.prototype.setStencilBuffer = function (enable) {
  11773. this._stencilState.stencilTest = enable;
  11774. };
  11775. Engine.prototype.getStencilMask = function () {
  11776. return this._stencilState.stencilMask;
  11777. };
  11778. Engine.prototype.setStencilMask = function (mask) {
  11779. this._stencilState.stencilMask = mask;
  11780. };
  11781. Engine.prototype.getStencilFunction = function () {
  11782. return this._stencilState.stencilFunc;
  11783. };
  11784. Engine.prototype.getStencilFunctionReference = function () {
  11785. return this._stencilState.stencilFuncRef;
  11786. };
  11787. Engine.prototype.getStencilFunctionMask = function () {
  11788. return this._stencilState.stencilFuncMask;
  11789. };
  11790. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11791. this._stencilState.stencilFunc = stencilFunc;
  11792. };
  11793. Engine.prototype.setStencilFunctionReference = function (reference) {
  11794. this._stencilState.stencilFuncRef = reference;
  11795. };
  11796. Engine.prototype.setStencilFunctionMask = function (mask) {
  11797. this._stencilState.stencilFuncMask = mask;
  11798. };
  11799. Engine.prototype.getStencilOperationFail = function () {
  11800. return this._stencilState.stencilOpStencilFail;
  11801. };
  11802. Engine.prototype.getStencilOperationDepthFail = function () {
  11803. return this._stencilState.stencilOpDepthFail;
  11804. };
  11805. Engine.prototype.getStencilOperationPass = function () {
  11806. return this._stencilState.stencilOpStencilDepthPass;
  11807. };
  11808. Engine.prototype.setStencilOperationFail = function (operation) {
  11809. this._stencilState.stencilOpStencilFail = operation;
  11810. };
  11811. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11812. this._stencilState.stencilOpDepthFail = operation;
  11813. };
  11814. Engine.prototype.setStencilOperationPass = function (operation) {
  11815. this._stencilState.stencilOpStencilDepthPass = operation;
  11816. };
  11817. Engine.prototype.setDitheringState = function (value) {
  11818. if (value) {
  11819. this._gl.enable(this._gl.DITHER);
  11820. }
  11821. else {
  11822. this._gl.disable(this._gl.DITHER);
  11823. }
  11824. };
  11825. Engine.prototype.setRasterizerState = function (value) {
  11826. if (value) {
  11827. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11828. }
  11829. else {
  11830. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11831. }
  11832. };
  11833. /**
  11834. * stop executing a render loop function and remove it from the execution array
  11835. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11836. */
  11837. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11838. if (!renderFunction) {
  11839. this._activeRenderLoops = [];
  11840. return;
  11841. }
  11842. var index = this._activeRenderLoops.indexOf(renderFunction);
  11843. if (index >= 0) {
  11844. this._activeRenderLoops.splice(index, 1);
  11845. }
  11846. };
  11847. Engine.prototype._renderLoop = function () {
  11848. if (!this._contextWasLost) {
  11849. var shouldRender = true;
  11850. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11851. shouldRender = false;
  11852. }
  11853. if (shouldRender) {
  11854. // Start new frame
  11855. this.beginFrame();
  11856. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11857. var renderFunction = this._activeRenderLoops[index];
  11858. renderFunction();
  11859. }
  11860. // Present
  11861. this.endFrame();
  11862. }
  11863. }
  11864. if (this._activeRenderLoops.length > 0) {
  11865. // Register new frame
  11866. var requester = null;
  11867. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11868. requester = this._vrDisplay;
  11869. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11870. }
  11871. else {
  11872. this._renderingQueueLaunched = false;
  11873. }
  11874. };
  11875. /**
  11876. * Register and execute a render loop. The engine can have more than one render function.
  11877. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11878. * @example
  11879. * engine.runRenderLoop(function () {
  11880. * scene.render()
  11881. * })
  11882. */
  11883. Engine.prototype.runRenderLoop = function (renderFunction) {
  11884. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11885. return;
  11886. }
  11887. this._activeRenderLoops.push(renderFunction);
  11888. if (!this._renderingQueueLaunched) {
  11889. this._renderingQueueLaunched = true;
  11890. this._bindedRenderFunction = this._renderLoop.bind(this);
  11891. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11892. }
  11893. };
  11894. /**
  11895. * Toggle full screen mode.
  11896. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11897. * @param {any} options - an options object to be sent to the requestFullscreen function
  11898. */
  11899. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11900. if (this.isFullscreen) {
  11901. BABYLON.Tools.ExitFullscreen();
  11902. }
  11903. else {
  11904. this._pointerLockRequested = requestPointerLock;
  11905. if (this._renderingCanvas) {
  11906. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11907. }
  11908. }
  11909. };
  11910. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11911. if (stencil === void 0) { stencil = false; }
  11912. this.applyStates();
  11913. var mode = 0;
  11914. if (backBuffer && color) {
  11915. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11916. mode |= this._gl.COLOR_BUFFER_BIT;
  11917. }
  11918. if (depth) {
  11919. this._gl.clearDepth(1.0);
  11920. mode |= this._gl.DEPTH_BUFFER_BIT;
  11921. }
  11922. if (stencil) {
  11923. this._gl.clearStencil(0);
  11924. mode |= this._gl.STENCIL_BUFFER_BIT;
  11925. }
  11926. this._gl.clear(mode);
  11927. };
  11928. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11929. var gl = this._gl;
  11930. // Save state
  11931. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11932. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11933. // Change state
  11934. gl.enable(gl.SCISSOR_TEST);
  11935. gl.scissor(x, y, width, height);
  11936. // Clear
  11937. this.clear(clearColor, true, true, true);
  11938. // Restore state
  11939. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11940. if (curScissor === true) {
  11941. gl.enable(gl.SCISSOR_TEST);
  11942. }
  11943. else {
  11944. gl.disable(gl.SCISSOR_TEST);
  11945. }
  11946. };
  11947. /**
  11948. * Set the WebGL's viewport
  11949. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11950. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11951. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11952. */
  11953. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11954. var width = requiredWidth || this.getRenderWidth();
  11955. var height = requiredHeight || this.getRenderHeight();
  11956. var x = viewport.x || 0;
  11957. var y = viewport.y || 0;
  11958. this._cachedViewport = viewport;
  11959. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11960. };
  11961. /**
  11962. * Directly set the WebGL Viewport
  11963. * The x, y, width & height are directly passed to the WebGL call
  11964. * @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.
  11965. */
  11966. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11967. var currentViewport = this._cachedViewport;
  11968. this._cachedViewport = null;
  11969. this._gl.viewport(x, y, width, height);
  11970. return currentViewport;
  11971. };
  11972. Engine.prototype.beginFrame = function () {
  11973. this.onBeginFrameObservable.notifyObservers(this);
  11974. this._measureFps();
  11975. };
  11976. Engine.prototype.endFrame = function () {
  11977. //force a flush in case we are using a bad OS.
  11978. if (this._badOS) {
  11979. this.flushFramebuffer();
  11980. }
  11981. //submit frame to the vr device, if enabled
  11982. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11983. // TODO: We should only submit the frame if we read frameData successfully.
  11984. this._vrDisplay.submitFrame();
  11985. }
  11986. this.onEndFrameObservable.notifyObservers(this);
  11987. };
  11988. /**
  11989. * resize the view according to the canvas' size.
  11990. * @example
  11991. * window.addEventListener("resize", function () {
  11992. * engine.resize();
  11993. * });
  11994. */
  11995. Engine.prototype.resize = function () {
  11996. // We're not resizing the size of the canvas while in VR mode & presenting
  11997. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11998. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11999. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12000. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12001. }
  12002. };
  12003. /**
  12004. * force a specific size of the canvas
  12005. * @param {number} width - the new canvas' width
  12006. * @param {number} height - the new canvas' height
  12007. */
  12008. Engine.prototype.setSize = function (width, height) {
  12009. if (!this._renderingCanvas) {
  12010. return;
  12011. }
  12012. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12013. return;
  12014. }
  12015. this._renderingCanvas.width = width;
  12016. this._renderingCanvas.height = height;
  12017. for (var index = 0; index < this.scenes.length; index++) {
  12018. var scene = this.scenes[index];
  12019. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12020. var cam = scene.cameras[camIndex];
  12021. cam._currentRenderId = 0;
  12022. }
  12023. }
  12024. if (this.onResizeObservable.hasObservers) {
  12025. this.onResizeObservable.notifyObservers(this);
  12026. }
  12027. };
  12028. // WebVR functions
  12029. Engine.prototype.isVRDevicePresent = function () {
  12030. return !!this._vrDisplay;
  12031. };
  12032. Engine.prototype.getVRDevice = function () {
  12033. return this._vrDisplay;
  12034. };
  12035. /**
  12036. * Initializes a webVR display and starts listening to display change events.
  12037. * The onVRDisplayChangedObservable will be notified upon these changes.
  12038. * @returns The onVRDisplayChangedObservable.
  12039. */
  12040. Engine.prototype.initWebVR = function () {
  12041. this.initWebVRAsync();
  12042. return this.onVRDisplayChangedObservable;
  12043. };
  12044. /**
  12045. * Initializes a webVR display and starts listening to display change events.
  12046. * The onVRDisplayChangedObservable will be notified upon these changes.
  12047. * @returns A promise containing a VRDisplay and if vr is supported.
  12048. */
  12049. Engine.prototype.initWebVRAsync = function () {
  12050. var _this = this;
  12051. var notifyObservers = function () {
  12052. var eventArgs = {
  12053. vrDisplay: _this._vrDisplay,
  12054. vrSupported: _this._vrSupported
  12055. };
  12056. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12057. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12058. };
  12059. if (!this._onVrDisplayConnect) {
  12060. this._onVrDisplayConnect = function (event) {
  12061. _this._vrDisplay = event.display;
  12062. notifyObservers();
  12063. };
  12064. this._onVrDisplayDisconnect = function () {
  12065. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12066. _this._vrDisplay = undefined;
  12067. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12068. notifyObservers();
  12069. };
  12070. this._onVrDisplayPresentChange = function () {
  12071. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12072. };
  12073. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12074. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12075. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12076. }
  12077. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12078. this._webVRInitPromise.then(notifyObservers);
  12079. return this._webVRInitPromise;
  12080. };
  12081. Engine.prototype.enableVR = function () {
  12082. var _this = this;
  12083. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12084. var onResolved = function () {
  12085. _this.onVRRequestPresentComplete.notifyObservers(true);
  12086. _this._onVRFullScreenTriggered();
  12087. };
  12088. var onRejected = function () {
  12089. _this.onVRRequestPresentComplete.notifyObservers(false);
  12090. };
  12091. this.onVRRequestPresentStart.notifyObservers(this);
  12092. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12093. }
  12094. };
  12095. Engine.prototype.disableVR = function () {
  12096. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12097. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12098. }
  12099. };
  12100. Engine.prototype._getVRDisplaysAsync = function () {
  12101. var _this = this;
  12102. return new Promise(function (res, rej) {
  12103. if (navigator.getVRDisplays) {
  12104. navigator.getVRDisplays().then(function (devices) {
  12105. _this._vrSupported = true;
  12106. // note that devices may actually be an empty array. This is fine;
  12107. // we expect this._vrDisplay to be undefined in this case.
  12108. _this._vrDisplay = devices[0];
  12109. res({
  12110. vrDisplay: _this._vrDisplay,
  12111. vrSupported: _this._vrSupported
  12112. });
  12113. });
  12114. }
  12115. else {
  12116. _this._vrDisplay = undefined;
  12117. _this._vrSupported = false;
  12118. res({
  12119. vrDisplay: _this._vrDisplay,
  12120. vrSupported: _this._vrSupported
  12121. });
  12122. }
  12123. });
  12124. };
  12125. /**
  12126. * Binds the frame buffer to the specified texture.
  12127. * @param texture The texture to render to or null for the default canvas
  12128. * @param faceIndex The face of the texture to render to in case of cube texture
  12129. * @param requiredWidth The width of the target to render to
  12130. * @param requiredHeight The height of the target to render to
  12131. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12132. * @param depthStencilTexture The depth stencil texture to use to render
  12133. */
  12134. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12135. if (this._currentRenderTarget) {
  12136. this.unBindFramebuffer(this._currentRenderTarget);
  12137. }
  12138. this._currentRenderTarget = texture;
  12139. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12140. var gl = this._gl;
  12141. if (texture.isCube) {
  12142. if (faceIndex === undefined) {
  12143. faceIndex = 0;
  12144. }
  12145. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12146. if (depthStencilTexture) {
  12147. if (depthStencilTexture._generateStencilBuffer) {
  12148. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12149. }
  12150. else {
  12151. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12152. }
  12153. }
  12154. }
  12155. if (this._cachedViewport && !forceFullscreenViewport) {
  12156. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12157. }
  12158. else {
  12159. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12160. }
  12161. this.wipeCaches();
  12162. };
  12163. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12164. if (this._currentFramebuffer !== framebuffer) {
  12165. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12166. this._currentFramebuffer = framebuffer;
  12167. }
  12168. };
  12169. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12170. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12171. this._currentRenderTarget = null;
  12172. // If MSAA, we need to bitblt back to main texture
  12173. var gl = this._gl;
  12174. if (texture._MSAAFramebuffer) {
  12175. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12176. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12177. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12178. }
  12179. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12180. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12181. gl.generateMipmap(gl.TEXTURE_2D);
  12182. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12183. }
  12184. if (onBeforeUnbind) {
  12185. if (texture._MSAAFramebuffer) {
  12186. // Bind the correct framebuffer
  12187. this.bindUnboundFramebuffer(texture._framebuffer);
  12188. }
  12189. onBeforeUnbind();
  12190. }
  12191. this.bindUnboundFramebuffer(null);
  12192. };
  12193. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12194. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12195. this._currentRenderTarget = null;
  12196. // If MSAA, we need to bitblt back to main texture
  12197. var gl = this._gl;
  12198. if (textures[0]._MSAAFramebuffer) {
  12199. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12200. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12201. var attachments = textures[0]._attachments;
  12202. if (!attachments) {
  12203. attachments = new Array(textures.length);
  12204. textures[0]._attachments = attachments;
  12205. }
  12206. for (var i = 0; i < textures.length; i++) {
  12207. var texture = textures[i];
  12208. for (var j = 0; j < attachments.length; j++) {
  12209. attachments[j] = gl.NONE;
  12210. }
  12211. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12212. gl.readBuffer(attachments[i]);
  12213. gl.drawBuffers(attachments);
  12214. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12215. }
  12216. for (var i = 0; i < attachments.length; i++) {
  12217. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12218. }
  12219. gl.drawBuffers(attachments);
  12220. }
  12221. for (var i = 0; i < textures.length; i++) {
  12222. var texture = textures[i];
  12223. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12224. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12225. gl.generateMipmap(gl.TEXTURE_2D);
  12226. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12227. }
  12228. }
  12229. if (onBeforeUnbind) {
  12230. if (textures[0]._MSAAFramebuffer) {
  12231. // Bind the correct framebuffer
  12232. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12233. }
  12234. onBeforeUnbind();
  12235. }
  12236. this.bindUnboundFramebuffer(null);
  12237. };
  12238. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12239. if (texture.generateMipMaps) {
  12240. var gl = this._gl;
  12241. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12242. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12243. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12244. }
  12245. };
  12246. Engine.prototype.flushFramebuffer = function () {
  12247. this._gl.flush();
  12248. };
  12249. Engine.prototype.restoreDefaultFramebuffer = function () {
  12250. if (this._currentRenderTarget) {
  12251. this.unBindFramebuffer(this._currentRenderTarget);
  12252. }
  12253. else {
  12254. this.bindUnboundFramebuffer(null);
  12255. }
  12256. if (this._cachedViewport) {
  12257. this.setViewport(this._cachedViewport);
  12258. }
  12259. this.wipeCaches();
  12260. };
  12261. // UBOs
  12262. Engine.prototype.createUniformBuffer = function (elements) {
  12263. var ubo = this._gl.createBuffer();
  12264. if (!ubo) {
  12265. throw new Error("Unable to create uniform buffer");
  12266. }
  12267. this.bindUniformBuffer(ubo);
  12268. if (elements instanceof Float32Array) {
  12269. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12270. }
  12271. else {
  12272. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12273. }
  12274. this.bindUniformBuffer(null);
  12275. ubo.references = 1;
  12276. return ubo;
  12277. };
  12278. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12279. var ubo = this._gl.createBuffer();
  12280. if (!ubo) {
  12281. throw new Error("Unable to create dynamic uniform buffer");
  12282. }
  12283. this.bindUniformBuffer(ubo);
  12284. if (elements instanceof Float32Array) {
  12285. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12286. }
  12287. else {
  12288. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12289. }
  12290. this.bindUniformBuffer(null);
  12291. ubo.references = 1;
  12292. return ubo;
  12293. };
  12294. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12295. this.bindUniformBuffer(uniformBuffer);
  12296. if (offset === undefined) {
  12297. offset = 0;
  12298. }
  12299. if (count === undefined) {
  12300. if (elements instanceof Float32Array) {
  12301. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12302. }
  12303. else {
  12304. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12305. }
  12306. }
  12307. else {
  12308. if (elements instanceof Float32Array) {
  12309. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12310. }
  12311. else {
  12312. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12313. }
  12314. }
  12315. this.bindUniformBuffer(null);
  12316. };
  12317. // VBOs
  12318. Engine.prototype._resetVertexBufferBinding = function () {
  12319. this.bindArrayBuffer(null);
  12320. this._cachedVertexBuffers = null;
  12321. };
  12322. Engine.prototype.createVertexBuffer = function (vertices) {
  12323. var vbo = this._gl.createBuffer();
  12324. if (!vbo) {
  12325. throw new Error("Unable to create vertex buffer");
  12326. }
  12327. this.bindArrayBuffer(vbo);
  12328. if (vertices instanceof Float32Array) {
  12329. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  12330. }
  12331. else {
  12332. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  12333. }
  12334. this._resetVertexBufferBinding();
  12335. vbo.references = 1;
  12336. return vbo;
  12337. };
  12338. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12339. var vbo = this._gl.createBuffer();
  12340. if (!vbo) {
  12341. throw new Error("Unable to create dynamic vertex buffer");
  12342. }
  12343. this.bindArrayBuffer(vbo);
  12344. if (vertices instanceof Float32Array) {
  12345. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12346. }
  12347. else {
  12348. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12349. }
  12350. this._resetVertexBufferBinding();
  12351. vbo.references = 1;
  12352. return vbo;
  12353. };
  12354. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12355. if (offset === void 0) { offset = 0; }
  12356. // Force cache update
  12357. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12358. this.bindIndexBuffer(indexBuffer);
  12359. var arrayBuffer;
  12360. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12361. arrayBuffer = indices;
  12362. }
  12363. else {
  12364. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12365. }
  12366. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12367. this._resetIndexBufferBinding();
  12368. };
  12369. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12370. this.bindArrayBuffer(vertexBuffer);
  12371. if (offset === undefined) {
  12372. offset = 0;
  12373. }
  12374. if (count === undefined) {
  12375. if (vertices instanceof Float32Array) {
  12376. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12377. }
  12378. else {
  12379. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12380. }
  12381. }
  12382. else {
  12383. if (vertices instanceof Float32Array) {
  12384. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12385. }
  12386. else {
  12387. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12388. }
  12389. }
  12390. this._resetVertexBufferBinding();
  12391. };
  12392. Engine.prototype._resetIndexBufferBinding = function () {
  12393. this.bindIndexBuffer(null);
  12394. this._cachedIndexBuffer = null;
  12395. };
  12396. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12397. var vbo = this._gl.createBuffer();
  12398. if (!vbo) {
  12399. throw new Error("Unable to create index buffer");
  12400. }
  12401. this.bindIndexBuffer(vbo);
  12402. // Check for 32 bits indices
  12403. var arrayBuffer;
  12404. var need32Bits = false;
  12405. if (indices instanceof Uint16Array) {
  12406. arrayBuffer = indices;
  12407. }
  12408. else {
  12409. //check 32 bit support
  12410. if (this._caps.uintIndices) {
  12411. if (indices instanceof Uint32Array) {
  12412. arrayBuffer = indices;
  12413. need32Bits = true;
  12414. }
  12415. else {
  12416. //number[] or Int32Array, check if 32 bit is necessary
  12417. for (var index = 0; index < indices.length; index++) {
  12418. if (indices[index] > 65535) {
  12419. need32Bits = true;
  12420. break;
  12421. }
  12422. }
  12423. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12424. }
  12425. }
  12426. else {
  12427. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12428. arrayBuffer = new Uint16Array(indices);
  12429. }
  12430. }
  12431. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12432. this._resetIndexBufferBinding();
  12433. vbo.references = 1;
  12434. vbo.is32Bits = need32Bits;
  12435. return vbo;
  12436. };
  12437. Engine.prototype.bindArrayBuffer = function (buffer) {
  12438. if (!this._vaoRecordInProgress) {
  12439. this._unbindVertexArrayObject();
  12440. }
  12441. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12442. };
  12443. Engine.prototype.bindUniformBuffer = function (buffer) {
  12444. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12445. };
  12446. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12447. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12448. };
  12449. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12450. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12451. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12452. };
  12453. ;
  12454. Engine.prototype.bindIndexBuffer = function (buffer) {
  12455. if (!this._vaoRecordInProgress) {
  12456. this._unbindVertexArrayObject();
  12457. }
  12458. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12459. };
  12460. Engine.prototype.bindBuffer = function (buffer, target) {
  12461. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12462. this._gl.bindBuffer(target, buffer);
  12463. this._currentBoundBuffer[target] = buffer;
  12464. }
  12465. };
  12466. Engine.prototype.updateArrayBuffer = function (data) {
  12467. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12468. };
  12469. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12470. var pointer = this._currentBufferPointers[indx];
  12471. var changed = false;
  12472. if (!pointer.active) {
  12473. changed = true;
  12474. pointer.active = true;
  12475. pointer.index = indx;
  12476. pointer.size = size;
  12477. pointer.type = type;
  12478. pointer.normalized = normalized;
  12479. pointer.stride = stride;
  12480. pointer.offset = offset;
  12481. pointer.buffer = buffer;
  12482. }
  12483. else {
  12484. if (pointer.buffer !== buffer) {
  12485. pointer.buffer = buffer;
  12486. changed = true;
  12487. }
  12488. if (pointer.size !== size) {
  12489. pointer.size = size;
  12490. changed = true;
  12491. }
  12492. if (pointer.type !== type) {
  12493. pointer.type = type;
  12494. changed = true;
  12495. }
  12496. if (pointer.normalized !== normalized) {
  12497. pointer.normalized = normalized;
  12498. changed = true;
  12499. }
  12500. if (pointer.stride !== stride) {
  12501. pointer.stride = stride;
  12502. changed = true;
  12503. }
  12504. if (pointer.offset !== offset) {
  12505. pointer.offset = offset;
  12506. changed = true;
  12507. }
  12508. }
  12509. if (changed || this._vaoRecordInProgress) {
  12510. this.bindArrayBuffer(buffer);
  12511. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12512. }
  12513. };
  12514. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12515. if (indexBuffer == null) {
  12516. return;
  12517. }
  12518. if (this._cachedIndexBuffer !== indexBuffer) {
  12519. this._cachedIndexBuffer = indexBuffer;
  12520. this.bindIndexBuffer(indexBuffer);
  12521. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12522. }
  12523. };
  12524. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12525. var attributes = effect.getAttributesNames();
  12526. if (!this._vaoRecordInProgress) {
  12527. this._unbindVertexArrayObject();
  12528. }
  12529. this.unbindAllAttributes();
  12530. for (var index = 0; index < attributes.length; index++) {
  12531. var order = effect.getAttributeLocation(index);
  12532. if (order >= 0) {
  12533. var vertexBuffer = vertexBuffers[attributes[index]];
  12534. if (!vertexBuffer) {
  12535. continue;
  12536. }
  12537. this._gl.enableVertexAttribArray(order);
  12538. if (!this._vaoRecordInProgress) {
  12539. this._vertexAttribArraysEnabled[order] = true;
  12540. }
  12541. var buffer = vertexBuffer.getBuffer();
  12542. if (buffer) {
  12543. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12544. if (vertexBuffer.getIsInstanced()) {
  12545. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12546. if (!this._vaoRecordInProgress) {
  12547. this._currentInstanceLocations.push(order);
  12548. this._currentInstanceBuffers.push(buffer);
  12549. }
  12550. }
  12551. }
  12552. }
  12553. }
  12554. };
  12555. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12556. var vao = this._gl.createVertexArray();
  12557. this._vaoRecordInProgress = true;
  12558. this._gl.bindVertexArray(vao);
  12559. this._mustWipeVertexAttributes = true;
  12560. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12561. this.bindIndexBuffer(indexBuffer);
  12562. this._vaoRecordInProgress = false;
  12563. this._gl.bindVertexArray(null);
  12564. return vao;
  12565. };
  12566. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12567. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12568. this._cachedVertexArrayObject = vertexArrayObject;
  12569. this._gl.bindVertexArray(vertexArrayObject);
  12570. this._cachedVertexBuffers = null;
  12571. this._cachedIndexBuffer = null;
  12572. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12573. this._mustWipeVertexAttributes = true;
  12574. }
  12575. };
  12576. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12577. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12578. this._cachedVertexBuffers = vertexBuffer;
  12579. this._cachedEffectForVertexBuffers = effect;
  12580. var attributesCount = effect.getAttributesCount();
  12581. this._unbindVertexArrayObject();
  12582. this.unbindAllAttributes();
  12583. var offset = 0;
  12584. for (var index = 0; index < attributesCount; index++) {
  12585. if (index < vertexDeclaration.length) {
  12586. var order = effect.getAttributeLocation(index);
  12587. if (order >= 0) {
  12588. this._gl.enableVertexAttribArray(order);
  12589. this._vertexAttribArraysEnabled[order] = true;
  12590. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12591. }
  12592. offset += vertexDeclaration[index] * 4;
  12593. }
  12594. }
  12595. }
  12596. this._bindIndexBufferWithCache(indexBuffer);
  12597. };
  12598. Engine.prototype._unbindVertexArrayObject = function () {
  12599. if (!this._cachedVertexArrayObject) {
  12600. return;
  12601. }
  12602. this._cachedVertexArrayObject = null;
  12603. this._gl.bindVertexArray(null);
  12604. };
  12605. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12606. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12607. this._cachedVertexBuffers = vertexBuffers;
  12608. this._cachedEffectForVertexBuffers = effect;
  12609. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12610. }
  12611. this._bindIndexBufferWithCache(indexBuffer);
  12612. };
  12613. Engine.prototype.unbindInstanceAttributes = function () {
  12614. var boundBuffer;
  12615. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12616. var instancesBuffer = this._currentInstanceBuffers[i];
  12617. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12618. boundBuffer = instancesBuffer;
  12619. this.bindArrayBuffer(instancesBuffer);
  12620. }
  12621. var offsetLocation = this._currentInstanceLocations[i];
  12622. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12623. }
  12624. this._currentInstanceBuffers.length = 0;
  12625. this._currentInstanceLocations.length = 0;
  12626. };
  12627. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12628. this._gl.deleteVertexArray(vao);
  12629. };
  12630. Engine.prototype._releaseBuffer = function (buffer) {
  12631. buffer.references--;
  12632. if (buffer.references === 0) {
  12633. this._gl.deleteBuffer(buffer);
  12634. return true;
  12635. }
  12636. return false;
  12637. };
  12638. Engine.prototype.createInstancesBuffer = function (capacity) {
  12639. var buffer = this._gl.createBuffer();
  12640. if (!buffer) {
  12641. throw new Error("Unable to create instance buffer");
  12642. }
  12643. buffer.capacity = capacity;
  12644. this.bindArrayBuffer(buffer);
  12645. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12646. return buffer;
  12647. };
  12648. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12649. this._gl.deleteBuffer(buffer);
  12650. };
  12651. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12652. this.bindArrayBuffer(instancesBuffer);
  12653. if (data) {
  12654. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12655. }
  12656. if (offsetLocations[0].index !== undefined) {
  12657. var stride = 0;
  12658. for (var i = 0; i < offsetLocations.length; i++) {
  12659. var ai = offsetLocations[i];
  12660. stride += ai.attributeSize * 4;
  12661. }
  12662. for (var i = 0; i < offsetLocations.length; i++) {
  12663. var ai = offsetLocations[i];
  12664. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12665. this._gl.enableVertexAttribArray(ai.index);
  12666. this._vertexAttribArraysEnabled[ai.index] = true;
  12667. }
  12668. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12669. this._gl.vertexAttribDivisor(ai.index, 1);
  12670. this._currentInstanceLocations.push(ai.index);
  12671. this._currentInstanceBuffers.push(instancesBuffer);
  12672. }
  12673. }
  12674. else {
  12675. for (var index = 0; index < 4; index++) {
  12676. var offsetLocation = offsetLocations[index];
  12677. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12678. this._gl.enableVertexAttribArray(offsetLocation);
  12679. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12680. }
  12681. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12682. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12683. this._currentInstanceLocations.push(offsetLocation);
  12684. this._currentInstanceBuffers.push(instancesBuffer);
  12685. }
  12686. }
  12687. };
  12688. Engine.prototype.applyStates = function () {
  12689. this._depthCullingState.apply(this._gl);
  12690. this._stencilState.apply(this._gl);
  12691. this._alphaState.apply(this._gl);
  12692. };
  12693. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12694. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12695. };
  12696. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12697. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12698. };
  12699. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12700. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12701. };
  12702. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12703. // Apply states
  12704. this.applyStates();
  12705. this._drawCalls.addCount(1, false);
  12706. // Render
  12707. var drawMode = this._drawMode(fillMode);
  12708. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12709. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12710. if (instancesCount) {
  12711. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12712. }
  12713. else {
  12714. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12715. }
  12716. };
  12717. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12718. // Apply states
  12719. this.applyStates();
  12720. this._drawCalls.addCount(1, false);
  12721. var drawMode = this._drawMode(fillMode);
  12722. if (instancesCount) {
  12723. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12724. }
  12725. else {
  12726. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12727. }
  12728. };
  12729. Engine.prototype._drawMode = function (fillMode) {
  12730. switch (fillMode) {
  12731. // Triangle views
  12732. case BABYLON.Material.TriangleFillMode:
  12733. return this._gl.TRIANGLES;
  12734. case BABYLON.Material.PointFillMode:
  12735. return this._gl.POINTS;
  12736. case BABYLON.Material.WireFrameFillMode:
  12737. return this._gl.LINES;
  12738. // Draw modes
  12739. case BABYLON.Material.PointListDrawMode:
  12740. return this._gl.POINTS;
  12741. case BABYLON.Material.LineListDrawMode:
  12742. return this._gl.LINES;
  12743. case BABYLON.Material.LineLoopDrawMode:
  12744. return this._gl.LINE_LOOP;
  12745. case BABYLON.Material.LineStripDrawMode:
  12746. return this._gl.LINE_STRIP;
  12747. case BABYLON.Material.TriangleStripDrawMode:
  12748. return this._gl.TRIANGLE_STRIP;
  12749. case BABYLON.Material.TriangleFanDrawMode:
  12750. return this._gl.TRIANGLE_FAN;
  12751. default:
  12752. return this._gl.TRIANGLES;
  12753. }
  12754. };
  12755. // Shaders
  12756. Engine.prototype._releaseEffect = function (effect) {
  12757. if (this._compiledEffects[effect._key]) {
  12758. delete this._compiledEffects[effect._key];
  12759. this._deleteProgram(effect.getProgram());
  12760. }
  12761. };
  12762. Engine.prototype._deleteProgram = function (program) {
  12763. if (program) {
  12764. program.__SPECTOR_rebuildProgram = null;
  12765. if (program.transformFeedback) {
  12766. this.deleteTransformFeedback(program.transformFeedback);
  12767. program.transformFeedback = null;
  12768. }
  12769. this._gl.deleteProgram(program);
  12770. }
  12771. };
  12772. /**
  12773. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12774. * @param samplers An array of string used to represent textures
  12775. */
  12776. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12777. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12778. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12779. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12780. if (this._compiledEffects[name]) {
  12781. var compiledEffect = this._compiledEffects[name];
  12782. if (onCompiled && compiledEffect.isReady()) {
  12783. onCompiled(compiledEffect);
  12784. }
  12785. return compiledEffect;
  12786. }
  12787. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12788. effect._key = name;
  12789. this._compiledEffects[name] = effect;
  12790. return effect;
  12791. };
  12792. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12793. if (uniformsNames === void 0) { uniformsNames = []; }
  12794. if (samplers === void 0) { samplers = []; }
  12795. if (defines === void 0) { defines = ""; }
  12796. return this.createEffect({
  12797. vertex: "particles",
  12798. fragmentElement: fragmentName
  12799. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12800. };
  12801. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12802. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12803. context = context || this._gl;
  12804. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12805. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12806. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12807. };
  12808. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12809. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12810. context = context || this._gl;
  12811. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12812. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  12813. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12814. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12815. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12816. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12817. return program;
  12818. };
  12819. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12820. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12821. var shaderProgram = context.createProgram();
  12822. if (!shaderProgram) {
  12823. throw new Error("Unable to create program");
  12824. }
  12825. context.attachShader(shaderProgram, vertexShader);
  12826. context.attachShader(shaderProgram, fragmentShader);
  12827. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12828. var transformFeedback = this.createTransformFeedback();
  12829. this.bindTransformFeedback(transformFeedback);
  12830. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12831. shaderProgram.transformFeedback = transformFeedback;
  12832. }
  12833. context.linkProgram(shaderProgram);
  12834. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12835. this.bindTransformFeedback(null);
  12836. }
  12837. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12838. if (!linked) {
  12839. context.validateProgram(shaderProgram);
  12840. var error = context.getProgramInfoLog(shaderProgram);
  12841. if (error) {
  12842. throw new Error(error);
  12843. }
  12844. }
  12845. context.deleteShader(vertexShader);
  12846. context.deleteShader(fragmentShader);
  12847. return shaderProgram;
  12848. };
  12849. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12850. var results = new Array();
  12851. for (var index = 0; index < uniformsNames.length; index++) {
  12852. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12853. }
  12854. return results;
  12855. };
  12856. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12857. var results = [];
  12858. for (var index = 0; index < attributesNames.length; index++) {
  12859. try {
  12860. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12861. }
  12862. catch (e) {
  12863. results.push(-1);
  12864. }
  12865. }
  12866. return results;
  12867. };
  12868. Engine.prototype.enableEffect = function (effect) {
  12869. if (!effect) {
  12870. return;
  12871. }
  12872. // Use program
  12873. this.bindSamplers(effect);
  12874. this._currentEffect = effect;
  12875. if (effect.onBind) {
  12876. effect.onBind(effect);
  12877. }
  12878. effect.onBindObservable.notifyObservers(effect);
  12879. };
  12880. Engine.prototype.setIntArray = function (uniform, array) {
  12881. if (!uniform)
  12882. return;
  12883. this._gl.uniform1iv(uniform, array);
  12884. };
  12885. Engine.prototype.setIntArray2 = function (uniform, array) {
  12886. if (!uniform || array.length % 2 !== 0)
  12887. return;
  12888. this._gl.uniform2iv(uniform, array);
  12889. };
  12890. Engine.prototype.setIntArray3 = function (uniform, array) {
  12891. if (!uniform || array.length % 3 !== 0)
  12892. return;
  12893. this._gl.uniform3iv(uniform, array);
  12894. };
  12895. Engine.prototype.setIntArray4 = function (uniform, array) {
  12896. if (!uniform || array.length % 4 !== 0)
  12897. return;
  12898. this._gl.uniform4iv(uniform, array);
  12899. };
  12900. Engine.prototype.setFloatArray = function (uniform, array) {
  12901. if (!uniform)
  12902. return;
  12903. this._gl.uniform1fv(uniform, array);
  12904. };
  12905. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12906. if (!uniform || array.length % 2 !== 0)
  12907. return;
  12908. this._gl.uniform2fv(uniform, array);
  12909. };
  12910. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12911. if (!uniform || array.length % 3 !== 0)
  12912. return;
  12913. this._gl.uniform3fv(uniform, array);
  12914. };
  12915. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12916. if (!uniform || array.length % 4 !== 0)
  12917. return;
  12918. this._gl.uniform4fv(uniform, array);
  12919. };
  12920. Engine.prototype.setArray = function (uniform, array) {
  12921. if (!uniform)
  12922. return;
  12923. this._gl.uniform1fv(uniform, array);
  12924. };
  12925. Engine.prototype.setArray2 = function (uniform, array) {
  12926. if (!uniform || array.length % 2 !== 0)
  12927. return;
  12928. this._gl.uniform2fv(uniform, array);
  12929. };
  12930. Engine.prototype.setArray3 = function (uniform, array) {
  12931. if (!uniform || array.length % 3 !== 0)
  12932. return;
  12933. this._gl.uniform3fv(uniform, array);
  12934. };
  12935. Engine.prototype.setArray4 = function (uniform, array) {
  12936. if (!uniform || array.length % 4 !== 0)
  12937. return;
  12938. this._gl.uniform4fv(uniform, array);
  12939. };
  12940. Engine.prototype.setMatrices = function (uniform, matrices) {
  12941. if (!uniform)
  12942. return;
  12943. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12944. };
  12945. Engine.prototype.setMatrix = function (uniform, matrix) {
  12946. if (!uniform)
  12947. return;
  12948. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12949. };
  12950. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12951. if (!uniform)
  12952. return;
  12953. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12954. };
  12955. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12956. if (!uniform)
  12957. return;
  12958. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12959. };
  12960. Engine.prototype.setInt = function (uniform, value) {
  12961. if (!uniform)
  12962. return;
  12963. this._gl.uniform1i(uniform, value);
  12964. };
  12965. Engine.prototype.setFloat = function (uniform, value) {
  12966. if (!uniform)
  12967. return;
  12968. this._gl.uniform1f(uniform, value);
  12969. };
  12970. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12971. if (!uniform)
  12972. return;
  12973. this._gl.uniform2f(uniform, x, y);
  12974. };
  12975. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12976. if (!uniform)
  12977. return;
  12978. this._gl.uniform3f(uniform, x, y, z);
  12979. };
  12980. Engine.prototype.setBool = function (uniform, bool) {
  12981. if (!uniform)
  12982. return;
  12983. this._gl.uniform1i(uniform, bool);
  12984. };
  12985. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12986. if (!uniform)
  12987. return;
  12988. this._gl.uniform4f(uniform, x, y, z, w);
  12989. };
  12990. Engine.prototype.setColor3 = function (uniform, color3) {
  12991. if (!uniform)
  12992. return;
  12993. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12994. };
  12995. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12996. if (!uniform)
  12997. return;
  12998. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12999. };
  13000. /**
  13001. * Sets a Color4 on a uniform variable
  13002. * @param uniform defines the uniform location
  13003. * @param color4 defines the value to be set
  13004. */
  13005. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  13006. if (!uniform)
  13007. return;
  13008. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  13009. };
  13010. // States
  13011. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  13012. if (zOffset === void 0) { zOffset = 0; }
  13013. if (reverseSide === void 0) { reverseSide = false; }
  13014. // Culling
  13015. if (this._depthCullingState.cull !== culling || force) {
  13016. this._depthCullingState.cull = culling;
  13017. }
  13018. // Cull face
  13019. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  13020. if (this._depthCullingState.cullFace !== cullFace || force) {
  13021. this._depthCullingState.cullFace = cullFace;
  13022. }
  13023. // Z offset
  13024. this.setZOffset(zOffset);
  13025. // Front face
  13026. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  13027. if (this._depthCullingState.frontFace !== frontFace || force) {
  13028. this._depthCullingState.frontFace = frontFace;
  13029. }
  13030. };
  13031. Engine.prototype.setZOffset = function (value) {
  13032. this._depthCullingState.zOffset = value;
  13033. };
  13034. Engine.prototype.getZOffset = function () {
  13035. return this._depthCullingState.zOffset;
  13036. };
  13037. Engine.prototype.setDepthBuffer = function (enable) {
  13038. this._depthCullingState.depthTest = enable;
  13039. };
  13040. Engine.prototype.getDepthWrite = function () {
  13041. return this._depthCullingState.depthMask;
  13042. };
  13043. Engine.prototype.setDepthWrite = function (enable) {
  13044. this._depthCullingState.depthMask = enable;
  13045. };
  13046. Engine.prototype.setColorWrite = function (enable) {
  13047. this._gl.colorMask(enable, enable, enable, enable);
  13048. this._colorWrite = enable;
  13049. };
  13050. Engine.prototype.getColorWrite = function () {
  13051. return this._colorWrite;
  13052. };
  13053. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  13054. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  13055. };
  13056. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  13057. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  13058. if (this._alphaMode === mode) {
  13059. return;
  13060. }
  13061. switch (mode) {
  13062. case Engine.ALPHA_DISABLE:
  13063. this._alphaState.alphaBlend = false;
  13064. break;
  13065. case Engine.ALPHA_PREMULTIPLIED:
  13066. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  13067. this._alphaState.alphaBlend = true;
  13068. break;
  13069. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  13070. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  13071. this._alphaState.alphaBlend = true;
  13072. break;
  13073. case Engine.ALPHA_COMBINE:
  13074. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  13075. this._alphaState.alphaBlend = true;
  13076. break;
  13077. case Engine.ALPHA_ONEONE:
  13078. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  13079. this._alphaState.alphaBlend = true;
  13080. break;
  13081. case Engine.ALPHA_ADD:
  13082. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  13083. this._alphaState.alphaBlend = true;
  13084. break;
  13085. case Engine.ALPHA_SUBTRACT:
  13086. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  13087. this._alphaState.alphaBlend = true;
  13088. break;
  13089. case Engine.ALPHA_MULTIPLY:
  13090. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  13091. this._alphaState.alphaBlend = true;
  13092. break;
  13093. case Engine.ALPHA_MAXIMIZED:
  13094. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  13095. this._alphaState.alphaBlend = true;
  13096. break;
  13097. case Engine.ALPHA_INTERPOLATE:
  13098. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  13099. this._alphaState.alphaBlend = true;
  13100. break;
  13101. case Engine.ALPHA_SCREENMODE:
  13102. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  13103. this._alphaState.alphaBlend = true;
  13104. break;
  13105. }
  13106. if (!noDepthWriteChange) {
  13107. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  13108. }
  13109. this._alphaMode = mode;
  13110. };
  13111. Engine.prototype.getAlphaMode = function () {
  13112. return this._alphaMode;
  13113. };
  13114. // Textures
  13115. Engine.prototype.wipeCaches = function (bruteForce) {
  13116. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  13117. return;
  13118. }
  13119. this._currentEffect = null;
  13120. // 6/8/2017: deltakosh: Should not be required anymore.
  13121. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  13122. if (bruteForce) {
  13123. this.resetTextureCache();
  13124. this._currentProgram = null;
  13125. this._stencilState.reset();
  13126. this._depthCullingState.reset();
  13127. this.setDepthFunctionToLessOrEqual();
  13128. this._alphaState.reset();
  13129. }
  13130. this._resetVertexBufferBinding();
  13131. this._cachedIndexBuffer = null;
  13132. this._cachedEffectForVertexBuffers = null;
  13133. this._unbindVertexArrayObject();
  13134. this.bindIndexBuffer(null);
  13135. };
  13136. /**
  13137. * Set the compressed texture format to use, based on the formats you have, and the formats
  13138. * supported by the hardware / browser.
  13139. *
  13140. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  13141. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  13142. * to API arguments needed to compressed textures. This puts the burden on the container
  13143. * generator to house the arcane code for determining these for current & future formats.
  13144. *
  13145. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  13146. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  13147. *
  13148. * Note: The result of this call is not taken into account when a texture is base64.
  13149. *
  13150. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  13151. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  13152. *
  13153. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  13154. * @returns The extension selected.
  13155. */
  13156. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  13157. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  13158. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  13159. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  13160. return this._textureFormatInUse = this._texturesSupported[i];
  13161. }
  13162. }
  13163. }
  13164. // actively set format to nothing, to allow this to be called more than once
  13165. // and possibly fail the 2nd time
  13166. this._textureFormatInUse = null;
  13167. return null;
  13168. };
  13169. Engine.prototype._createTexture = function () {
  13170. var texture = this._gl.createTexture();
  13171. if (!texture) {
  13172. throw new Error("Unable to create texture");
  13173. }
  13174. return texture;
  13175. };
  13176. /**
  13177. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  13178. * @param {string} urlArg- This contains one of the following:
  13179. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  13180. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  13181. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  13182. *
  13183. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  13184. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  13185. * @param {Scene} scene- Needed for loading to the correct scene.
  13186. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  13187. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  13188. * @param {callback} onError- Optional callback to be called upon failure.
  13189. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  13190. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  13191. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  13192. *
  13193. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  13194. */
  13195. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  13196. var _this = this;
  13197. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13198. if (onLoad === void 0) { onLoad = null; }
  13199. if (onError === void 0) { onError = null; }
  13200. if (buffer === void 0) { buffer = null; }
  13201. if (fallBack === void 0) { fallBack = null; }
  13202. if (format === void 0) { format = null; }
  13203. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  13204. var fromData = url.substr(0, 5) === "data:";
  13205. var fromBlob = url.substr(0, 5) === "blob:";
  13206. var isBase64 = fromData && url.indexOf("base64") !== -1;
  13207. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  13208. // establish the file extension, if possible
  13209. var lastDot = url.lastIndexOf('.');
  13210. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  13211. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  13212. var isTGA = (extension.indexOf(".tga") === 0);
  13213. // determine if a ktx file should be substituted
  13214. var isKTX = false;
  13215. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  13216. url = url.substring(0, lastDot) + this._textureFormatInUse;
  13217. isKTX = true;
  13218. }
  13219. if (scene) {
  13220. scene._addPendingData(texture);
  13221. }
  13222. texture.url = url;
  13223. texture.generateMipMaps = !noMipmap;
  13224. texture.samplingMode = samplingMode;
  13225. texture.invertY = invertY;
  13226. if (!this._doNotHandleContextLost) {
  13227. // Keep a link to the buffer only if we plan to handle context lost
  13228. texture._buffer = buffer;
  13229. }
  13230. var onLoadObserver = null;
  13231. if (onLoad && !fallBack) {
  13232. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  13233. }
  13234. if (!fallBack)
  13235. this._internalTexturesCache.push(texture);
  13236. var onerror = function (message, exception) {
  13237. if (scene) {
  13238. scene._removePendingData(texture);
  13239. }
  13240. if (onLoadObserver) {
  13241. texture.onLoadedObservable.remove(onLoadObserver);
  13242. }
  13243. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  13244. if (isKTX) {
  13245. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13246. }
  13247. else if (BABYLON.Tools.UseFallbackTexture) {
  13248. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13249. }
  13250. if (onError) {
  13251. onError(message || "Unknown error", exception);
  13252. }
  13253. };
  13254. var callback = null;
  13255. // processing for non-image formats
  13256. if (isKTX || isTGA || isDDS) {
  13257. if (isKTX) {
  13258. callback = function (data) {
  13259. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  13260. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  13261. ktx.uploadLevels(_this._gl, !noMipmap);
  13262. return false;
  13263. }, samplingMode);
  13264. };
  13265. }
  13266. else if (isTGA) {
  13267. callback = function (arrayBuffer) {
  13268. var data = new Uint8Array(arrayBuffer);
  13269. var header = BABYLON.TGATools.GetTGAHeader(data);
  13270. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  13271. BABYLON.TGATools.UploadContent(_this._gl, data);
  13272. return false;
  13273. }, samplingMode);
  13274. };
  13275. }
  13276. else if (isDDS) {
  13277. callback = function (data) {
  13278. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13279. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  13280. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  13281. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  13282. return false;
  13283. }, samplingMode);
  13284. };
  13285. }
  13286. if (!buffer) {
  13287. this._loadFile(url, function (data) {
  13288. if (callback) {
  13289. callback(data);
  13290. }
  13291. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13292. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13293. });
  13294. }
  13295. else {
  13296. if (callback) {
  13297. callback(buffer);
  13298. }
  13299. }
  13300. // image format processing
  13301. }
  13302. else {
  13303. var onload = function (img) {
  13304. if (fromBlob && !_this._doNotHandleContextLost) {
  13305. // We need to store the image if we need to rebuild the texture
  13306. // in case of a webgl context lost
  13307. texture._buffer = img;
  13308. }
  13309. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13310. var gl = _this._gl;
  13311. var isPot = (img.width === potWidth && img.height === potHeight);
  13312. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13313. if (isPot) {
  13314. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13315. return false;
  13316. }
  13317. // Using shaders to rescale because canvas.drawImage is lossy
  13318. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13319. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13320. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13321. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13322. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13323. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13324. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13325. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13326. _this._releaseTexture(source);
  13327. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13328. continuationCallback();
  13329. });
  13330. return true;
  13331. }, samplingMode);
  13332. };
  13333. if (!fromData || isBase64)
  13334. if (buffer instanceof HTMLImageElement) {
  13335. onload(buffer);
  13336. }
  13337. else {
  13338. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13339. }
  13340. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13341. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13342. else
  13343. onload(buffer);
  13344. }
  13345. return texture;
  13346. };
  13347. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13348. var _this = this;
  13349. var rtt = this.createRenderTargetTexture({
  13350. width: destination.width,
  13351. height: destination.height,
  13352. }, {
  13353. generateMipMaps: false,
  13354. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13355. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13356. generateDepthBuffer: false,
  13357. generateStencilBuffer: false
  13358. });
  13359. if (!this._rescalePostProcess) {
  13360. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13361. }
  13362. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13363. _this._rescalePostProcess.onApply = function (effect) {
  13364. effect._bindTexture("textureSampler", source);
  13365. };
  13366. var hostingScene = scene;
  13367. if (!hostingScene) {
  13368. hostingScene = _this.scenes[_this.scenes.length - 1];
  13369. }
  13370. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13371. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13372. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13373. _this.unBindFramebuffer(rtt);
  13374. _this._releaseTexture(rtt);
  13375. if (onComplete) {
  13376. onComplete();
  13377. }
  13378. });
  13379. };
  13380. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13381. if (compression === void 0) { compression = null; }
  13382. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13383. if (!texture) {
  13384. return;
  13385. }
  13386. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13387. var internalFormat = this._getInternalFormat(format);
  13388. var textureType = this._getWebGLTextureType(type);
  13389. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13390. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13391. if (!this._doNotHandleContextLost) {
  13392. texture._bufferView = data;
  13393. texture.format = format;
  13394. texture.type = type;
  13395. texture.invertY = invertY;
  13396. texture._compression = compression;
  13397. }
  13398. if (texture.width % 4 !== 0) {
  13399. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13400. }
  13401. if (compression && data) {
  13402. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13403. }
  13404. else {
  13405. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13406. }
  13407. if (texture.generateMipMaps) {
  13408. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13409. }
  13410. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13411. // this.resetTextureCache();
  13412. texture.isReady = true;
  13413. };
  13414. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13415. if (compression === void 0) { compression = null; }
  13416. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13417. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13418. texture.baseWidth = width;
  13419. texture.baseHeight = height;
  13420. texture.width = width;
  13421. texture.height = height;
  13422. texture.format = format;
  13423. texture.generateMipMaps = generateMipMaps;
  13424. texture.samplingMode = samplingMode;
  13425. texture.invertY = invertY;
  13426. texture._compression = compression;
  13427. texture.type = type;
  13428. if (!this._doNotHandleContextLost) {
  13429. texture._bufferView = data;
  13430. }
  13431. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13432. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13433. // Filters
  13434. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13435. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13436. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13437. if (generateMipMaps) {
  13438. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13439. }
  13440. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13441. this._internalTexturesCache.push(texture);
  13442. return texture;
  13443. };
  13444. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13445. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13446. texture.baseWidth = width;
  13447. texture.baseHeight = height;
  13448. if (generateMipMaps) {
  13449. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13450. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13451. }
  13452. // this.resetTextureCache();
  13453. texture.width = width;
  13454. texture.height = height;
  13455. texture.isReady = false;
  13456. texture.generateMipMaps = generateMipMaps;
  13457. texture.samplingMode = samplingMode;
  13458. this.updateTextureSamplingMode(samplingMode, texture);
  13459. this._internalTexturesCache.push(texture);
  13460. return texture;
  13461. };
  13462. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13463. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13464. if (texture.isCube) {
  13465. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13466. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13467. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13468. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13469. }
  13470. else if (texture.is3D) {
  13471. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13472. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13473. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13474. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13475. }
  13476. else {
  13477. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13478. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13479. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13480. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13481. }
  13482. texture.samplingMode = samplingMode;
  13483. };
  13484. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13485. if (premulAlpha === void 0) { premulAlpha = false; }
  13486. if (!texture) {
  13487. return;
  13488. }
  13489. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13490. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13491. if (premulAlpha) {
  13492. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13493. }
  13494. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13495. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13496. if (texture.generateMipMaps) {
  13497. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13498. }
  13499. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13500. if (premulAlpha) {
  13501. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13502. }
  13503. texture.isReady = true;
  13504. };
  13505. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13506. if (!texture || texture._isDisabled) {
  13507. return;
  13508. }
  13509. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13510. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13511. try {
  13512. // Testing video texture support
  13513. if (this._videoTextureSupported === undefined) {
  13514. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13515. if (this._gl.getError() !== 0) {
  13516. this._videoTextureSupported = false;
  13517. }
  13518. else {
  13519. this._videoTextureSupported = true;
  13520. }
  13521. }
  13522. // Copy video through the current working canvas if video texture is not supported
  13523. if (!this._videoTextureSupported) {
  13524. if (!texture._workingCanvas) {
  13525. texture._workingCanvas = document.createElement("canvas");
  13526. var context = texture._workingCanvas.getContext("2d");
  13527. if (!context) {
  13528. throw new Error("Unable to get 2d context");
  13529. }
  13530. texture._workingContext = context;
  13531. texture._workingCanvas.width = texture.width;
  13532. texture._workingCanvas.height = texture.height;
  13533. }
  13534. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13535. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13536. }
  13537. else {
  13538. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13539. }
  13540. if (texture.generateMipMaps) {
  13541. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13542. }
  13543. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13544. // this.resetTextureCache();
  13545. texture.isReady = true;
  13546. }
  13547. catch (ex) {
  13548. // Something unexpected
  13549. // Let's disable the texture
  13550. texture._isDisabled = true;
  13551. }
  13552. };
  13553. /**
  13554. * Updates a depth texture Comparison Mode and Function.
  13555. * If the comparison Function is equal to 0, the mode will be set to none.
  13556. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13557. * @param texture The texture to set the comparison function for
  13558. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13559. */
  13560. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13561. if (this.webGLVersion === 1) {
  13562. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13563. return;
  13564. }
  13565. var gl = this._gl;
  13566. if (texture.isCube) {
  13567. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13568. if (comparisonFunction === 0) {
  13569. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13570. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13571. }
  13572. else {
  13573. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13574. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13575. }
  13576. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13577. }
  13578. else {
  13579. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13580. if (comparisonFunction === 0) {
  13581. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13582. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13583. }
  13584. else {
  13585. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13586. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13587. }
  13588. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13589. }
  13590. texture._comparisonFunction = comparisonFunction;
  13591. };
  13592. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13593. var width = size.width || size;
  13594. var height = size.height || size;
  13595. internalTexture.baseWidth = width;
  13596. internalTexture.baseHeight = height;
  13597. internalTexture.width = width;
  13598. internalTexture.height = height;
  13599. internalTexture.isReady = true;
  13600. internalTexture.samples = 1;
  13601. internalTexture.generateMipMaps = false;
  13602. internalTexture._generateDepthBuffer = true;
  13603. internalTexture._generateStencilBuffer = generateStencil;
  13604. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13605. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13606. internalTexture._comparisonFunction = comparisonFunction;
  13607. var gl = this._gl;
  13608. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13609. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13610. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13611. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13612. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13613. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13614. if (comparisonFunction === 0) {
  13615. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13616. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13617. }
  13618. else {
  13619. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13620. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13621. }
  13622. };
  13623. /**
  13624. * Creates a depth stencil texture.
  13625. * This is only available in WebGL 2 or with the depth texture extension available.
  13626. * @param size The size of face edge in the texture.
  13627. * @param options The options defining the texture.
  13628. * @returns The texture
  13629. */
  13630. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13631. if (options.isCube) {
  13632. var width = size.width || size;
  13633. return this._createDepthStencilCubeTexture(width, options);
  13634. }
  13635. else {
  13636. return this._createDepthStencilTexture(size, options);
  13637. }
  13638. };
  13639. /**
  13640. * Creates a depth stencil texture.
  13641. * This is only available in WebGL 2 or with the depth texture extension available.
  13642. * @param size The size of face edge in the texture.
  13643. * @param options The options defining the texture.
  13644. * @returns The texture
  13645. */
  13646. Engine.prototype._createDepthStencilTexture = function (size, options) {
  13647. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13648. if (!this._caps.depthTextureExtension) {
  13649. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13650. return internalTexture;
  13651. }
  13652. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13653. var gl = this._gl;
  13654. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13655. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13656. if (this.webGLVersion > 1) {
  13657. if (internalOptions.generateStencil) {
  13658. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13659. }
  13660. else {
  13661. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13662. }
  13663. }
  13664. else {
  13665. if (internalOptions.generateStencil) {
  13666. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13667. }
  13668. else {
  13669. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13670. }
  13671. }
  13672. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13673. return internalTexture;
  13674. };
  13675. /**
  13676. * Creates a depth stencil cube texture.
  13677. * This is only available in WebGL 2.
  13678. * @param size The size of face edge in the cube texture.
  13679. * @param options The options defining the cube texture.
  13680. * @returns The cube texture
  13681. */
  13682. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  13683. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13684. internalTexture.isCube = true;
  13685. if (this.webGLVersion === 1) {
  13686. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13687. return internalTexture;
  13688. }
  13689. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13690. var gl = this._gl;
  13691. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13692. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13693. // Create the depth/stencil buffer
  13694. for (var face = 0; face < 6; face++) {
  13695. if (internalOptions.generateStencil) {
  13696. 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);
  13697. }
  13698. else {
  13699. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13700. }
  13701. }
  13702. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13703. return internalTexture;
  13704. };
  13705. /**
  13706. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13707. * @param renderTarget The render target to set the frame buffer for
  13708. */
  13709. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13710. // Create the framebuffer
  13711. var internalTexture = renderTarget.getInternalTexture();
  13712. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13713. return;
  13714. }
  13715. var gl = this._gl;
  13716. var depthStencilTexture = renderTarget.depthStencilTexture;
  13717. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13718. if (depthStencilTexture.isCube) {
  13719. if (depthStencilTexture._generateStencilBuffer) {
  13720. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13721. }
  13722. else {
  13723. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13724. }
  13725. }
  13726. else {
  13727. if (depthStencilTexture._generateStencilBuffer) {
  13728. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13729. }
  13730. else {
  13731. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13732. }
  13733. }
  13734. this.bindUnboundFramebuffer(null);
  13735. };
  13736. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13737. var fullOptions = new RenderTargetCreationOptions();
  13738. if (options !== undefined && typeof options === "object") {
  13739. fullOptions.generateMipMaps = options.generateMipMaps;
  13740. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13741. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13742. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13743. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13744. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  13745. }
  13746. else {
  13747. fullOptions.generateMipMaps = options;
  13748. fullOptions.generateDepthBuffer = true;
  13749. fullOptions.generateStencilBuffer = false;
  13750. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13751. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13752. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  13753. }
  13754. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13755. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13756. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13757. }
  13758. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13759. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13760. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13761. }
  13762. var gl = this._gl;
  13763. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13764. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13765. var width = size.width || size;
  13766. var height = size.height || size;
  13767. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13768. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13769. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13770. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13771. }
  13772. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13773. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13774. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13775. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13776. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13777. // Create the framebuffer
  13778. var framebuffer = gl.createFramebuffer();
  13779. this.bindUnboundFramebuffer(framebuffer);
  13780. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13781. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13782. if (fullOptions.generateMipMaps) {
  13783. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13784. }
  13785. // Unbind
  13786. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13787. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13788. this.bindUnboundFramebuffer(null);
  13789. texture._framebuffer = framebuffer;
  13790. texture.baseWidth = width;
  13791. texture.baseHeight = height;
  13792. texture.width = width;
  13793. texture.height = height;
  13794. texture.isReady = true;
  13795. texture.samples = 1;
  13796. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13797. texture.samplingMode = fullOptions.samplingMode;
  13798. texture.type = fullOptions.type;
  13799. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13800. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13801. // this.resetTextureCache();
  13802. this._internalTexturesCache.push(texture);
  13803. return texture;
  13804. };
  13805. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13806. var generateMipMaps = false;
  13807. var generateDepthBuffer = true;
  13808. var generateStencilBuffer = false;
  13809. var generateDepthTexture = false;
  13810. var textureCount = 1;
  13811. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13812. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13813. var types = [], samplingModes = [];
  13814. if (options !== undefined) {
  13815. generateMipMaps = options.generateMipMaps;
  13816. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13817. generateStencilBuffer = options.generateStencilBuffer;
  13818. generateDepthTexture = options.generateDepthTexture;
  13819. textureCount = options.textureCount || 1;
  13820. if (options.types) {
  13821. types = options.types;
  13822. }
  13823. if (options.samplingModes) {
  13824. samplingModes = options.samplingModes;
  13825. }
  13826. }
  13827. var gl = this._gl;
  13828. // Create the framebuffer
  13829. var framebuffer = gl.createFramebuffer();
  13830. this.bindUnboundFramebuffer(framebuffer);
  13831. var width = size.width || size;
  13832. var height = size.height || size;
  13833. var textures = [];
  13834. var attachments = [];
  13835. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13836. for (var i = 0; i < textureCount; i++) {
  13837. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13838. var type = types[i] || defaultType;
  13839. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13840. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13841. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13842. }
  13843. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13844. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13845. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13846. }
  13847. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13848. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13849. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13850. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13851. }
  13852. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13853. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13854. textures.push(texture);
  13855. attachments.push(attachment);
  13856. gl.activeTexture(gl["TEXTURE" + i]);
  13857. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13858. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13859. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13860. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13861. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13862. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13863. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13864. if (generateMipMaps) {
  13865. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13866. }
  13867. // Unbind
  13868. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13869. texture._framebuffer = framebuffer;
  13870. texture._depthStencilBuffer = depthStencilBuffer;
  13871. texture.baseWidth = width;
  13872. texture.baseHeight = height;
  13873. texture.width = width;
  13874. texture.height = height;
  13875. texture.isReady = true;
  13876. texture.samples = 1;
  13877. texture.generateMipMaps = generateMipMaps;
  13878. texture.samplingMode = samplingMode;
  13879. texture.type = type;
  13880. texture._generateDepthBuffer = generateDepthBuffer;
  13881. texture._generateStencilBuffer = generateStencilBuffer;
  13882. texture._attachments = attachments;
  13883. this._internalTexturesCache.push(texture);
  13884. }
  13885. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13886. // Depth texture
  13887. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13888. gl.activeTexture(gl.TEXTURE0);
  13889. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13890. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13891. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13892. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13893. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13894. 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);
  13895. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13896. depthTexture._framebuffer = framebuffer;
  13897. depthTexture.baseWidth = width;
  13898. depthTexture.baseHeight = height;
  13899. depthTexture.width = width;
  13900. depthTexture.height = height;
  13901. depthTexture.isReady = true;
  13902. depthTexture.samples = 1;
  13903. depthTexture.generateMipMaps = generateMipMaps;
  13904. depthTexture.samplingMode = gl.NEAREST;
  13905. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13906. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13907. textures.push(depthTexture);
  13908. this._internalTexturesCache.push(depthTexture);
  13909. }
  13910. gl.drawBuffers(attachments);
  13911. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13912. this.bindUnboundFramebuffer(null);
  13913. this.resetTextureCache();
  13914. return textures;
  13915. };
  13916. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13917. if (samples === void 0) { samples = 1; }
  13918. var depthStencilBuffer = null;
  13919. var gl = this._gl;
  13920. // Create the depth/stencil buffer
  13921. if (generateStencilBuffer) {
  13922. depthStencilBuffer = gl.createRenderbuffer();
  13923. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13924. if (samples > 1) {
  13925. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13926. }
  13927. else {
  13928. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13929. }
  13930. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13931. }
  13932. else if (generateDepthBuffer) {
  13933. depthStencilBuffer = gl.createRenderbuffer();
  13934. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13935. if (samples > 1) {
  13936. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13937. }
  13938. else {
  13939. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13940. }
  13941. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13942. }
  13943. return depthStencilBuffer;
  13944. };
  13945. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13946. if (this.webGLVersion < 2 || !texture) {
  13947. return 1;
  13948. }
  13949. if (texture.samples === samples) {
  13950. return samples;
  13951. }
  13952. var gl = this._gl;
  13953. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13954. // Dispose previous render buffers
  13955. if (texture._depthStencilBuffer) {
  13956. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13957. texture._depthStencilBuffer = null;
  13958. }
  13959. if (texture._MSAAFramebuffer) {
  13960. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13961. texture._MSAAFramebuffer = null;
  13962. }
  13963. if (texture._MSAARenderBuffer) {
  13964. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13965. texture._MSAARenderBuffer = null;
  13966. }
  13967. if (samples > 1) {
  13968. var framebuffer = gl.createFramebuffer();
  13969. if (!framebuffer) {
  13970. throw new Error("Unable to create multi sampled framebuffer");
  13971. }
  13972. texture._MSAAFramebuffer = framebuffer;
  13973. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13974. var colorRenderbuffer = gl.createRenderbuffer();
  13975. if (!colorRenderbuffer) {
  13976. throw new Error("Unable to create multi sampled framebuffer");
  13977. }
  13978. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13979. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13980. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13981. texture._MSAARenderBuffer = colorRenderbuffer;
  13982. }
  13983. else {
  13984. this.bindUnboundFramebuffer(texture._framebuffer);
  13985. }
  13986. texture.samples = samples;
  13987. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13988. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13989. this.bindUnboundFramebuffer(null);
  13990. return samples;
  13991. };
  13992. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13993. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13994. return 1;
  13995. }
  13996. if (textures[0].samples === samples) {
  13997. return samples;
  13998. }
  13999. var gl = this._gl;
  14000. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  14001. // Dispose previous render buffers
  14002. if (textures[0]._depthStencilBuffer) {
  14003. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  14004. textures[0]._depthStencilBuffer = null;
  14005. }
  14006. if (textures[0]._MSAAFramebuffer) {
  14007. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  14008. textures[0]._MSAAFramebuffer = null;
  14009. }
  14010. for (var i = 0; i < textures.length; i++) {
  14011. if (textures[i]._MSAARenderBuffer) {
  14012. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  14013. textures[i]._MSAARenderBuffer = null;
  14014. }
  14015. }
  14016. if (samples > 1) {
  14017. var framebuffer = gl.createFramebuffer();
  14018. if (!framebuffer) {
  14019. throw new Error("Unable to create multi sampled framebuffer");
  14020. }
  14021. this.bindUnboundFramebuffer(framebuffer);
  14022. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  14023. var attachments = [];
  14024. for (var i = 0; i < textures.length; i++) {
  14025. var texture = textures[i];
  14026. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  14027. var colorRenderbuffer = gl.createRenderbuffer();
  14028. if (!colorRenderbuffer) {
  14029. throw new Error("Unable to create multi sampled framebuffer");
  14030. }
  14031. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  14032. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  14033. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  14034. texture._MSAAFramebuffer = framebuffer;
  14035. texture._MSAARenderBuffer = colorRenderbuffer;
  14036. texture.samples = samples;
  14037. texture._depthStencilBuffer = depthStencilBuffer;
  14038. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14039. attachments.push(attachment);
  14040. }
  14041. gl.drawBuffers(attachments);
  14042. }
  14043. else {
  14044. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  14045. }
  14046. this.bindUnboundFramebuffer(null);
  14047. return samples;
  14048. };
  14049. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  14050. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  14051. };
  14052. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  14053. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  14054. };
  14055. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  14056. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  14057. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  14058. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14059. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14060. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14061. }
  14062. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14063. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14064. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14065. }
  14066. var gl = this._gl;
  14067. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  14068. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14069. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  14070. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14071. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14072. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  14073. }
  14074. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14075. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14076. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14077. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14078. for (var face = 0; face < 6; face++) {
  14079. 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);
  14080. }
  14081. // Create the framebuffer
  14082. var framebuffer = gl.createFramebuffer();
  14083. this.bindUnboundFramebuffer(framebuffer);
  14084. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  14085. // MipMaps
  14086. if (fullOptions.generateMipMaps) {
  14087. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14088. }
  14089. // Unbind
  14090. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14091. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14092. this.bindUnboundFramebuffer(null);
  14093. texture._framebuffer = framebuffer;
  14094. texture.width = size;
  14095. texture.height = size;
  14096. texture.isReady = true;
  14097. texture.isCube = true;
  14098. texture.samples = 1;
  14099. texture.generateMipMaps = fullOptions.generateMipMaps;
  14100. texture.samplingMode = fullOptions.samplingMode;
  14101. texture.type = fullOptions.type;
  14102. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  14103. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  14104. this._internalTexturesCache.push(texture);
  14105. return texture;
  14106. };
  14107. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  14108. var _this = this;
  14109. if (onLoad === void 0) { onLoad = null; }
  14110. if (onError === void 0) { onError = null; }
  14111. if (forcedExtension === void 0) { forcedExtension = null; }
  14112. var callback = function (loadData) {
  14113. if (!loadData) {
  14114. if (onLoad) {
  14115. onLoad(null);
  14116. }
  14117. return;
  14118. }
  14119. var texture = loadData.texture;
  14120. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  14121. texture._lodGenerationScale = scale;
  14122. texture._lodGenerationOffset = offset;
  14123. if (_this._caps.textureLOD) {
  14124. // Do not add extra process if texture lod is supported.
  14125. if (onLoad) {
  14126. onLoad(texture);
  14127. }
  14128. return;
  14129. }
  14130. var mipSlices = 3;
  14131. var gl = _this._gl;
  14132. var width = loadData.width;
  14133. if (!width) {
  14134. return;
  14135. }
  14136. var textures = [];
  14137. for (var i = 0; i < mipSlices; i++) {
  14138. //compute LOD from even spacing in smoothness (matching shader calculation)
  14139. var smoothness = i / (mipSlices - 1);
  14140. var roughness = 1 - smoothness;
  14141. var minLODIndex = offset; // roughness = 0
  14142. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  14143. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  14144. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  14145. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14146. glTextureFromLod.isCube = true;
  14147. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  14148. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14149. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14150. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14151. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14152. if (loadData.isDDS) {
  14153. var info = loadData.info;
  14154. var data = loadData.data;
  14155. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14156. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  14157. }
  14158. else {
  14159. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  14160. }
  14161. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14162. // Wrap in a base texture for easy binding.
  14163. var lodTexture = new BABYLON.BaseTexture(scene);
  14164. lodTexture.isCube = true;
  14165. lodTexture._texture = glTextureFromLod;
  14166. glTextureFromLod.isReady = true;
  14167. textures.push(lodTexture);
  14168. }
  14169. texture._lodTextureHigh = textures[2];
  14170. texture._lodTextureMid = textures[1];
  14171. texture._lodTextureLow = textures[0];
  14172. if (onLoad) {
  14173. onLoad(texture);
  14174. }
  14175. };
  14176. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  14177. };
  14178. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  14179. var _this = this;
  14180. if (onLoad === void 0) { onLoad = null; }
  14181. if (onError === void 0) { onError = null; }
  14182. if (forcedExtension === void 0) { forcedExtension = null; }
  14183. var gl = this._gl;
  14184. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  14185. texture.isCube = true;
  14186. texture.url = rootUrl;
  14187. texture.generateMipMaps = !noMipmap;
  14188. if (!this._doNotHandleContextLost) {
  14189. texture._extension = forcedExtension;
  14190. texture._files = files;
  14191. }
  14192. var isKTX = false;
  14193. var isDDS = false;
  14194. var lastDot = rootUrl.lastIndexOf('.');
  14195. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  14196. if (this._textureFormatInUse) {
  14197. extension = this._textureFormatInUse;
  14198. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  14199. isKTX = true;
  14200. }
  14201. else {
  14202. isDDS = (extension === ".dds");
  14203. }
  14204. var onerror = function (request, exception) {
  14205. if (onError && request) {
  14206. onError(request.status + " " + request.statusText, exception);
  14207. }
  14208. };
  14209. if (isKTX) {
  14210. this._loadFile(rootUrl, function (data) {
  14211. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  14212. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  14213. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14214. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  14215. ktx.uploadLevels(_this._gl, !noMipmap);
  14216. _this.setCubeMapTextureParams(gl, loadMipmap);
  14217. texture.width = ktx.pixelWidth;
  14218. texture.height = ktx.pixelHeight;
  14219. texture.isReady = true;
  14220. }, undefined, undefined, true, onerror);
  14221. }
  14222. else if (isDDS) {
  14223. if (files && files.length === 6) {
  14224. this._cascadeLoadFiles(scene, function (imgs) {
  14225. var info;
  14226. var loadMipmap = false;
  14227. var width = 0;
  14228. for (var index = 0; index < imgs.length; index++) {
  14229. var data = imgs[index];
  14230. info = BABYLON.DDSTools.GetDDSInfo(data);
  14231. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14232. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14233. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14234. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  14235. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14236. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14237. }
  14238. texture.width = info.width;
  14239. texture.height = info.height;
  14240. texture.type = info.textureType;
  14241. width = info.width;
  14242. }
  14243. _this.setCubeMapTextureParams(gl, loadMipmap);
  14244. texture.isReady = true;
  14245. if (onLoad) {
  14246. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  14247. }
  14248. }, files, onError);
  14249. }
  14250. else {
  14251. this._loadFile(rootUrl, function (data) {
  14252. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14253. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14254. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14255. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14256. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  14257. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14258. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14259. }
  14260. _this.setCubeMapTextureParams(gl, loadMipmap);
  14261. texture.width = info.width;
  14262. texture.height = info.height;
  14263. texture.isReady = true;
  14264. texture.type = info.textureType;
  14265. if (onLoad) {
  14266. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  14267. }
  14268. }, undefined, undefined, true, onerror);
  14269. }
  14270. }
  14271. else {
  14272. if (!files) {
  14273. throw new Error("Cannot load cubemap because files were not defined");
  14274. }
  14275. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  14276. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  14277. var height = width;
  14278. _this._prepareWorkingCanvas();
  14279. if (!_this._workingCanvas || !_this._workingContext) {
  14280. return;
  14281. }
  14282. _this._workingCanvas.width = width;
  14283. _this._workingCanvas.height = height;
  14284. var faces = [
  14285. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  14286. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  14287. ];
  14288. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14289. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14290. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  14291. for (var index = 0; index < faces.length; index++) {
  14292. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  14293. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14294. }
  14295. if (!noMipmap) {
  14296. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14297. }
  14298. _this.setCubeMapTextureParams(gl, !noMipmap);
  14299. texture.width = width;
  14300. texture.height = height;
  14301. texture.isReady = true;
  14302. if (format) {
  14303. texture.format = format;
  14304. }
  14305. texture.onLoadedObservable.notifyObservers(texture);
  14306. texture.onLoadedObservable.clear();
  14307. if (onLoad) {
  14308. onLoad();
  14309. }
  14310. }, files, onError);
  14311. }
  14312. this._internalTexturesCache.push(texture);
  14313. return texture;
  14314. };
  14315. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14316. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14317. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14318. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14319. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14320. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14321. // this.resetTextureCache();
  14322. };
  14323. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14324. if (compression === void 0) { compression = null; }
  14325. if (level === void 0) { level = 0; }
  14326. texture._bufferViewArray = data;
  14327. texture.format = format;
  14328. texture.type = type;
  14329. texture.invertY = invertY;
  14330. texture._compression = compression;
  14331. var gl = this._gl;
  14332. var textureType = this._getWebGLTextureType(type);
  14333. var internalFormat = this._getInternalFormat(format);
  14334. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14335. var needConversion = false;
  14336. if (internalFormat === gl.RGB) {
  14337. internalFormat = gl.RGBA;
  14338. needConversion = true;
  14339. }
  14340. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14341. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14342. if (texture.width % 4 !== 0) {
  14343. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14344. }
  14345. // Data are known to be in +X +Y +Z -X -Y -Z
  14346. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14347. var faceData = data[faceIndex];
  14348. if (compression) {
  14349. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14350. }
  14351. else {
  14352. if (needConversion) {
  14353. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14354. }
  14355. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14356. }
  14357. }
  14358. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14359. if (isPot && texture.generateMipMaps && level === 0) {
  14360. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14361. }
  14362. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14363. // this.resetTextureCache();
  14364. texture.isReady = true;
  14365. };
  14366. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14367. if (compression === void 0) { compression = null; }
  14368. var gl = this._gl;
  14369. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14370. texture.isCube = true;
  14371. texture.generateMipMaps = generateMipMaps;
  14372. texture.format = format;
  14373. texture.type = type;
  14374. if (!this._doNotHandleContextLost) {
  14375. texture._bufferViewArray = data;
  14376. }
  14377. var textureType = this._getWebGLTextureType(type);
  14378. var internalFormat = this._getInternalFormat(format);
  14379. if (internalFormat === gl.RGB) {
  14380. internalFormat = gl.RGBA;
  14381. }
  14382. var width = size;
  14383. var height = width;
  14384. texture.width = width;
  14385. texture.height = height;
  14386. // Double check on POT to generate Mips.
  14387. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14388. if (!isPot) {
  14389. generateMipMaps = false;
  14390. }
  14391. // Upload data if needed. The texture won't be ready until then.
  14392. if (data) {
  14393. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14394. }
  14395. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14396. // Filters
  14397. if (data && generateMipMaps) {
  14398. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14399. }
  14400. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14401. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14402. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14403. }
  14404. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14405. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14406. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14407. }
  14408. else {
  14409. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14410. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14411. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14412. }
  14413. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14414. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14415. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14416. return texture;
  14417. };
  14418. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14419. var _this = this;
  14420. if (onLoad === void 0) { onLoad = null; }
  14421. if (onError === void 0) { onError = null; }
  14422. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14423. if (invertY === void 0) { invertY = false; }
  14424. var gl = this._gl;
  14425. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14426. scene._addPendingData(texture);
  14427. texture.url = url;
  14428. this._internalTexturesCache.push(texture);
  14429. var onerror = function (request, exception) {
  14430. scene._removePendingData(texture);
  14431. if (onError && request) {
  14432. onError(request.status + " " + request.statusText, exception);
  14433. }
  14434. };
  14435. var internalCallback = function (data) {
  14436. var width = texture.width;
  14437. var faceDataArrays = callback(data);
  14438. if (!faceDataArrays) {
  14439. return;
  14440. }
  14441. if (mipmmapGenerator) {
  14442. var textureType = _this._getWebGLTextureType(type);
  14443. var internalFormat = _this._getInternalFormat(format);
  14444. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14445. var needConversion = false;
  14446. if (internalFormat === gl.RGB) {
  14447. internalFormat = gl.RGBA;
  14448. needConversion = true;
  14449. }
  14450. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14451. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14452. var mipData = mipmmapGenerator(faceDataArrays);
  14453. for (var level = 0; level < mipData.length; level++) {
  14454. var mipSize = width >> level;
  14455. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14456. var mipFaceData = mipData[level][faceIndex];
  14457. if (needConversion) {
  14458. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14459. }
  14460. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14461. }
  14462. }
  14463. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14464. }
  14465. else {
  14466. texture.generateMipMaps = !noMipmap;
  14467. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14468. }
  14469. texture.isReady = true;
  14470. // this.resetTextureCache();
  14471. scene._removePendingData(texture);
  14472. if (onLoad) {
  14473. onLoad();
  14474. }
  14475. };
  14476. this._loadFile(url, function (data) {
  14477. internalCallback(data);
  14478. }, undefined, scene.database, true, onerror);
  14479. return texture;
  14480. };
  14481. ;
  14482. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14483. if (compression === void 0) { compression = null; }
  14484. var internalFormat = this._getInternalFormat(format);
  14485. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14486. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14487. if (!this._doNotHandleContextLost) {
  14488. texture._bufferView = data;
  14489. texture.format = format;
  14490. texture.invertY = invertY;
  14491. texture._compression = compression;
  14492. }
  14493. if (texture.width % 4 !== 0) {
  14494. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14495. }
  14496. if (compression && data) {
  14497. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14498. }
  14499. else {
  14500. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14501. }
  14502. if (texture.generateMipMaps) {
  14503. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14504. }
  14505. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14506. // this.resetTextureCache();
  14507. texture.isReady = true;
  14508. };
  14509. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14510. if (compression === void 0) { compression = null; }
  14511. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14512. texture.baseWidth = width;
  14513. texture.baseHeight = height;
  14514. texture.baseDepth = depth;
  14515. texture.width = width;
  14516. texture.height = height;
  14517. texture.depth = depth;
  14518. texture.format = format;
  14519. texture.generateMipMaps = generateMipMaps;
  14520. texture.samplingMode = samplingMode;
  14521. texture.is3D = true;
  14522. if (!this._doNotHandleContextLost) {
  14523. texture._bufferView = data;
  14524. }
  14525. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14526. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14527. // Filters
  14528. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14529. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14530. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14531. if (generateMipMaps) {
  14532. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14533. }
  14534. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14535. this._internalTexturesCache.push(texture);
  14536. return texture;
  14537. };
  14538. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14539. var gl = this._gl;
  14540. if (!gl) {
  14541. return;
  14542. }
  14543. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14544. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14545. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14546. if (!noMipmap && !isCompressed) {
  14547. gl.generateMipmap(gl.TEXTURE_2D);
  14548. }
  14549. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14550. // this.resetTextureCache();
  14551. if (scene) {
  14552. scene._removePendingData(texture);
  14553. }
  14554. texture.onLoadedObservable.notifyObservers(texture);
  14555. texture.onLoadedObservable.clear();
  14556. };
  14557. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14558. var _this = this;
  14559. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14560. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14561. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14562. var gl = this._gl;
  14563. if (!gl) {
  14564. return;
  14565. }
  14566. if (!texture._webGLTexture) {
  14567. // this.resetTextureCache();
  14568. if (scene) {
  14569. scene._removePendingData(texture);
  14570. }
  14571. return;
  14572. }
  14573. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14574. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14575. texture.baseWidth = width;
  14576. texture.baseHeight = height;
  14577. texture.width = potWidth;
  14578. texture.height = potHeight;
  14579. texture.isReady = true;
  14580. if (processFunction(potWidth, potHeight, function () {
  14581. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14582. })) {
  14583. // Returning as texture needs extra async steps
  14584. return;
  14585. }
  14586. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14587. };
  14588. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14589. // Create new RGBA data container.
  14590. var rgbaData;
  14591. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14592. rgbaData = new Float32Array(width * height * 4);
  14593. }
  14594. else {
  14595. rgbaData = new Uint32Array(width * height * 4);
  14596. }
  14597. // Convert each pixel.
  14598. for (var x = 0; x < width; x++) {
  14599. for (var y = 0; y < height; y++) {
  14600. var index = (y * width + x) * 3;
  14601. var newIndex = (y * width + x) * 4;
  14602. // Map Old Value to new value.
  14603. rgbaData[newIndex + 0] = rgbData[index + 0];
  14604. rgbaData[newIndex + 1] = rgbData[index + 1];
  14605. rgbaData[newIndex + 2] = rgbData[index + 2];
  14606. // Add fully opaque alpha channel.
  14607. rgbaData[newIndex + 3] = 1;
  14608. }
  14609. }
  14610. return rgbaData;
  14611. };
  14612. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14613. var gl = this._gl;
  14614. if (texture._framebuffer) {
  14615. gl.deleteFramebuffer(texture._framebuffer);
  14616. texture._framebuffer = null;
  14617. }
  14618. if (texture._depthStencilBuffer) {
  14619. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14620. texture._depthStencilBuffer = null;
  14621. }
  14622. if (texture._MSAAFramebuffer) {
  14623. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14624. texture._MSAAFramebuffer = null;
  14625. }
  14626. if (texture._MSAARenderBuffer) {
  14627. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14628. texture._MSAARenderBuffer = null;
  14629. }
  14630. };
  14631. Engine.prototype._releaseTexture = function (texture) {
  14632. var gl = this._gl;
  14633. this._releaseFramebufferObjects(texture);
  14634. gl.deleteTexture(texture._webGLTexture);
  14635. // Unbind channels
  14636. this.unbindAllTextures();
  14637. var index = this._internalTexturesCache.indexOf(texture);
  14638. if (index !== -1) {
  14639. this._internalTexturesCache.splice(index, 1);
  14640. }
  14641. // Integrated fixed lod samplers.
  14642. if (texture._lodTextureHigh) {
  14643. texture._lodTextureHigh.dispose();
  14644. }
  14645. if (texture._lodTextureMid) {
  14646. texture._lodTextureMid.dispose();
  14647. }
  14648. if (texture._lodTextureLow) {
  14649. texture._lodTextureLow.dispose();
  14650. }
  14651. // Set output texture of post process to null if the texture has been released/disposed
  14652. this.scenes.forEach(function (scene) {
  14653. scene.postProcesses.forEach(function (postProcess) {
  14654. if (postProcess._outputTexture == texture) {
  14655. postProcess._outputTexture = null;
  14656. }
  14657. });
  14658. scene.cameras.forEach(function (camera) {
  14659. camera._postProcesses.forEach(function (postProcess) {
  14660. if (postProcess) {
  14661. if (postProcess._outputTexture == texture) {
  14662. postProcess._outputTexture = null;
  14663. }
  14664. }
  14665. });
  14666. });
  14667. });
  14668. };
  14669. Engine.prototype.setProgram = function (program) {
  14670. if (this._currentProgram !== program) {
  14671. this._gl.useProgram(program);
  14672. this._currentProgram = program;
  14673. }
  14674. };
  14675. Engine.prototype.bindSamplers = function (effect) {
  14676. this.setProgram(effect.getProgram());
  14677. var samplers = effect.getSamplers();
  14678. for (var index = 0; index < samplers.length; index++) {
  14679. var uniform = effect.getUniform(samplers[index]);
  14680. if (uniform) {
  14681. this._boundUniforms[index] = uniform;
  14682. }
  14683. }
  14684. this._currentEffect = null;
  14685. };
  14686. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14687. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14688. return;
  14689. }
  14690. // Remove
  14691. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14692. // Bind last to it
  14693. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14694. // Bind to dummy
  14695. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14696. };
  14697. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14698. if (!internalTexture) {
  14699. return -1;
  14700. }
  14701. internalTexture._initialSlot = channel;
  14702. if (this.disableTextureBindingOptimization) {
  14703. if (channel !== internalTexture._designatedSlot) {
  14704. this._textureCollisions.addCount(1, false);
  14705. }
  14706. }
  14707. else {
  14708. if (channel !== internalTexture._designatedSlot) {
  14709. if (internalTexture._designatedSlot > -1) {
  14710. return internalTexture._designatedSlot;
  14711. }
  14712. else {
  14713. // No slot for this texture, let's pick a new one (if we find a free slot)
  14714. if (this._nextFreeTextureSlots.length) {
  14715. return this._nextFreeTextureSlots[0];
  14716. }
  14717. // We need to recycle the oldest bound texture, sorry.
  14718. this._textureCollisions.addCount(1, false);
  14719. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14720. }
  14721. }
  14722. }
  14723. return channel;
  14724. };
  14725. Engine.prototype._linkTrackers = function (previous, next) {
  14726. previous.next = next;
  14727. next.previous = previous;
  14728. };
  14729. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14730. var currentSlot = internalTexture._designatedSlot;
  14731. if (currentSlot === -1) {
  14732. return -1;
  14733. }
  14734. internalTexture._designatedSlot = -1;
  14735. if (this.disableTextureBindingOptimization) {
  14736. return -1;
  14737. }
  14738. // Remove from bound list
  14739. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14740. // Free the slot
  14741. this._boundTexturesCache[currentSlot] = null;
  14742. this._nextFreeTextureSlots.push(currentSlot);
  14743. return currentSlot;
  14744. };
  14745. Engine.prototype._activateCurrentTexture = function () {
  14746. if (this._currentTextureChannel !== this._activeChannel) {
  14747. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14748. this._currentTextureChannel = this._activeChannel;
  14749. }
  14750. };
  14751. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14752. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14753. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14754. this._activeChannel = texture._designatedSlot;
  14755. }
  14756. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14757. var isTextureForRendering = texture && texture._initialSlot > -1;
  14758. if (currentTextureBound !== texture) {
  14759. if (currentTextureBound) {
  14760. this._removeDesignatedSlot(currentTextureBound);
  14761. }
  14762. this._activateCurrentTexture();
  14763. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14764. this._boundTexturesCache[this._activeChannel] = texture;
  14765. if (texture) {
  14766. if (!this.disableTextureBindingOptimization) {
  14767. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14768. if (slotIndex > -1) {
  14769. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14770. }
  14771. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14772. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14773. }
  14774. texture._designatedSlot = this._activeChannel;
  14775. }
  14776. }
  14777. else if (forTextureDataUpdate) {
  14778. this._activateCurrentTexture();
  14779. }
  14780. if (isTextureForRendering && !forTextureDataUpdate) {
  14781. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14782. }
  14783. };
  14784. Engine.prototype._bindTexture = function (channel, texture) {
  14785. if (channel < 0) {
  14786. return;
  14787. }
  14788. if (texture) {
  14789. channel = this._getCorrectTextureChannel(channel, texture);
  14790. }
  14791. this._activeChannel = channel;
  14792. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14793. };
  14794. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14795. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14796. };
  14797. /**
  14798. * Binds the output of the passed in post process to the texture channel specified
  14799. * @param channel The channel the texture should be bound to
  14800. * @param postProcess The post process which's output should be bound
  14801. */
  14802. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  14803. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  14804. };
  14805. Engine.prototype.unbindAllTextures = function () {
  14806. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14807. this._activeChannel = channel;
  14808. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14809. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14810. if (this.webGLVersion > 1) {
  14811. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14812. }
  14813. }
  14814. };
  14815. /**
  14816. * Sets a texture to the according uniform.
  14817. * @param channel The texture channel
  14818. * @param uniform The uniform to set
  14819. * @param texture The texture to apply
  14820. */
  14821. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14822. if (channel < 0) {
  14823. return;
  14824. }
  14825. if (uniform) {
  14826. this._boundUniforms[channel] = uniform;
  14827. }
  14828. this._setTexture(channel, texture);
  14829. };
  14830. /**
  14831. * Sets a depth stencil texture from a render target to the according uniform.
  14832. * @param channel The texture channel
  14833. * @param uniform The uniform to set
  14834. * @param texture The render target texture containing the depth stencil texture to apply
  14835. */
  14836. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  14837. if (channel < 0) {
  14838. return;
  14839. }
  14840. if (uniform) {
  14841. this._boundUniforms[channel] = uniform;
  14842. }
  14843. if (!texture || !texture.depthStencilTexture) {
  14844. this._setTexture(channel, null);
  14845. }
  14846. else {
  14847. this._setTexture(channel, texture, false, true);
  14848. }
  14849. };
  14850. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14851. var uniform = this._boundUniforms[sourceSlot];
  14852. if (uniform._currentState === destination) {
  14853. return;
  14854. }
  14855. this._gl.uniform1i(uniform, destination);
  14856. uniform._currentState = destination;
  14857. };
  14858. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  14859. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14860. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  14861. // Not ready?
  14862. if (!texture) {
  14863. if (this._boundTexturesCache[channel] != null) {
  14864. this._activeChannel = channel;
  14865. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14866. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14867. if (this.webGLVersion > 1) {
  14868. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14869. }
  14870. }
  14871. return false;
  14872. }
  14873. // Video
  14874. if (texture.video) {
  14875. this._activeChannel = channel;
  14876. texture.update();
  14877. }
  14878. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14879. texture.delayLoad();
  14880. return false;
  14881. }
  14882. var internalTexture;
  14883. if (depthStencilTexture) {
  14884. internalTexture = texture.depthStencilTexture;
  14885. }
  14886. else if (texture.isReady()) {
  14887. internalTexture = texture.getInternalTexture();
  14888. }
  14889. else if (texture.isCube) {
  14890. internalTexture = this.emptyCubeTexture;
  14891. }
  14892. else if (texture.is3D) {
  14893. internalTexture = this.emptyTexture3D;
  14894. }
  14895. else {
  14896. internalTexture = this.emptyTexture;
  14897. }
  14898. if (!isPartOfTextureArray) {
  14899. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14900. }
  14901. if (this._boundTexturesCache[channel] === internalTexture) {
  14902. this._moveBoundTextureOnTop(internalTexture);
  14903. if (!isPartOfTextureArray) {
  14904. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14905. }
  14906. return false;
  14907. }
  14908. this._activeChannel = channel;
  14909. if (internalTexture && internalTexture.is3D) {
  14910. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14911. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14912. internalTexture._cachedWrapU = texture.wrapU;
  14913. switch (texture.wrapU) {
  14914. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14915. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14916. break;
  14917. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14918. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14919. break;
  14920. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14921. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14922. break;
  14923. }
  14924. }
  14925. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14926. internalTexture._cachedWrapV = texture.wrapV;
  14927. switch (texture.wrapV) {
  14928. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14929. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14930. break;
  14931. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14932. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14933. break;
  14934. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14935. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14936. break;
  14937. }
  14938. }
  14939. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14940. internalTexture._cachedWrapR = texture.wrapR;
  14941. switch (texture.wrapR) {
  14942. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14943. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14944. break;
  14945. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14946. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14947. break;
  14948. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14949. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14950. break;
  14951. }
  14952. }
  14953. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14954. }
  14955. else if (internalTexture && internalTexture.isCube) {
  14956. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14957. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14958. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14959. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14960. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14961. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14962. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14963. }
  14964. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14965. }
  14966. else {
  14967. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14968. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14969. internalTexture._cachedWrapU = texture.wrapU;
  14970. switch (texture.wrapU) {
  14971. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14972. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14973. break;
  14974. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14975. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14976. break;
  14977. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14978. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14979. break;
  14980. }
  14981. }
  14982. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14983. internalTexture._cachedWrapV = texture.wrapV;
  14984. switch (texture.wrapV) {
  14985. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14986. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14987. break;
  14988. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14989. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14990. break;
  14991. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14992. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14993. break;
  14994. }
  14995. }
  14996. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14997. }
  14998. return true;
  14999. };
  15000. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  15001. if (channel < 0 || !uniform) {
  15002. return;
  15003. }
  15004. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  15005. this._textureUnits = new Int32Array(textures.length);
  15006. }
  15007. for (var i = 0; i < textures.length; i++) {
  15008. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  15009. }
  15010. this._gl.uniform1iv(uniform, this._textureUnits);
  15011. for (var index = 0; index < textures.length; index++) {
  15012. this._setTexture(this._textureUnits[index], textures[index], true);
  15013. }
  15014. };
  15015. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  15016. var internalTexture = texture.getInternalTexture();
  15017. if (!internalTexture) {
  15018. return;
  15019. }
  15020. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  15021. var value = texture.anisotropicFilteringLevel;
  15022. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  15023. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  15024. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  15025. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  15026. }
  15027. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  15028. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  15029. internalTexture._cachedAnisotropicFilteringLevel = value;
  15030. }
  15031. };
  15032. Engine.prototype.readPixels = function (x, y, width, height) {
  15033. var data = new Uint8Array(height * width * 4);
  15034. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  15035. return data;
  15036. };
  15037. /**
  15038. * Add an externaly attached data from its key.
  15039. * This method call will fail and return false, if such key already exists.
  15040. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  15041. * @param key the unique key that identifies the data
  15042. * @param data the data object to associate to the key for this Engine instance
  15043. * @return true if no such key were already present and the data was added successfully, false otherwise
  15044. */
  15045. Engine.prototype.addExternalData = function (key, data) {
  15046. if (!this._externalData) {
  15047. this._externalData = new BABYLON.StringDictionary();
  15048. }
  15049. return this._externalData.add(key, data);
  15050. };
  15051. /**
  15052. * Get an externaly attached data from its key
  15053. * @param key the unique key that identifies the data
  15054. * @return the associated data, if present (can be null), or undefined if not present
  15055. */
  15056. Engine.prototype.getExternalData = function (key) {
  15057. if (!this._externalData) {
  15058. this._externalData = new BABYLON.StringDictionary();
  15059. }
  15060. return this._externalData.get(key);
  15061. };
  15062. /**
  15063. * Get an externaly attached data from its key, create it using a factory if it's not already present
  15064. * @param key the unique key that identifies the data
  15065. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  15066. * @return the associated data, can be null if the factory returned null.
  15067. */
  15068. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  15069. if (!this._externalData) {
  15070. this._externalData = new BABYLON.StringDictionary();
  15071. }
  15072. return this._externalData.getOrAddWithFactory(key, factory);
  15073. };
  15074. /**
  15075. * Remove an externaly attached data from the Engine instance
  15076. * @param key the unique key that identifies the data
  15077. * @return true if the data was successfully removed, false if it doesn't exist
  15078. */
  15079. Engine.prototype.removeExternalData = function (key) {
  15080. if (!this._externalData) {
  15081. this._externalData = new BABYLON.StringDictionary();
  15082. }
  15083. return this._externalData.remove(key);
  15084. };
  15085. Engine.prototype.unbindAllAttributes = function () {
  15086. if (this._mustWipeVertexAttributes) {
  15087. this._mustWipeVertexAttributes = false;
  15088. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  15089. this._gl.disableVertexAttribArray(i);
  15090. this._vertexAttribArraysEnabled[i] = false;
  15091. this._currentBufferPointers[i].active = false;
  15092. }
  15093. return;
  15094. }
  15095. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  15096. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  15097. continue;
  15098. }
  15099. this._gl.disableVertexAttribArray(i);
  15100. this._vertexAttribArraysEnabled[i] = false;
  15101. this._currentBufferPointers[i].active = false;
  15102. }
  15103. };
  15104. Engine.prototype.releaseEffects = function () {
  15105. for (var name in this._compiledEffects) {
  15106. this._deleteProgram(this._compiledEffects[name]._program);
  15107. }
  15108. this._compiledEffects = {};
  15109. };
  15110. // Dispose
  15111. Engine.prototype.dispose = function () {
  15112. this.hideLoadingUI();
  15113. this.stopRenderLoop();
  15114. // Release postProcesses
  15115. while (this.postProcesses.length) {
  15116. this.postProcesses[0].dispose();
  15117. }
  15118. // Empty texture
  15119. if (this._emptyTexture) {
  15120. this._releaseTexture(this._emptyTexture);
  15121. this._emptyTexture = null;
  15122. }
  15123. if (this._emptyCubeTexture) {
  15124. this._releaseTexture(this._emptyCubeTexture);
  15125. this._emptyCubeTexture = null;
  15126. }
  15127. // Rescale PP
  15128. if (this._rescalePostProcess) {
  15129. this._rescalePostProcess.dispose();
  15130. }
  15131. // Release scenes
  15132. while (this.scenes.length) {
  15133. this.scenes[0].dispose();
  15134. }
  15135. // Release audio engine
  15136. if (Engine.audioEngine) {
  15137. Engine.audioEngine.dispose();
  15138. }
  15139. // Release effects
  15140. this.releaseEffects();
  15141. // Unbind
  15142. this.unbindAllAttributes();
  15143. if (this._dummyFramebuffer) {
  15144. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  15145. }
  15146. //WebVR
  15147. this.disableVR();
  15148. // Events
  15149. if (BABYLON.Tools.IsWindowObjectExist()) {
  15150. window.removeEventListener("blur", this._onBlur);
  15151. window.removeEventListener("focus", this._onFocus);
  15152. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  15153. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  15154. if (this._renderingCanvas) {
  15155. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  15156. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  15157. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  15158. if (!this._doNotHandleContextLost) {
  15159. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  15160. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  15161. }
  15162. }
  15163. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  15164. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  15165. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  15166. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  15167. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  15168. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  15169. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  15170. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  15171. if (this._onVrDisplayConnect) {
  15172. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  15173. if (this._onVrDisplayDisconnect) {
  15174. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  15175. }
  15176. if (this._onVrDisplayPresentChange) {
  15177. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  15178. }
  15179. this._onVrDisplayConnect = null;
  15180. this._onVrDisplayDisconnect = null;
  15181. }
  15182. }
  15183. // Remove from Instances
  15184. var index = Engine.Instances.indexOf(this);
  15185. if (index >= 0) {
  15186. Engine.Instances.splice(index, 1);
  15187. }
  15188. this._workingCanvas = null;
  15189. this._workingContext = null;
  15190. this._currentBufferPointers = [];
  15191. this._renderingCanvas = null;
  15192. this._currentProgram = null;
  15193. this._bindedRenderFunction = null;
  15194. this.onResizeObservable.clear();
  15195. this.onCanvasBlurObservable.clear();
  15196. this.onCanvasFocusObservable.clear();
  15197. this.onCanvasPointerOutObservable.clear();
  15198. this.onBeginFrameObservable.clear();
  15199. this.onEndFrameObservable.clear();
  15200. BABYLON.Effect.ResetCache();
  15201. // Abort active requests
  15202. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  15203. var request = _a[_i];
  15204. request.abort();
  15205. }
  15206. };
  15207. // Loading screen
  15208. Engine.prototype.displayLoadingUI = function () {
  15209. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15210. return;
  15211. }
  15212. var loadingScreen = this.loadingScreen;
  15213. if (loadingScreen) {
  15214. loadingScreen.displayLoadingUI();
  15215. }
  15216. };
  15217. Engine.prototype.hideLoadingUI = function () {
  15218. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15219. return;
  15220. }
  15221. var loadingScreen = this.loadingScreen;
  15222. if (loadingScreen) {
  15223. loadingScreen.hideLoadingUI();
  15224. }
  15225. };
  15226. Object.defineProperty(Engine.prototype, "loadingScreen", {
  15227. get: function () {
  15228. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  15229. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  15230. return this._loadingScreen;
  15231. },
  15232. set: function (loadingScreen) {
  15233. this._loadingScreen = loadingScreen;
  15234. },
  15235. enumerable: true,
  15236. configurable: true
  15237. });
  15238. Object.defineProperty(Engine.prototype, "loadingUIText", {
  15239. set: function (text) {
  15240. this.loadingScreen.loadingUIText = text;
  15241. },
  15242. enumerable: true,
  15243. configurable: true
  15244. });
  15245. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  15246. set: function (color) {
  15247. this.loadingScreen.loadingUIBackgroundColor = color;
  15248. },
  15249. enumerable: true,
  15250. configurable: true
  15251. });
  15252. Engine.prototype.attachContextLostEvent = function (callback) {
  15253. if (this._renderingCanvas) {
  15254. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  15255. }
  15256. };
  15257. Engine.prototype.attachContextRestoredEvent = function (callback) {
  15258. if (this._renderingCanvas) {
  15259. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  15260. }
  15261. };
  15262. Engine.prototype.getVertexShaderSource = function (program) {
  15263. var shaders = this._gl.getAttachedShaders(program);
  15264. if (!shaders) {
  15265. return null;
  15266. }
  15267. return this._gl.getShaderSource(shaders[0]);
  15268. };
  15269. Engine.prototype.getFragmentShaderSource = function (program) {
  15270. var shaders = this._gl.getAttachedShaders(program);
  15271. if (!shaders) {
  15272. return null;
  15273. }
  15274. return this._gl.getShaderSource(shaders[1]);
  15275. };
  15276. Engine.prototype.getError = function () {
  15277. return this._gl.getError();
  15278. };
  15279. // FPS
  15280. Engine.prototype.getFps = function () {
  15281. return this._fps;
  15282. };
  15283. Engine.prototype.getDeltaTime = function () {
  15284. return this._deltaTime;
  15285. };
  15286. Engine.prototype._measureFps = function () {
  15287. this._performanceMonitor.sampleFrame();
  15288. this._fps = this._performanceMonitor.averageFPS;
  15289. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  15290. };
  15291. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  15292. if (faceIndex === void 0) { faceIndex = -1; }
  15293. var gl = this._gl;
  15294. if (!this._dummyFramebuffer) {
  15295. var dummy = gl.createFramebuffer();
  15296. if (!dummy) {
  15297. throw new Error("Unable to create dummy framebuffer");
  15298. }
  15299. this._dummyFramebuffer = dummy;
  15300. }
  15301. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  15302. if (faceIndex > -1) {
  15303. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  15304. }
  15305. else {
  15306. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15307. }
  15308. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  15309. var buffer;
  15310. switch (readType) {
  15311. case gl.UNSIGNED_BYTE:
  15312. buffer = new Uint8Array(4 * width * height);
  15313. readType = gl.UNSIGNED_BYTE;
  15314. break;
  15315. default:
  15316. buffer = new Float32Array(4 * width * height);
  15317. readType = gl.FLOAT;
  15318. break;
  15319. }
  15320. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  15321. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  15322. return buffer;
  15323. };
  15324. Engine.prototype._canRenderToFloatFramebuffer = function () {
  15325. if (this._webGLVersion > 1) {
  15326. return this._caps.colorBufferFloat;
  15327. }
  15328. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  15329. };
  15330. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  15331. if (this._webGLVersion > 1) {
  15332. return this._caps.colorBufferFloat;
  15333. }
  15334. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  15335. };
  15336. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  15337. Engine.prototype._canRenderToFramebuffer = function (type) {
  15338. var gl = this._gl;
  15339. //clear existing errors
  15340. while (gl.getError() !== gl.NO_ERROR) { }
  15341. var successful = true;
  15342. var texture = gl.createTexture();
  15343. gl.bindTexture(gl.TEXTURE_2D, texture);
  15344. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15345. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15346. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15347. var fb = gl.createFramebuffer();
  15348. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  15349. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  15350. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  15351. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  15352. successful = successful && (gl.getError() === gl.NO_ERROR);
  15353. //try render by clearing frame buffer's color buffer
  15354. if (successful) {
  15355. gl.clear(gl.COLOR_BUFFER_BIT);
  15356. successful = successful && (gl.getError() === gl.NO_ERROR);
  15357. }
  15358. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15359. if (successful) {
  15360. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15361. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15362. var readFormat = gl.RGBA;
  15363. var readType = gl.UNSIGNED_BYTE;
  15364. var buffer = new Uint8Array(4);
  15365. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15366. successful = successful && (gl.getError() === gl.NO_ERROR);
  15367. }
  15368. //clean up
  15369. gl.deleteTexture(texture);
  15370. gl.deleteFramebuffer(fb);
  15371. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15372. //clear accumulated errors
  15373. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15374. return successful;
  15375. };
  15376. Engine.prototype._getWebGLTextureType = function (type) {
  15377. if (type === Engine.TEXTURETYPE_FLOAT) {
  15378. return this._gl.FLOAT;
  15379. }
  15380. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15381. // Add Half Float Constant.
  15382. return this._gl.HALF_FLOAT_OES;
  15383. }
  15384. return this._gl.UNSIGNED_BYTE;
  15385. };
  15386. ;
  15387. Engine.prototype._getInternalFormat = function (format) {
  15388. var internalFormat = this._gl.RGBA;
  15389. switch (format) {
  15390. case Engine.TEXTUREFORMAT_ALPHA:
  15391. internalFormat = this._gl.ALPHA;
  15392. break;
  15393. case Engine.TEXTUREFORMAT_LUMINANCE:
  15394. internalFormat = this._gl.LUMINANCE;
  15395. break;
  15396. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  15397. internalFormat = this._gl.LUMINANCE_ALPHA;
  15398. break;
  15399. case Engine.TEXTUREFORMAT_RGB:
  15400. case Engine.TEXTUREFORMAT_RGB32F:
  15401. internalFormat = this._gl.RGB;
  15402. break;
  15403. case Engine.TEXTUREFORMAT_RGBA:
  15404. case Engine.TEXTUREFORMAT_RGBA32F:
  15405. internalFormat = this._gl.RGBA;
  15406. break;
  15407. case Engine.TEXTUREFORMAT_R32F:
  15408. internalFormat = this._gl.RED;
  15409. break;
  15410. case Engine.TEXTUREFORMAT_RG32F:
  15411. internalFormat = this._gl.RG;
  15412. break;
  15413. }
  15414. return internalFormat;
  15415. };
  15416. /** @ignore */
  15417. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15418. if (this._webGLVersion === 1) {
  15419. if (format) {
  15420. switch (format) {
  15421. case Engine.TEXTUREFORMAT_LUMINANCE:
  15422. return this._gl.LUMINANCE;
  15423. }
  15424. }
  15425. return this._gl.RGBA;
  15426. }
  15427. if (type === Engine.TEXTURETYPE_FLOAT) {
  15428. if (format) {
  15429. switch (format) {
  15430. case Engine.TEXTUREFORMAT_R32F:
  15431. return this._gl.R32F;
  15432. case Engine.TEXTUREFORMAT_RG32F:
  15433. return this._gl.RG32F;
  15434. case Engine.TEXTUREFORMAT_RGB32F:
  15435. return this._gl.RGB32F;
  15436. }
  15437. }
  15438. return this._gl.RGBA32F;
  15439. }
  15440. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15441. return this._gl.RGBA16F;
  15442. }
  15443. if (format) {
  15444. switch (format) {
  15445. case Engine.TEXTUREFORMAT_LUMINANCE:
  15446. return this._gl.LUMINANCE;
  15447. }
  15448. }
  15449. return this._gl.RGBA;
  15450. };
  15451. ;
  15452. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15453. if (type === Engine.TEXTURETYPE_FLOAT) {
  15454. return this._gl.RGBA32F;
  15455. }
  15456. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15457. return this._gl.RGBA16F;
  15458. }
  15459. return this._gl.RGBA8;
  15460. };
  15461. ;
  15462. Engine.prototype.createQuery = function () {
  15463. return this._gl.createQuery();
  15464. };
  15465. Engine.prototype.deleteQuery = function (query) {
  15466. this._gl.deleteQuery(query);
  15467. return this;
  15468. };
  15469. Engine.prototype.isQueryResultAvailable = function (query) {
  15470. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15471. };
  15472. Engine.prototype.getQueryResult = function (query) {
  15473. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15474. };
  15475. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15476. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15477. this._gl.beginQuery(glAlgorithm, query);
  15478. return this;
  15479. };
  15480. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15481. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15482. this._gl.endQuery(glAlgorithm);
  15483. return this;
  15484. };
  15485. /* Time queries */
  15486. Engine.prototype._createTimeQuery = function () {
  15487. var timerQuery = this._caps.timerQuery;
  15488. if (timerQuery.createQueryEXT) {
  15489. return timerQuery.createQueryEXT();
  15490. }
  15491. return this.createQuery();
  15492. };
  15493. Engine.prototype._deleteTimeQuery = function (query) {
  15494. var timerQuery = this._caps.timerQuery;
  15495. if (timerQuery.deleteQueryEXT) {
  15496. timerQuery.deleteQueryEXT(query);
  15497. return;
  15498. }
  15499. this.deleteQuery(query);
  15500. };
  15501. Engine.prototype._getTimeQueryResult = function (query) {
  15502. var timerQuery = this._caps.timerQuery;
  15503. if (timerQuery.getQueryObjectEXT) {
  15504. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15505. }
  15506. return this.getQueryResult(query);
  15507. };
  15508. Engine.prototype._getTimeQueryAvailability = function (query) {
  15509. var timerQuery = this._caps.timerQuery;
  15510. if (timerQuery.getQueryObjectEXT) {
  15511. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15512. }
  15513. return this.isQueryResultAvailable(query);
  15514. };
  15515. Engine.prototype.startTimeQuery = function () {
  15516. var timerQuery = this._caps.timerQuery;
  15517. if (!timerQuery) {
  15518. return null;
  15519. }
  15520. var token = new BABYLON._TimeToken();
  15521. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15522. if (this._caps.canUseTimestampForTimerQuery) {
  15523. token._startTimeQuery = this._createTimeQuery();
  15524. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15525. }
  15526. else {
  15527. if (this._currentNonTimestampToken) {
  15528. return this._currentNonTimestampToken;
  15529. }
  15530. token._timeElapsedQuery = this._createTimeQuery();
  15531. if (timerQuery.beginQueryEXT) {
  15532. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15533. }
  15534. else {
  15535. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15536. }
  15537. this._currentNonTimestampToken = token;
  15538. }
  15539. return token;
  15540. };
  15541. Engine.prototype.endTimeQuery = function (token) {
  15542. var timerQuery = this._caps.timerQuery;
  15543. if (!timerQuery || !token) {
  15544. return -1;
  15545. }
  15546. if (this._caps.canUseTimestampForTimerQuery) {
  15547. if (!token._startTimeQuery) {
  15548. return -1;
  15549. }
  15550. if (!token._endTimeQuery) {
  15551. token._endTimeQuery = this._createTimeQuery();
  15552. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15553. }
  15554. }
  15555. else if (!token._timeElapsedQueryEnded) {
  15556. if (!token._timeElapsedQuery) {
  15557. return -1;
  15558. }
  15559. if (timerQuery.endQueryEXT) {
  15560. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15561. }
  15562. else {
  15563. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15564. }
  15565. token._timeElapsedQueryEnded = true;
  15566. }
  15567. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15568. var available = false;
  15569. if (token._endTimeQuery) {
  15570. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15571. }
  15572. else if (token._timeElapsedQuery) {
  15573. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15574. }
  15575. if (available && !disjoint) {
  15576. var result = 0;
  15577. if (this._caps.canUseTimestampForTimerQuery) {
  15578. if (!token._startTimeQuery || !token._endTimeQuery) {
  15579. return -1;
  15580. }
  15581. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15582. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15583. result = timeEnd - timeStart;
  15584. this._deleteTimeQuery(token._startTimeQuery);
  15585. this._deleteTimeQuery(token._endTimeQuery);
  15586. token._startTimeQuery = null;
  15587. token._endTimeQuery = null;
  15588. }
  15589. else {
  15590. if (!token._timeElapsedQuery) {
  15591. return -1;
  15592. }
  15593. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15594. this._deleteTimeQuery(token._timeElapsedQuery);
  15595. token._timeElapsedQuery = null;
  15596. token._timeElapsedQueryEnded = false;
  15597. this._currentNonTimestampToken = null;
  15598. }
  15599. return result;
  15600. }
  15601. return -1;
  15602. };
  15603. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15604. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15605. };
  15606. // Transform feedback
  15607. Engine.prototype.createTransformFeedback = function () {
  15608. return this._gl.createTransformFeedback();
  15609. };
  15610. Engine.prototype.deleteTransformFeedback = function (value) {
  15611. this._gl.deleteTransformFeedback(value);
  15612. };
  15613. Engine.prototype.bindTransformFeedback = function (value) {
  15614. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15615. };
  15616. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15617. if (usePoints === void 0) { usePoints = true; }
  15618. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15619. };
  15620. Engine.prototype.endTransformFeedback = function () {
  15621. this._gl.endTransformFeedback();
  15622. };
  15623. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15624. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15625. };
  15626. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15627. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15628. };
  15629. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15630. var _this = this;
  15631. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15632. this._activeRequests.push(request);
  15633. request.onCompleteObservable.add(function (request) {
  15634. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15635. });
  15636. return request;
  15637. };
  15638. /** @ignore */
  15639. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15640. var _this = this;
  15641. return new Promise(function (resolve, reject) {
  15642. _this._loadFile(url, function (data) {
  15643. resolve(data);
  15644. }, undefined, database, useArrayBuffer, function (request, exception) {
  15645. reject(exception);
  15646. });
  15647. });
  15648. };
  15649. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15650. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15651. var onload = function (data) {
  15652. loadedFiles[index] = data;
  15653. loadedFiles._internalCount++;
  15654. if (loadedFiles._internalCount === 6) {
  15655. onfinish(loadedFiles);
  15656. }
  15657. };
  15658. var onerror = function (request, exception) {
  15659. if (onErrorCallBack && request) {
  15660. onErrorCallBack(request.status + " " + request.statusText, exception);
  15661. }
  15662. };
  15663. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15664. };
  15665. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15666. if (onError === void 0) { onError = null; }
  15667. var loadedFiles = [];
  15668. loadedFiles._internalCount = 0;
  15669. for (var index = 0; index < 6; index++) {
  15670. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15671. }
  15672. };
  15673. // Statics
  15674. Engine.isSupported = function () {
  15675. try {
  15676. var tempcanvas = document.createElement("canvas");
  15677. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15678. return gl != null && !!window.WebGLRenderingContext;
  15679. }
  15680. catch (e) {
  15681. return false;
  15682. }
  15683. };
  15684. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15685. Engine.ExceptionList = [
  15686. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15687. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15688. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15689. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15690. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15691. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15692. ];
  15693. Engine.Instances = new Array();
  15694. // Const statics
  15695. Engine._ALPHA_DISABLE = 0;
  15696. Engine._ALPHA_ADD = 1;
  15697. Engine._ALPHA_COMBINE = 2;
  15698. Engine._ALPHA_SUBTRACT = 3;
  15699. Engine._ALPHA_MULTIPLY = 4;
  15700. Engine._ALPHA_MAXIMIZED = 5;
  15701. Engine._ALPHA_ONEONE = 6;
  15702. Engine._ALPHA_PREMULTIPLIED = 7;
  15703. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15704. Engine._ALPHA_INTERPOLATE = 9;
  15705. Engine._ALPHA_SCREENMODE = 10;
  15706. Engine._DELAYLOADSTATE_NONE = 0;
  15707. Engine._DELAYLOADSTATE_LOADED = 1;
  15708. Engine._DELAYLOADSTATE_LOADING = 2;
  15709. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15710. Engine._TEXTUREFORMAT_ALPHA = 0;
  15711. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15712. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15713. Engine._TEXTUREFORMAT_RGB = 4;
  15714. Engine._TEXTUREFORMAT_RGBA = 5;
  15715. Engine._TEXTUREFORMAT_R32F = 6;
  15716. Engine._TEXTUREFORMAT_RG32F = 7;
  15717. Engine._TEXTUREFORMAT_RGB32F = 8;
  15718. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15719. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15720. Engine._TEXTURETYPE_FLOAT = 1;
  15721. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15722. // Depht or Stencil test Constants.
  15723. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15724. 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.
  15725. 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.
  15726. 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.
  15727. 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.
  15728. 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.
  15729. 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.
  15730. 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.
  15731. // Stencil Actions Constants.
  15732. Engine._KEEP = 0x1E00;
  15733. Engine._REPLACE = 0x1E01;
  15734. Engine._INCR = 0x1E02;
  15735. Engine._DECR = 0x1E03;
  15736. Engine._INVERT = 0x150A;
  15737. Engine._INCR_WRAP = 0x8507;
  15738. Engine._DECR_WRAP = 0x8508;
  15739. // Texture rescaling mode
  15740. Engine._SCALEMODE_FLOOR = 1;
  15741. Engine._SCALEMODE_NEAREST = 2;
  15742. Engine._SCALEMODE_CEILING = 3;
  15743. // Updatable statics so stick with vars here
  15744. Engine.CollisionsEpsilon = 0.001;
  15745. Engine.CodeRepository = "src/";
  15746. Engine.ShadersRepository = "src/Shaders/";
  15747. return Engine;
  15748. }());
  15749. BABYLON.Engine = Engine;
  15750. })(BABYLON || (BABYLON = {}));
  15751. //# sourceMappingURL=babylon.engine.js.map
  15752. "use strict";
  15753. var BABYLON;
  15754. (function (BABYLON) {
  15755. /**
  15756. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15757. */
  15758. var Node = /** @class */ (function () {
  15759. /**
  15760. * Creates a new Node
  15761. * @param {string} name - the name and id to be given to this node
  15762. * @param {BABYLON.Scene} the scene this node will be added to
  15763. */
  15764. function Node(name, scene) {
  15765. if (scene === void 0) { scene = null; }
  15766. /**
  15767. * Gets or sets a string used to store user defined state for the node
  15768. */
  15769. this.state = "";
  15770. /**
  15771. * Gets or sets an object used to store user defined information for the node
  15772. */
  15773. this.metadata = null;
  15774. /**
  15775. * Gets or sets a boolean used to define if the node must be serialized
  15776. */
  15777. this.doNotSerialize = false;
  15778. /** @ignore */
  15779. this._isDisposed = false;
  15780. /**
  15781. * Gets a list of {BABYLON.Animation} associated with the node
  15782. */
  15783. this.animations = new Array();
  15784. this._ranges = {};
  15785. this._isEnabled = true;
  15786. this._isReady = true;
  15787. /** @ignore */
  15788. this._currentRenderId = -1;
  15789. this._parentRenderId = -1;
  15790. this._animationPropertiesOverride = null;
  15791. /**
  15792. * An event triggered when the mesh is disposed
  15793. * @type {BABYLON.Observable}
  15794. */
  15795. this.onDisposeObservable = new BABYLON.Observable();
  15796. // Behaviors
  15797. this._behaviors = new Array();
  15798. this.name = name;
  15799. this.id = name;
  15800. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15801. this.uniqueId = this._scene.getUniqueId();
  15802. this._initCache();
  15803. }
  15804. /**
  15805. * Gets a boolean indicating if the node has been disposed
  15806. * @returns true if the node was disposed
  15807. */
  15808. Node.prototype.isDisposed = function () {
  15809. return this._isDisposed;
  15810. };
  15811. Object.defineProperty(Node.prototype, "parent", {
  15812. get: function () {
  15813. return this._parentNode;
  15814. },
  15815. /**
  15816. * Gets or sets the parent of the node
  15817. */
  15818. set: function (parent) {
  15819. if (this._parentNode === parent) {
  15820. return;
  15821. }
  15822. // Remove self from list of children of parent
  15823. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15824. var index = this._parentNode._children.indexOf(this);
  15825. if (index !== -1) {
  15826. this._parentNode._children.splice(index, 1);
  15827. }
  15828. }
  15829. // Store new parent
  15830. this._parentNode = parent;
  15831. // Add as child to new parent
  15832. if (this._parentNode) {
  15833. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15834. this._parentNode._children = new Array();
  15835. }
  15836. this._parentNode._children.push(this);
  15837. }
  15838. },
  15839. enumerable: true,
  15840. configurable: true
  15841. });
  15842. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15843. /**
  15844. * Gets or sets the animation properties override
  15845. */
  15846. get: function () {
  15847. return this._animationPropertiesOverride;
  15848. },
  15849. set: function (value) {
  15850. this._animationPropertiesOverride = value;
  15851. },
  15852. enumerable: true,
  15853. configurable: true
  15854. });
  15855. /**
  15856. * Gets a string idenfifying the name of the class
  15857. * @returns "Node" string
  15858. */
  15859. Node.prototype.getClassName = function () {
  15860. return "Node";
  15861. };
  15862. Object.defineProperty(Node.prototype, "onDispose", {
  15863. /**
  15864. * Sets a callback that will be raised when the node will be disposed
  15865. */
  15866. set: function (callback) {
  15867. if (this._onDisposeObserver) {
  15868. this.onDisposeObservable.remove(this._onDisposeObserver);
  15869. }
  15870. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15871. },
  15872. enumerable: true,
  15873. configurable: true
  15874. });
  15875. /**
  15876. * Gets the scene of the node
  15877. * @returns a {BABYLON.Scene}
  15878. */
  15879. Node.prototype.getScene = function () {
  15880. return this._scene;
  15881. };
  15882. /**
  15883. * Gets the engine of the node
  15884. * @returns a {BABYLON.Engine}
  15885. */
  15886. Node.prototype.getEngine = function () {
  15887. return this._scene.getEngine();
  15888. };
  15889. /**
  15890. * Attach a behavior to the node
  15891. * @see http://doc.babylonjs.com/features/behaviour
  15892. * @param behavior defines the behavior to attach
  15893. * @returns the current Node
  15894. */
  15895. Node.prototype.addBehavior = function (behavior) {
  15896. var _this = this;
  15897. var index = this._behaviors.indexOf(behavior);
  15898. if (index !== -1) {
  15899. return this;
  15900. }
  15901. behavior.init();
  15902. if (this._scene.isLoading) {
  15903. // We defer the attach when the scene will be loaded
  15904. var observer = this._scene.onDataLoadedObservable.add(function () {
  15905. behavior.attach(_this);
  15906. setTimeout(function () {
  15907. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15908. _this._scene.onDataLoadedObservable.remove(observer);
  15909. }, 0);
  15910. });
  15911. }
  15912. else {
  15913. behavior.attach(this);
  15914. }
  15915. this._behaviors.push(behavior);
  15916. return this;
  15917. };
  15918. /**
  15919. * Remove an attached behavior
  15920. * @see http://doc.babylonjs.com/features/behaviour
  15921. * @param behavior defines the behavior to attach
  15922. * @returns the current Node
  15923. */
  15924. Node.prototype.removeBehavior = function (behavior) {
  15925. var index = this._behaviors.indexOf(behavior);
  15926. if (index === -1) {
  15927. return this;
  15928. }
  15929. this._behaviors[index].detach();
  15930. this._behaviors.splice(index, 1);
  15931. return this;
  15932. };
  15933. Object.defineProperty(Node.prototype, "behaviors", {
  15934. /**
  15935. * Gets the list of attached behaviors
  15936. * @see http://doc.babylonjs.com/features/behaviour
  15937. */
  15938. get: function () {
  15939. return this._behaviors;
  15940. },
  15941. enumerable: true,
  15942. configurable: true
  15943. });
  15944. /**
  15945. * Gets an attached behavior by name
  15946. * @param name defines the name of the behavior to look for
  15947. * @see http://doc.babylonjs.com/features/behaviour
  15948. * @returns null if behavior was not found else the requested behavior
  15949. */
  15950. Node.prototype.getBehaviorByName = function (name) {
  15951. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15952. var behavior = _a[_i];
  15953. if (behavior.name === name) {
  15954. return behavior;
  15955. }
  15956. }
  15957. return null;
  15958. };
  15959. /**
  15960. * Returns the world matrix of the node
  15961. * @returns a matrix containing the node's world matrix
  15962. */
  15963. Node.prototype.getWorldMatrix = function () {
  15964. return BABYLON.Matrix.Identity();
  15965. };
  15966. // override it in derived class if you add new variables to the cache
  15967. // and call the parent class method
  15968. /** @ignore */
  15969. Node.prototype._initCache = function () {
  15970. this._cache = {};
  15971. this._cache.parent = undefined;
  15972. };
  15973. /** @ignore */
  15974. Node.prototype.updateCache = function (force) {
  15975. if (!force && this.isSynchronized())
  15976. return;
  15977. this._cache.parent = this.parent;
  15978. this._updateCache();
  15979. };
  15980. // override it in derived class if you add new variables to the cache
  15981. // and call the parent class method if !ignoreParentClass
  15982. /** @ignore */
  15983. Node.prototype._updateCache = function (ignoreParentClass) {
  15984. };
  15985. // override it in derived class if you add new variables to the cache
  15986. /** @ignore */
  15987. Node.prototype._isSynchronized = function () {
  15988. return true;
  15989. };
  15990. /** @ignore */
  15991. Node.prototype._markSyncedWithParent = function () {
  15992. if (this.parent) {
  15993. this._parentRenderId = this.parent._currentRenderId;
  15994. }
  15995. };
  15996. /** @ignore */
  15997. Node.prototype.isSynchronizedWithParent = function () {
  15998. if (!this.parent) {
  15999. return true;
  16000. }
  16001. if (this._parentRenderId !== this.parent._currentRenderId) {
  16002. return false;
  16003. }
  16004. return this.parent.isSynchronized();
  16005. };
  16006. /** @ignore */
  16007. Node.prototype.isSynchronized = function (updateCache) {
  16008. var check = this.hasNewParent();
  16009. check = check || !this.isSynchronizedWithParent();
  16010. check = check || !this._isSynchronized();
  16011. if (updateCache)
  16012. this.updateCache(true);
  16013. return !check;
  16014. };
  16015. /** @ignore */
  16016. Node.prototype.hasNewParent = function (update) {
  16017. if (this._cache.parent === this.parent)
  16018. return false;
  16019. if (update)
  16020. this._cache.parent = this.parent;
  16021. return true;
  16022. };
  16023. /**
  16024. * Is this node ready to be used/rendered
  16025. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  16026. * @return true if the node is ready
  16027. */
  16028. Node.prototype.isReady = function (completeCheck) {
  16029. if (completeCheck === void 0) { completeCheck = false; }
  16030. return this._isReady;
  16031. };
  16032. /**
  16033. * Is this node enabled?
  16034. * 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
  16035. * @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
  16036. * @return whether this node (and its parent) is enabled
  16037. * @see setEnabled
  16038. */
  16039. Node.prototype.isEnabled = function (checkAncestors) {
  16040. if (checkAncestors === void 0) { checkAncestors = true; }
  16041. if (checkAncestors === false) {
  16042. return this._isEnabled;
  16043. }
  16044. if (this._isEnabled === false) {
  16045. return false;
  16046. }
  16047. if (this.parent !== undefined && this.parent !== null) {
  16048. return this.parent.isEnabled(checkAncestors);
  16049. }
  16050. return true;
  16051. };
  16052. /**
  16053. * Set the enabled state of this node
  16054. * @param value defines the new enabled state
  16055. * @see isEnabled
  16056. */
  16057. Node.prototype.setEnabled = function (value) {
  16058. this._isEnabled = value;
  16059. };
  16060. /**
  16061. * Is this node a descendant of the given node?
  16062. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  16063. * @param ancestor defines the parent node to inspect
  16064. * @see parent
  16065. * @returns a boolean indicating if this node is a descendant of the given node
  16066. */
  16067. Node.prototype.isDescendantOf = function (ancestor) {
  16068. if (this.parent) {
  16069. if (this.parent === ancestor) {
  16070. return true;
  16071. }
  16072. return this.parent.isDescendantOf(ancestor);
  16073. }
  16074. return false;
  16075. };
  16076. /** @ignore */
  16077. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  16078. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  16079. if (!this._children) {
  16080. return;
  16081. }
  16082. for (var index = 0; index < this._children.length; index++) {
  16083. var item = this._children[index];
  16084. if (!predicate || predicate(item)) {
  16085. results.push(item);
  16086. }
  16087. if (!directDescendantsOnly) {
  16088. item._getDescendants(results, false, predicate);
  16089. }
  16090. }
  16091. };
  16092. /**
  16093. * Will return all nodes that have this node as ascendant
  16094. * @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
  16095. * @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
  16096. * @return all children nodes of all types
  16097. */
  16098. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  16099. var results = new Array();
  16100. this._getDescendants(results, directDescendantsOnly, predicate);
  16101. return results;
  16102. };
  16103. /**
  16104. * Get all child-meshes of this node
  16105. * @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
  16106. * @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
  16107. * @returns an array of {BABYLON.AbstractMesh}
  16108. */
  16109. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  16110. var results = [];
  16111. this._getDescendants(results, directDescendantsOnly, function (node) {
  16112. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  16113. });
  16114. return results;
  16115. };
  16116. /**
  16117. * Get all child-transformNodes of this node
  16118. * @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
  16119. * @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
  16120. * @returns an array of {BABYLON.TransformNode}
  16121. */
  16122. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  16123. var results = [];
  16124. this._getDescendants(results, directDescendantsOnly, function (node) {
  16125. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  16126. });
  16127. return results;
  16128. };
  16129. /**
  16130. * Get all direct children of this node
  16131. * @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
  16132. * @returns an array of {BABYLON.Node}
  16133. */
  16134. Node.prototype.getChildren = function (predicate) {
  16135. return this.getDescendants(true, predicate);
  16136. };
  16137. /** @ignore */
  16138. Node.prototype._setReady = function (state) {
  16139. if (state === this._isReady) {
  16140. return;
  16141. }
  16142. if (!state) {
  16143. this._isReady = false;
  16144. return;
  16145. }
  16146. if (this.onReady) {
  16147. this.onReady(this);
  16148. }
  16149. this._isReady = true;
  16150. };
  16151. /**
  16152. * Get an animation by name
  16153. * @param name defines the name of the animation to look for
  16154. * @returns null if not found else the requested animation
  16155. */
  16156. Node.prototype.getAnimationByName = function (name) {
  16157. for (var i = 0; i < this.animations.length; i++) {
  16158. var animation = this.animations[i];
  16159. if (animation.name === name) {
  16160. return animation;
  16161. }
  16162. }
  16163. return null;
  16164. };
  16165. /**
  16166. * Creates an animation range for this node
  16167. * @param name defines the name of the range
  16168. * @param from defines the starting key
  16169. * @param to defines the end key
  16170. */
  16171. Node.prototype.createAnimationRange = function (name, from, to) {
  16172. // check name not already in use
  16173. if (!this._ranges[name]) {
  16174. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  16175. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16176. if (this.animations[i]) {
  16177. this.animations[i].createRange(name, from, to);
  16178. }
  16179. }
  16180. }
  16181. };
  16182. /**
  16183. * Delete a specific animation range
  16184. * @param name defines the name of the range to delete
  16185. * @param deleteFrames defines if animation frames from the range must be deleted as well
  16186. */
  16187. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  16188. if (deleteFrames === void 0) { deleteFrames = true; }
  16189. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16190. if (this.animations[i]) {
  16191. this.animations[i].deleteRange(name, deleteFrames);
  16192. }
  16193. }
  16194. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  16195. };
  16196. /**
  16197. * Get an animation range by name
  16198. * @param name defines the name of the animation range to look for
  16199. * @returns null if not found else the requested animation range
  16200. */
  16201. Node.prototype.getAnimationRange = function (name) {
  16202. return this._ranges[name];
  16203. };
  16204. /**
  16205. * Will start the animation sequence
  16206. * @param name defines the range frames for animation sequence
  16207. * @param loop defines if the animation should loop (false by default)
  16208. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  16209. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  16210. * @returns the object created for this animation. If range does not exist, it will return null
  16211. */
  16212. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  16213. var range = this.getAnimationRange(name);
  16214. if (!range) {
  16215. return null;
  16216. }
  16217. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  16218. };
  16219. /**
  16220. * Serialize animation ranges into a JSON compatible object
  16221. * @returns serialization object
  16222. */
  16223. Node.prototype.serializeAnimationRanges = function () {
  16224. var serializationRanges = [];
  16225. for (var name in this._ranges) {
  16226. var localRange = this._ranges[name];
  16227. if (!localRange) {
  16228. continue;
  16229. }
  16230. var range = {};
  16231. range.name = name;
  16232. range.from = localRange.from;
  16233. range.to = localRange.to;
  16234. serializationRanges.push(range);
  16235. }
  16236. return serializationRanges;
  16237. };
  16238. /**
  16239. * Computes the world matrix of the node
  16240. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  16241. * @returns the world matrix
  16242. */
  16243. Node.prototype.computeWorldMatrix = function (force) {
  16244. return BABYLON.Matrix.Identity();
  16245. };
  16246. /**
  16247. * Releases resources associated with this node.
  16248. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  16249. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  16250. */
  16251. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16252. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16253. if (!doNotRecurse) {
  16254. var nodes = this.getDescendants(true);
  16255. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  16256. var node = nodes_1[_i];
  16257. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  16258. }
  16259. }
  16260. else {
  16261. var transformNodes = this.getChildTransformNodes(true);
  16262. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  16263. var transformNode = transformNodes_1[_a];
  16264. transformNode.parent = null;
  16265. transformNode.computeWorldMatrix(true);
  16266. }
  16267. }
  16268. this.parent = null;
  16269. // Callback
  16270. this.onDisposeObservable.notifyObservers(this);
  16271. this.onDisposeObservable.clear();
  16272. // Behaviors
  16273. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  16274. var behavior = _c[_b];
  16275. behavior.detach();
  16276. }
  16277. this._behaviors = [];
  16278. this._isDisposed = true;
  16279. };
  16280. /**
  16281. * Parse animation range data from a serialization object and store them into a given node
  16282. * @param node defines where to store the animation ranges
  16283. * @param parsedNode defines the serialization object to read data from
  16284. * @param scene defines the hosting scene
  16285. */
  16286. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  16287. if (parsedNode.ranges) {
  16288. for (var index = 0; index < parsedNode.ranges.length; index++) {
  16289. var data = parsedNode.ranges[index];
  16290. node.createAnimationRange(data.name, data.from, data.to);
  16291. }
  16292. }
  16293. };
  16294. __decorate([
  16295. BABYLON.serialize()
  16296. ], Node.prototype, "name", void 0);
  16297. __decorate([
  16298. BABYLON.serialize()
  16299. ], Node.prototype, "id", void 0);
  16300. __decorate([
  16301. BABYLON.serialize()
  16302. ], Node.prototype, "uniqueId", void 0);
  16303. __decorate([
  16304. BABYLON.serialize()
  16305. ], Node.prototype, "state", void 0);
  16306. __decorate([
  16307. BABYLON.serialize()
  16308. ], Node.prototype, "metadata", void 0);
  16309. return Node;
  16310. }());
  16311. BABYLON.Node = Node;
  16312. })(BABYLON || (BABYLON = {}));
  16313. //# sourceMappingURL=babylon.node.js.map
  16314. "use strict";
  16315. var BABYLON;
  16316. (function (BABYLON) {
  16317. var BoundingSphere = /** @class */ (function () {
  16318. function BoundingSphere(minimum, maximum) {
  16319. this.minimum = minimum;
  16320. this.maximum = maximum;
  16321. this._tempRadiusVector = BABYLON.Vector3.Zero();
  16322. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  16323. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  16324. this.radius = distance * 0.5;
  16325. this.centerWorld = BABYLON.Vector3.Zero();
  16326. this._update(BABYLON.Matrix.Identity());
  16327. }
  16328. // Methods
  16329. BoundingSphere.prototype._update = function (world) {
  16330. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  16331. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  16332. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  16333. };
  16334. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  16335. for (var i = 0; i < 6; i++) {
  16336. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  16337. return false;
  16338. }
  16339. return true;
  16340. };
  16341. BoundingSphere.prototype.intersectsPoint = function (point) {
  16342. var x = this.centerWorld.x - point.x;
  16343. var y = this.centerWorld.y - point.y;
  16344. var z = this.centerWorld.z - point.z;
  16345. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16346. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  16347. return false;
  16348. return true;
  16349. };
  16350. // Statics
  16351. BoundingSphere.Intersects = function (sphere0, sphere1) {
  16352. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  16353. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  16354. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  16355. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16356. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  16357. return false;
  16358. return true;
  16359. };
  16360. return BoundingSphere;
  16361. }());
  16362. BABYLON.BoundingSphere = BoundingSphere;
  16363. })(BABYLON || (BABYLON = {}));
  16364. //# sourceMappingURL=babylon.boundingSphere.js.map
  16365. "use strict";
  16366. var BABYLON;
  16367. (function (BABYLON) {
  16368. var BoundingBox = /** @class */ (function () {
  16369. function BoundingBox(minimum, maximum) {
  16370. this.minimum = minimum;
  16371. this.maximum = maximum;
  16372. this.vectors = new Array();
  16373. this.vectorsWorld = new Array();
  16374. // Bounding vectors
  16375. this.vectors.push(this.minimum.clone());
  16376. this.vectors.push(this.maximum.clone());
  16377. this.vectors.push(this.minimum.clone());
  16378. this.vectors[2].x = this.maximum.x;
  16379. this.vectors.push(this.minimum.clone());
  16380. this.vectors[3].y = this.maximum.y;
  16381. this.vectors.push(this.minimum.clone());
  16382. this.vectors[4].z = this.maximum.z;
  16383. this.vectors.push(this.maximum.clone());
  16384. this.vectors[5].z = this.minimum.z;
  16385. this.vectors.push(this.maximum.clone());
  16386. this.vectors[6].x = this.minimum.x;
  16387. this.vectors.push(this.maximum.clone());
  16388. this.vectors[7].y = this.minimum.y;
  16389. // OBB
  16390. this.center = this.maximum.add(this.minimum).scale(0.5);
  16391. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  16392. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  16393. // World
  16394. for (var index = 0; index < this.vectors.length; index++) {
  16395. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  16396. }
  16397. this.minimumWorld = BABYLON.Vector3.Zero();
  16398. this.maximumWorld = BABYLON.Vector3.Zero();
  16399. this.centerWorld = BABYLON.Vector3.Zero();
  16400. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16401. this._update(BABYLON.Matrix.Identity());
  16402. }
  16403. // Methods
  16404. BoundingBox.prototype.getWorldMatrix = function () {
  16405. return this._worldMatrix;
  16406. };
  16407. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16408. this._worldMatrix.copyFrom(matrix);
  16409. return this;
  16410. };
  16411. BoundingBox.prototype._update = function (world) {
  16412. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16413. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16414. for (var index = 0; index < this.vectors.length; index++) {
  16415. var v = this.vectorsWorld[index];
  16416. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16417. if (v.x < this.minimumWorld.x)
  16418. this.minimumWorld.x = v.x;
  16419. if (v.y < this.minimumWorld.y)
  16420. this.minimumWorld.y = v.y;
  16421. if (v.z < this.minimumWorld.z)
  16422. this.minimumWorld.z = v.z;
  16423. if (v.x > this.maximumWorld.x)
  16424. this.maximumWorld.x = v.x;
  16425. if (v.y > this.maximumWorld.y)
  16426. this.maximumWorld.y = v.y;
  16427. if (v.z > this.maximumWorld.z)
  16428. this.maximumWorld.z = v.z;
  16429. }
  16430. // Extend
  16431. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16432. this.extendSizeWorld.scaleInPlace(0.5);
  16433. // OBB
  16434. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16435. this.centerWorld.scaleInPlace(0.5);
  16436. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16437. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16438. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16439. this._worldMatrix = world;
  16440. };
  16441. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16442. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16443. };
  16444. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16445. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16446. };
  16447. BoundingBox.prototype.intersectsPoint = function (point) {
  16448. var delta = -BABYLON.Epsilon;
  16449. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16450. return false;
  16451. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16452. return false;
  16453. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16454. return false;
  16455. return true;
  16456. };
  16457. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16458. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16459. };
  16460. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16461. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16462. return false;
  16463. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16464. return false;
  16465. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16466. return false;
  16467. return true;
  16468. };
  16469. // Statics
  16470. BoundingBox.Intersects = function (box0, box1) {
  16471. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16472. return false;
  16473. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16474. return false;
  16475. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16476. return false;
  16477. return true;
  16478. };
  16479. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16480. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16481. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16482. return (num <= (sphereRadius * sphereRadius));
  16483. };
  16484. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16485. for (var p = 0; p < 6; p++) {
  16486. for (var i = 0; i < 8; i++) {
  16487. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16488. return false;
  16489. }
  16490. }
  16491. }
  16492. return true;
  16493. };
  16494. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16495. for (var p = 0; p < 6; p++) {
  16496. var inCount = 8;
  16497. for (var i = 0; i < 8; i++) {
  16498. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16499. --inCount;
  16500. }
  16501. else {
  16502. break;
  16503. }
  16504. }
  16505. if (inCount === 0)
  16506. return false;
  16507. }
  16508. return true;
  16509. };
  16510. return BoundingBox;
  16511. }());
  16512. BABYLON.BoundingBox = BoundingBox;
  16513. })(BABYLON || (BABYLON = {}));
  16514. //# sourceMappingURL=babylon.boundingBox.js.map
  16515. "use strict";
  16516. var BABYLON;
  16517. (function (BABYLON) {
  16518. var computeBoxExtents = function (axis, box) {
  16519. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16520. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16521. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16522. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16523. var r = r0 + r1 + r2;
  16524. return {
  16525. min: p - r,
  16526. max: p + r
  16527. };
  16528. };
  16529. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16530. var axisOverlap = function (axis, box0, box1) {
  16531. var result0 = computeBoxExtents(axis, box0);
  16532. var result1 = computeBoxExtents(axis, box1);
  16533. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16534. };
  16535. var BoundingInfo = /** @class */ (function () {
  16536. function BoundingInfo(minimum, maximum) {
  16537. this.minimum = minimum;
  16538. this.maximum = maximum;
  16539. this._isLocked = false;
  16540. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16541. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16542. }
  16543. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16544. get: function () {
  16545. return this._isLocked;
  16546. },
  16547. set: function (value) {
  16548. this._isLocked = value;
  16549. },
  16550. enumerable: true,
  16551. configurable: true
  16552. });
  16553. // Methods
  16554. BoundingInfo.prototype.update = function (world) {
  16555. if (this._isLocked) {
  16556. return;
  16557. }
  16558. this.boundingBox._update(world);
  16559. this.boundingSphere._update(world);
  16560. };
  16561. /**
  16562. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16563. * @param center New center of the bounding info
  16564. * @param extend New extend of the bounding info
  16565. */
  16566. BoundingInfo.prototype.centerOn = function (center, extend) {
  16567. this.minimum = center.subtract(extend);
  16568. this.maximum = center.add(extend);
  16569. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16570. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16571. return this;
  16572. };
  16573. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16574. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16575. return false;
  16576. return this.boundingBox.isInFrustum(frustumPlanes);
  16577. };
  16578. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16579. /**
  16580. * Gets the world distance between the min and max points of the bounding box
  16581. */
  16582. get: function () {
  16583. var boundingBox = this.boundingBox;
  16584. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16585. return size.length();
  16586. },
  16587. enumerable: true,
  16588. configurable: true
  16589. });
  16590. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16591. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16592. };
  16593. BoundingInfo.prototype._checkCollision = function (collider) {
  16594. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16595. };
  16596. BoundingInfo.prototype.intersectsPoint = function (point) {
  16597. if (!this.boundingSphere.centerWorld) {
  16598. return false;
  16599. }
  16600. if (!this.boundingSphere.intersectsPoint(point)) {
  16601. return false;
  16602. }
  16603. if (!this.boundingBox.intersectsPoint(point)) {
  16604. return false;
  16605. }
  16606. return true;
  16607. };
  16608. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16609. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16610. return false;
  16611. }
  16612. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16613. return false;
  16614. }
  16615. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16616. return false;
  16617. }
  16618. if (!precise) {
  16619. return true;
  16620. }
  16621. var box0 = this.boundingBox;
  16622. var box1 = boundingInfo.boundingBox;
  16623. if (!axisOverlap(box0.directions[0], box0, box1))
  16624. return false;
  16625. if (!axisOverlap(box0.directions[1], box0, box1))
  16626. return false;
  16627. if (!axisOverlap(box0.directions[2], box0, box1))
  16628. return false;
  16629. if (!axisOverlap(box1.directions[0], box0, box1))
  16630. return false;
  16631. if (!axisOverlap(box1.directions[1], box0, box1))
  16632. return false;
  16633. if (!axisOverlap(box1.directions[2], box0, box1))
  16634. return false;
  16635. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16636. return false;
  16637. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16638. return false;
  16639. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16640. return false;
  16641. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16642. return false;
  16643. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16644. return false;
  16645. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16646. return false;
  16647. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16648. return false;
  16649. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16650. return false;
  16651. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16652. return false;
  16653. return true;
  16654. };
  16655. return BoundingInfo;
  16656. }());
  16657. BABYLON.BoundingInfo = BoundingInfo;
  16658. })(BABYLON || (BABYLON = {}));
  16659. //# sourceMappingURL=babylon.boundingInfo.js.map
  16660. "use strict";
  16661. var BABYLON;
  16662. (function (BABYLON) {
  16663. var TransformNode = /** @class */ (function (_super) {
  16664. __extends(TransformNode, _super);
  16665. function TransformNode(name, scene, isPure) {
  16666. if (scene === void 0) { scene = null; }
  16667. if (isPure === void 0) { isPure = true; }
  16668. var _this = _super.call(this, name, scene) || this;
  16669. // Properties
  16670. _this._rotation = BABYLON.Vector3.Zero();
  16671. _this._scaling = BABYLON.Vector3.One();
  16672. _this._isDirty = false;
  16673. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  16674. _this.scalingDeterminant = 1;
  16675. _this.infiniteDistance = false;
  16676. _this.position = BABYLON.Vector3.Zero();
  16677. _this._localWorld = BABYLON.Matrix.Zero();
  16678. _this._worldMatrix = BABYLON.Matrix.Zero();
  16679. _this._worldMatrixDeterminant = 0;
  16680. _this._absolutePosition = BABYLON.Vector3.Zero();
  16681. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16682. _this._postMultiplyPivotMatrix = false;
  16683. _this._isWorldMatrixFrozen = false;
  16684. /**
  16685. * An event triggered after the world matrix is updated
  16686. * @type {BABYLON.Observable}
  16687. */
  16688. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16689. _this._nonUniformScaling = false;
  16690. if (isPure) {
  16691. _this.getScene().addTransformNode(_this);
  16692. }
  16693. return _this;
  16694. }
  16695. /**
  16696. * Gets a string idenfifying the name of the class
  16697. * @returns "TransformNode" string
  16698. */
  16699. TransformNode.prototype.getClassName = function () {
  16700. return "TransformNode";
  16701. };
  16702. Object.defineProperty(TransformNode.prototype, "rotation", {
  16703. /**
  16704. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16705. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16706. * Default : (0.0, 0.0, 0.0)
  16707. */
  16708. get: function () {
  16709. return this._rotation;
  16710. },
  16711. set: function (newRotation) {
  16712. this._rotation = newRotation;
  16713. },
  16714. enumerable: true,
  16715. configurable: true
  16716. });
  16717. Object.defineProperty(TransformNode.prototype, "scaling", {
  16718. /**
  16719. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16720. * Default : (1.0, 1.0, 1.0)
  16721. */
  16722. get: function () {
  16723. return this._scaling;
  16724. },
  16725. /**
  16726. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16727. * Default : (1.0, 1.0, 1.0)
  16728. */
  16729. set: function (newScaling) {
  16730. this._scaling = newScaling;
  16731. },
  16732. enumerable: true,
  16733. configurable: true
  16734. });
  16735. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16736. /**
  16737. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16738. * It's null by default.
  16739. * 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)
  16740. */
  16741. get: function () {
  16742. return this._rotationQuaternion;
  16743. },
  16744. set: function (quaternion) {
  16745. this._rotationQuaternion = quaternion;
  16746. //reset the rotation vector.
  16747. if (quaternion && this.rotation.length()) {
  16748. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16749. }
  16750. },
  16751. enumerable: true,
  16752. configurable: true
  16753. });
  16754. /**
  16755. * Returns the latest update of the World matrix
  16756. * Returns a Matrix.
  16757. */
  16758. TransformNode.prototype.getWorldMatrix = function () {
  16759. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16760. this.computeWorldMatrix();
  16761. }
  16762. return this._worldMatrix;
  16763. };
  16764. /**
  16765. * Returns the latest update of the World matrix determinant.
  16766. */
  16767. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16768. return this._worldMatrixDeterminant;
  16769. };
  16770. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16771. /**
  16772. * Returns directly the latest state of the mesh World matrix.
  16773. * A Matrix is returned.
  16774. */
  16775. get: function () {
  16776. return this._worldMatrix;
  16777. },
  16778. enumerable: true,
  16779. configurable: true
  16780. });
  16781. /**
  16782. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16783. * Returns the AbstractMesh.
  16784. */
  16785. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16786. this._poseMatrix.copyFrom(matrix);
  16787. return this;
  16788. };
  16789. /**
  16790. * Returns the mesh Pose matrix.
  16791. * Returned object : Matrix
  16792. */
  16793. TransformNode.prototype.getPoseMatrix = function () {
  16794. return this._poseMatrix;
  16795. };
  16796. TransformNode.prototype._isSynchronized = function () {
  16797. if (this._isDirty) {
  16798. return false;
  16799. }
  16800. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16801. return false;
  16802. if (this._cache.pivotMatrixUpdated) {
  16803. return false;
  16804. }
  16805. if (this.infiniteDistance) {
  16806. return false;
  16807. }
  16808. if (!this._cache.position.equals(this.position))
  16809. return false;
  16810. if (this.rotationQuaternion) {
  16811. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16812. return false;
  16813. }
  16814. if (!this._cache.rotation.equals(this.rotation))
  16815. return false;
  16816. if (!this._cache.scaling.equals(this.scaling))
  16817. return false;
  16818. return true;
  16819. };
  16820. TransformNode.prototype._initCache = function () {
  16821. _super.prototype._initCache.call(this);
  16822. this._cache.localMatrixUpdated = false;
  16823. this._cache.position = BABYLON.Vector3.Zero();
  16824. this._cache.scaling = BABYLON.Vector3.Zero();
  16825. this._cache.rotation = BABYLON.Vector3.Zero();
  16826. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16827. this._cache.billboardMode = -1;
  16828. };
  16829. TransformNode.prototype.markAsDirty = function (property) {
  16830. if (property === "rotation") {
  16831. this.rotationQuaternion = null;
  16832. }
  16833. this._currentRenderId = Number.MAX_VALUE;
  16834. this._isDirty = true;
  16835. return this;
  16836. };
  16837. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16838. /**
  16839. * Returns the current mesh absolute position.
  16840. * Retuns a Vector3.
  16841. */
  16842. get: function () {
  16843. return this._absolutePosition;
  16844. },
  16845. enumerable: true,
  16846. configurable: true
  16847. });
  16848. /**
  16849. * Sets a new matrix to apply before all other transformation
  16850. * @param matrix defines the transform matrix
  16851. * @returns the current TransformNode
  16852. */
  16853. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16854. return this.setPivotMatrix(matrix, false);
  16855. };
  16856. /**
  16857. * Sets a new pivot matrix to the current node
  16858. * @param matrix defines the new pivot matrix to use
  16859. * @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
  16860. * @returns the current TransformNode
  16861. */
  16862. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16863. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16864. this._pivotMatrix = matrix.clone();
  16865. this._cache.pivotMatrixUpdated = true;
  16866. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16867. if (this._postMultiplyPivotMatrix) {
  16868. if (!this._pivotMatrixInverse) {
  16869. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16870. }
  16871. else {
  16872. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16873. }
  16874. }
  16875. return this;
  16876. };
  16877. /**
  16878. * Returns the mesh pivot matrix.
  16879. * Default : Identity.
  16880. * A Matrix is returned.
  16881. */
  16882. TransformNode.prototype.getPivotMatrix = function () {
  16883. return this._pivotMatrix;
  16884. };
  16885. /**
  16886. * Prevents the World matrix to be computed any longer.
  16887. * Returns the AbstractMesh.
  16888. */
  16889. TransformNode.prototype.freezeWorldMatrix = function () {
  16890. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16891. this.computeWorldMatrix(true);
  16892. this._isWorldMatrixFrozen = true;
  16893. return this;
  16894. };
  16895. /**
  16896. * Allows back the World matrix computation.
  16897. * Returns the AbstractMesh.
  16898. */
  16899. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16900. this._isWorldMatrixFrozen = false;
  16901. this.computeWorldMatrix(true);
  16902. return this;
  16903. };
  16904. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16905. /**
  16906. * True if the World matrix has been frozen.
  16907. * Returns a boolean.
  16908. */
  16909. get: function () {
  16910. return this._isWorldMatrixFrozen;
  16911. },
  16912. enumerable: true,
  16913. configurable: true
  16914. });
  16915. /**
  16916. * Retuns the mesh absolute position in the World.
  16917. * Returns a Vector3.
  16918. */
  16919. TransformNode.prototype.getAbsolutePosition = function () {
  16920. this.computeWorldMatrix();
  16921. return this._absolutePosition;
  16922. };
  16923. /**
  16924. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16925. * Returns the AbstractMesh.
  16926. */
  16927. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16928. if (!absolutePosition) {
  16929. return this;
  16930. }
  16931. var absolutePositionX;
  16932. var absolutePositionY;
  16933. var absolutePositionZ;
  16934. if (absolutePosition.x === undefined) {
  16935. if (arguments.length < 3) {
  16936. return this;
  16937. }
  16938. absolutePositionX = arguments[0];
  16939. absolutePositionY = arguments[1];
  16940. absolutePositionZ = arguments[2];
  16941. }
  16942. else {
  16943. absolutePositionX = absolutePosition.x;
  16944. absolutePositionY = absolutePosition.y;
  16945. absolutePositionZ = absolutePosition.z;
  16946. }
  16947. if (this.parent) {
  16948. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16949. invertParentWorldMatrix.invert();
  16950. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16951. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16952. }
  16953. else {
  16954. this.position.x = absolutePositionX;
  16955. this.position.y = absolutePositionY;
  16956. this.position.z = absolutePositionZ;
  16957. }
  16958. return this;
  16959. };
  16960. /**
  16961. * Sets the mesh position in its local space.
  16962. * Returns the AbstractMesh.
  16963. */
  16964. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16965. this.computeWorldMatrix();
  16966. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16967. return this;
  16968. };
  16969. /**
  16970. * Returns the mesh position in the local space from the current World matrix values.
  16971. * Returns a new Vector3.
  16972. */
  16973. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16974. this.computeWorldMatrix();
  16975. var invLocalWorldMatrix = this._localWorld.clone();
  16976. invLocalWorldMatrix.invert();
  16977. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16978. };
  16979. /**
  16980. * Translates the mesh along the passed Vector3 in its local space.
  16981. * Returns the AbstractMesh.
  16982. */
  16983. TransformNode.prototype.locallyTranslate = function (vector3) {
  16984. this.computeWorldMatrix(true);
  16985. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16986. return this;
  16987. };
  16988. /**
  16989. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16990. * @param targetPoint the position (must be in same space as current mesh) to look at
  16991. * @param yawCor optional yaw (y-axis) correction in radians
  16992. * @param pitchCor optional pitch (x-axis) correction in radians
  16993. * @param rollCor optional roll (z-axis) correction in radians
  16994. * @param space the choosen space of the target
  16995. * @returns the TransformNode.
  16996. */
  16997. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16998. if (yawCor === void 0) { yawCor = 0; }
  16999. if (pitchCor === void 0) { pitchCor = 0; }
  17000. if (rollCor === void 0) { rollCor = 0; }
  17001. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  17002. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  17003. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  17004. targetPoint.subtractToRef(pos, dv);
  17005. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  17006. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  17007. var pitch = Math.atan2(dv.y, len);
  17008. if (this.rotationQuaternion) {
  17009. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  17010. }
  17011. else {
  17012. this.rotation.x = pitch + pitchCor;
  17013. this.rotation.y = yaw + yawCor;
  17014. this.rotation.z = rollCor;
  17015. }
  17016. return this;
  17017. };
  17018. /**
  17019. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  17020. * This Vector3 is expressed in the World space.
  17021. */
  17022. TransformNode.prototype.getDirection = function (localAxis) {
  17023. var result = BABYLON.Vector3.Zero();
  17024. this.getDirectionToRef(localAxis, result);
  17025. return result;
  17026. };
  17027. /**
  17028. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  17029. * localAxis is expressed in the mesh local space.
  17030. * result is computed in the Wordl space from the mesh World matrix.
  17031. * Returns the AbstractMesh.
  17032. */
  17033. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  17034. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  17035. return this;
  17036. };
  17037. /**
  17038. * Sets a new pivot point to the current node
  17039. * @param point defines the new pivot point to use
  17040. * @param space defines if the point is in world or local space (local by default)
  17041. * @returns the current TransformNode
  17042. */
  17043. TransformNode.prototype.setPivotPoint = function (point, space) {
  17044. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  17045. if (this.getScene().getRenderId() == 0) {
  17046. this.computeWorldMatrix(true);
  17047. }
  17048. var wm = this.getWorldMatrix();
  17049. if (space == BABYLON.Space.WORLD) {
  17050. var tmat = BABYLON.Tmp.Matrix[0];
  17051. wm.invertToRef(tmat);
  17052. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  17053. }
  17054. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  17055. };
  17056. /**
  17057. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  17058. */
  17059. TransformNode.prototype.getPivotPoint = function () {
  17060. var point = BABYLON.Vector3.Zero();
  17061. this.getPivotPointToRef(point);
  17062. return point;
  17063. };
  17064. /**
  17065. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  17066. * Returns the AbstractMesh.
  17067. */
  17068. TransformNode.prototype.getPivotPointToRef = function (result) {
  17069. result.x = -this._pivotMatrix.m[12];
  17070. result.y = -this._pivotMatrix.m[13];
  17071. result.z = -this._pivotMatrix.m[14];
  17072. return this;
  17073. };
  17074. /**
  17075. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  17076. */
  17077. TransformNode.prototype.getAbsolutePivotPoint = function () {
  17078. var point = BABYLON.Vector3.Zero();
  17079. this.getAbsolutePivotPointToRef(point);
  17080. return point;
  17081. };
  17082. /**
  17083. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  17084. * Returns the AbstractMesh.
  17085. */
  17086. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  17087. result.x = this._pivotMatrix.m[12];
  17088. result.y = this._pivotMatrix.m[13];
  17089. result.z = this._pivotMatrix.m[14];
  17090. this.getPivotPointToRef(result);
  17091. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  17092. return this;
  17093. };
  17094. /**
  17095. * Defines the passed node as the parent of the current node.
  17096. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  17097. * Returns the TransformNode.
  17098. */
  17099. TransformNode.prototype.setParent = function (node) {
  17100. if (node === null) {
  17101. var rotation = BABYLON.Tmp.Quaternion[0];
  17102. var position = BABYLON.Tmp.Vector3[0];
  17103. var scale = BABYLON.Tmp.Vector3[1];
  17104. if (this.parent && this.parent.computeWorldMatrix) {
  17105. this.parent.computeWorldMatrix(true);
  17106. }
  17107. this.computeWorldMatrix(true);
  17108. this.getWorldMatrix().decompose(scale, rotation, position);
  17109. if (this.rotationQuaternion) {
  17110. this.rotationQuaternion.copyFrom(rotation);
  17111. }
  17112. else {
  17113. rotation.toEulerAnglesToRef(this.rotation);
  17114. }
  17115. this.scaling.x = scale.x;
  17116. this.scaling.y = scale.y;
  17117. this.scaling.z = scale.z;
  17118. this.position.x = position.x;
  17119. this.position.y = position.y;
  17120. this.position.z = position.z;
  17121. }
  17122. else {
  17123. var rotation = BABYLON.Tmp.Quaternion[0];
  17124. var position = BABYLON.Tmp.Vector3[0];
  17125. var scale = BABYLON.Tmp.Vector3[1];
  17126. var diffMatrix = BABYLON.Tmp.Matrix[0];
  17127. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  17128. this.computeWorldMatrix(true);
  17129. node.computeWorldMatrix(true);
  17130. node.getWorldMatrix().invertToRef(invParentMatrix);
  17131. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  17132. diffMatrix.decompose(scale, rotation, position);
  17133. if (this.rotationQuaternion) {
  17134. this.rotationQuaternion.copyFrom(rotation);
  17135. }
  17136. else {
  17137. rotation.toEulerAnglesToRef(this.rotation);
  17138. }
  17139. this.position.x = position.x;
  17140. this.position.y = position.y;
  17141. this.position.z = position.z;
  17142. this.scaling.x = scale.x;
  17143. this.scaling.y = scale.y;
  17144. this.scaling.z = scale.z;
  17145. }
  17146. this.parent = node;
  17147. return this;
  17148. };
  17149. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  17150. get: function () {
  17151. return this._nonUniformScaling;
  17152. },
  17153. enumerable: true,
  17154. configurable: true
  17155. });
  17156. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  17157. if (this._nonUniformScaling === value) {
  17158. return false;
  17159. }
  17160. this._nonUniformScaling = true;
  17161. return true;
  17162. };
  17163. /**
  17164. * Attach the current TransformNode to another TransformNode associated with a bone
  17165. * @param bone Bone affecting the TransformNode
  17166. * @param affectedTransformNode TransformNode associated with the bone
  17167. */
  17168. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  17169. this._transformToBoneReferal = affectedTransformNode;
  17170. this.parent = bone;
  17171. if (bone.getWorldMatrix().determinant() < 0) {
  17172. this.scalingDeterminant *= -1;
  17173. }
  17174. return this;
  17175. };
  17176. TransformNode.prototype.detachFromBone = function () {
  17177. if (!this.parent) {
  17178. return this;
  17179. }
  17180. if (this.parent.getWorldMatrix().determinant() < 0) {
  17181. this.scalingDeterminant *= -1;
  17182. }
  17183. this._transformToBoneReferal = null;
  17184. this.parent = null;
  17185. return this;
  17186. };
  17187. /**
  17188. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  17189. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17190. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17191. * The passed axis is also normalized.
  17192. * Returns the AbstractMesh.
  17193. */
  17194. TransformNode.prototype.rotate = function (axis, amount, space) {
  17195. axis.normalize();
  17196. if (!this.rotationQuaternion) {
  17197. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17198. this.rotation = BABYLON.Vector3.Zero();
  17199. }
  17200. var rotationQuaternion;
  17201. if (!space || space === BABYLON.Space.LOCAL) {
  17202. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  17203. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  17204. }
  17205. else {
  17206. if (this.parent) {
  17207. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  17208. invertParentWorldMatrix.invert();
  17209. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  17210. }
  17211. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  17212. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17213. }
  17214. return this;
  17215. };
  17216. /**
  17217. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  17218. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17219. * The passed axis is also normalized.
  17220. * Returns the AbstractMesh.
  17221. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  17222. */
  17223. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  17224. axis.normalize();
  17225. if (!this.rotationQuaternion) {
  17226. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17227. this.rotation.copyFromFloats(0, 0, 0);
  17228. }
  17229. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  17230. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  17231. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  17232. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  17233. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  17234. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  17235. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  17236. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  17237. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17238. return this;
  17239. };
  17240. /**
  17241. * Translates the mesh along the axis vector for the passed distance in the given space.
  17242. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17243. * Returns the AbstractMesh.
  17244. */
  17245. TransformNode.prototype.translate = function (axis, distance, space) {
  17246. var displacementVector = axis.scale(distance);
  17247. if (!space || space === BABYLON.Space.LOCAL) {
  17248. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  17249. this.setPositionWithLocalVector(tempV3);
  17250. }
  17251. else {
  17252. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  17253. }
  17254. return this;
  17255. };
  17256. /**
  17257. * Adds a rotation step to the mesh current rotation.
  17258. * x, y, z are Euler angles expressed in radians.
  17259. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  17260. * This means this rotation is made in the mesh local space only.
  17261. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  17262. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  17263. * ```javascript
  17264. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  17265. * ```
  17266. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  17267. * 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.
  17268. * Returns the AbstractMesh.
  17269. */
  17270. TransformNode.prototype.addRotation = function (x, y, z) {
  17271. var rotationQuaternion;
  17272. if (this.rotationQuaternion) {
  17273. rotationQuaternion = this.rotationQuaternion;
  17274. }
  17275. else {
  17276. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  17277. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  17278. }
  17279. var accumulation = BABYLON.Tmp.Quaternion[0];
  17280. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  17281. rotationQuaternion.multiplyInPlace(accumulation);
  17282. if (!this.rotationQuaternion) {
  17283. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  17284. }
  17285. return this;
  17286. };
  17287. /**
  17288. * Computes the mesh World matrix and returns it.
  17289. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  17290. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  17291. * If the parameter `force`is set to `true`, the actual computation is done.
  17292. * Returns the mesh World Matrix.
  17293. */
  17294. TransformNode.prototype.computeWorldMatrix = function (force) {
  17295. if (this._isWorldMatrixFrozen) {
  17296. return this._worldMatrix;
  17297. }
  17298. if (!force && this.isSynchronized(true)) {
  17299. return this._worldMatrix;
  17300. }
  17301. this._cache.position.copyFrom(this.position);
  17302. this._cache.scaling.copyFrom(this.scaling);
  17303. this._cache.pivotMatrixUpdated = false;
  17304. this._cache.billboardMode = this.billboardMode;
  17305. this._currentRenderId = this.getScene().getRenderId();
  17306. this._isDirty = false;
  17307. // Scaling
  17308. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  17309. // Rotation
  17310. //rotate, if quaternion is set and rotation was used
  17311. if (this.rotationQuaternion) {
  17312. var len = this.rotation.length();
  17313. if (len) {
  17314. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  17315. this.rotation.copyFromFloats(0, 0, 0);
  17316. }
  17317. }
  17318. if (this.rotationQuaternion) {
  17319. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  17320. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17321. }
  17322. else {
  17323. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  17324. this._cache.rotation.copyFrom(this.rotation);
  17325. }
  17326. // Translation
  17327. var camera = this.getScene().activeCamera;
  17328. if (this.infiniteDistance && !this.parent && camera) {
  17329. var cameraWorldMatrix = camera.getWorldMatrix();
  17330. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  17331. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  17332. }
  17333. else {
  17334. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  17335. }
  17336. // Composing transformations
  17337. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  17338. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17339. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  17340. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  17341. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  17342. // Need to decompose each rotation here
  17343. var currentPosition = BABYLON.Tmp.Vector3[3];
  17344. if (this.parent && this.parent.getWorldMatrix) {
  17345. if (this._transformToBoneReferal) {
  17346. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17347. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  17348. }
  17349. else {
  17350. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  17351. }
  17352. }
  17353. else {
  17354. currentPosition.copyFrom(this.position);
  17355. }
  17356. currentPosition.subtractInPlace(camera.globalPosition);
  17357. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  17358. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  17359. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  17360. }
  17361. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  17362. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  17363. }
  17364. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  17365. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  17366. }
  17367. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  17368. }
  17369. else {
  17370. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  17371. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  17372. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  17373. }
  17374. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  17375. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17376. }
  17377. // Local world
  17378. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  17379. // Parent
  17380. if (this.parent && this.parent.getWorldMatrix) {
  17381. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  17382. if (this._transformToBoneReferal) {
  17383. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17384. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  17385. }
  17386. else {
  17387. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  17388. }
  17389. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  17390. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  17391. this._worldMatrix.copyFrom(this._localWorld);
  17392. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  17393. }
  17394. else {
  17395. if (this._transformToBoneReferal) {
  17396. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17397. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  17398. }
  17399. else {
  17400. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  17401. }
  17402. }
  17403. this._markSyncedWithParent();
  17404. }
  17405. else {
  17406. this._worldMatrix.copyFrom(this._localWorld);
  17407. }
  17408. // Post multiply inverse of pivotMatrix
  17409. if (this._postMultiplyPivotMatrix) {
  17410. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17411. }
  17412. // Normal matrix
  17413. if (this.scaling.isNonUniform) {
  17414. this._updateNonUniformScalingState(true);
  17415. }
  17416. else if (this.parent && this.parent._nonUniformScaling) {
  17417. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17418. }
  17419. else {
  17420. this._updateNonUniformScalingState(false);
  17421. }
  17422. this._afterComputeWorldMatrix();
  17423. // Absolute position
  17424. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17425. // Callbacks
  17426. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17427. if (!this._poseMatrix) {
  17428. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17429. }
  17430. // Cache the determinant
  17431. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17432. return this._worldMatrix;
  17433. };
  17434. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17435. };
  17436. /**
  17437. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17438. * @param func: callback function to add
  17439. *
  17440. * Returns the TransformNode.
  17441. */
  17442. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17443. this.onAfterWorldMatrixUpdateObservable.add(func);
  17444. return this;
  17445. };
  17446. /**
  17447. * Removes a registered callback function.
  17448. * Returns the TransformNode.
  17449. */
  17450. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17451. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17452. return this;
  17453. };
  17454. /**
  17455. * Clone the current transform node
  17456. * Returns the new transform node
  17457. * @param name Name of the new clone
  17458. * @param newParent New parent for the clone
  17459. * @param doNotCloneChildren Do not clone children hierarchy
  17460. */
  17461. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17462. var _this = this;
  17463. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17464. result.name = name;
  17465. result.id = name;
  17466. if (newParent) {
  17467. result.parent = newParent;
  17468. }
  17469. if (!doNotCloneChildren) {
  17470. // Children
  17471. var directDescendants = this.getDescendants(true);
  17472. for (var index = 0; index < directDescendants.length; index++) {
  17473. var child = directDescendants[index];
  17474. if (child.clone) {
  17475. child.clone(name + "." + child.name, result);
  17476. }
  17477. }
  17478. }
  17479. return result;
  17480. };
  17481. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17482. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17483. serializationObject.type = this.getClassName();
  17484. // Parent
  17485. if (this.parent) {
  17486. serializationObject.parentId = this.parent.id;
  17487. }
  17488. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17489. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17490. }
  17491. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17492. serializationObject.isEnabled = this.isEnabled();
  17493. // Parent
  17494. if (this.parent) {
  17495. serializationObject.parentId = this.parent.id;
  17496. }
  17497. return serializationObject;
  17498. };
  17499. // Statics
  17500. /**
  17501. * Returns a new TransformNode object parsed from the source provided.
  17502. * The parameter `parsedMesh` is the source.
  17503. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17504. */
  17505. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17506. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17507. if (BABYLON.Tags) {
  17508. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17509. }
  17510. if (parsedTransformNode.localMatrix) {
  17511. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17512. }
  17513. else if (parsedTransformNode.pivotMatrix) {
  17514. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17515. }
  17516. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17517. // Parent
  17518. if (parsedTransformNode.parentId) {
  17519. transformNode._waitingParentId = parsedTransformNode.parentId;
  17520. }
  17521. return transformNode;
  17522. };
  17523. /**
  17524. * Releases resources associated with this transform node.
  17525. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17526. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17527. */
  17528. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17529. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17530. // Animations
  17531. this.getScene().stopAnimation(this);
  17532. // Remove from scene
  17533. this.getScene().removeTransformNode(this);
  17534. this.onAfterWorldMatrixUpdateObservable.clear();
  17535. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  17536. };
  17537. // Statics
  17538. TransformNode.BILLBOARDMODE_NONE = 0;
  17539. TransformNode.BILLBOARDMODE_X = 1;
  17540. TransformNode.BILLBOARDMODE_Y = 2;
  17541. TransformNode.BILLBOARDMODE_Z = 4;
  17542. TransformNode.BILLBOARDMODE_ALL = 7;
  17543. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17544. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17545. __decorate([
  17546. BABYLON.serializeAsVector3()
  17547. ], TransformNode.prototype, "_rotation", void 0);
  17548. __decorate([
  17549. BABYLON.serializeAsQuaternion()
  17550. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17551. __decorate([
  17552. BABYLON.serializeAsVector3()
  17553. ], TransformNode.prototype, "_scaling", void 0);
  17554. __decorate([
  17555. BABYLON.serialize()
  17556. ], TransformNode.prototype, "billboardMode", void 0);
  17557. __decorate([
  17558. BABYLON.serialize()
  17559. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17560. __decorate([
  17561. BABYLON.serialize()
  17562. ], TransformNode.prototype, "infiniteDistance", void 0);
  17563. __decorate([
  17564. BABYLON.serializeAsVector3()
  17565. ], TransformNode.prototype, "position", void 0);
  17566. return TransformNode;
  17567. }(BABYLON.Node));
  17568. BABYLON.TransformNode = TransformNode;
  17569. })(BABYLON || (BABYLON = {}));
  17570. //# sourceMappingURL=babylon.transformNode.js.map
  17571. "use strict";
  17572. var BABYLON;
  17573. (function (BABYLON) {
  17574. var AbstractMesh = /** @class */ (function (_super) {
  17575. __extends(AbstractMesh, _super);
  17576. // Constructor
  17577. function AbstractMesh(name, scene) {
  17578. if (scene === void 0) { scene = null; }
  17579. var _this = _super.call(this, name, scene, false) || this;
  17580. _this._facetNb = 0; // facet number
  17581. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17582. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17583. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17584. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17585. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17586. _this._subDiv = {
  17587. max: 1,
  17588. X: 1,
  17589. Y: 1,
  17590. Z: 1
  17591. };
  17592. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17593. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17594. // Events
  17595. /**
  17596. * An event triggered when this mesh collides with another one
  17597. * @type {BABYLON.Observable}
  17598. */
  17599. _this.onCollideObservable = new BABYLON.Observable();
  17600. /**
  17601. * An event triggered when the collision's position changes
  17602. * @type {BABYLON.Observable}
  17603. */
  17604. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17605. /**
  17606. * An event triggered when material is changed
  17607. * @type {BABYLON.Observable}
  17608. */
  17609. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17610. // Properties
  17611. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17612. /**
  17613. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17614. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17615. * or
  17616. * 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.
  17617. * for more info check WebGl documentations
  17618. */
  17619. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17620. /**
  17621. * 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:
  17622. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17623. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17624. * 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.
  17625. */
  17626. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17627. /**
  17628. * 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.
  17629. * The default value is -1 which means don't break the query and wait till the result.
  17630. */
  17631. _this.occlusionRetryCount = -1;
  17632. _this._occlusionInternalRetryCounter = 0;
  17633. _this._isOccluded = false;
  17634. _this._isOcclusionQueryInProgress = false;
  17635. _this._visibility = 1.0;
  17636. _this.alphaIndex = Number.MAX_VALUE;
  17637. _this.isVisible = true;
  17638. _this.isPickable = true;
  17639. _this.showBoundingBox = false;
  17640. _this.showSubMeshesBoundingBox = false;
  17641. _this.isBlocker = false;
  17642. _this.enablePointerMoveEvents = false;
  17643. _this.renderingGroupId = 0;
  17644. _this._receiveShadows = false;
  17645. _this.renderOutline = false;
  17646. _this.outlineColor = BABYLON.Color3.Red();
  17647. _this.outlineWidth = 0.02;
  17648. _this.renderOverlay = false;
  17649. _this.overlayColor = BABYLON.Color3.Red();
  17650. _this.overlayAlpha = 0.5;
  17651. _this._hasVertexAlpha = false;
  17652. _this._useVertexColors = true;
  17653. _this._computeBonesUsingShaders = true;
  17654. _this._numBoneInfluencers = 4;
  17655. _this._applyFog = true;
  17656. _this.useOctreeForRenderingSelection = true;
  17657. _this.useOctreeForPicking = true;
  17658. _this.useOctreeForCollisions = true;
  17659. _this._layerMask = 0x0FFFFFFF;
  17660. /**
  17661. * True if the mesh must be rendered in any case.
  17662. */
  17663. _this.alwaysSelectAsActiveMesh = false;
  17664. /**
  17665. * This scene's action manager
  17666. * @type {BABYLON.ActionManager}
  17667. */
  17668. _this.actionManager = null;
  17669. // Physics
  17670. _this.physicsImpostor = null;
  17671. // Collisions
  17672. _this._checkCollisions = false;
  17673. _this._collisionMask = -1;
  17674. _this._collisionGroup = -1;
  17675. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17676. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17677. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17678. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17679. // Edges
  17680. _this.edgesWidth = 1;
  17681. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17682. // Cache
  17683. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17684. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17685. _this._renderId = 0;
  17686. _this._intersectionsInProgress = new Array();
  17687. _this._unIndexed = false;
  17688. _this._lightSources = new Array();
  17689. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17690. if (collidedMesh === void 0) { collidedMesh = null; }
  17691. //TODO move this to the collision coordinator!
  17692. if (_this.getScene().workerCollisions)
  17693. newPosition.multiplyInPlace(_this._collider._radius);
  17694. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17695. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17696. _this.position.addInPlace(_this._diffPositionForCollisions);
  17697. }
  17698. if (collidedMesh) {
  17699. _this.onCollideObservable.notifyObservers(collidedMesh);
  17700. }
  17701. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17702. };
  17703. _this.getScene().addMesh(_this);
  17704. _this._resyncLightSources();
  17705. return _this;
  17706. }
  17707. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17708. get: function () {
  17709. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17710. },
  17711. enumerable: true,
  17712. configurable: true
  17713. });
  17714. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17715. get: function () {
  17716. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17717. },
  17718. enumerable: true,
  17719. configurable: true
  17720. });
  17721. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17722. get: function () {
  17723. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17724. },
  17725. enumerable: true,
  17726. configurable: true
  17727. });
  17728. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17729. get: function () {
  17730. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17731. },
  17732. enumerable: true,
  17733. configurable: true
  17734. });
  17735. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17736. get: function () {
  17737. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17738. },
  17739. enumerable: true,
  17740. configurable: true
  17741. });
  17742. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17743. /**
  17744. * Read-only : the number of facets in the mesh
  17745. */
  17746. get: function () {
  17747. return this._facetNb;
  17748. },
  17749. enumerable: true,
  17750. configurable: true
  17751. });
  17752. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17753. /**
  17754. * The number (integer) of subdivisions per axis in the partioning space
  17755. */
  17756. get: function () {
  17757. return this._partitioningSubdivisions;
  17758. },
  17759. set: function (nb) {
  17760. this._partitioningSubdivisions = nb;
  17761. },
  17762. enumerable: true,
  17763. configurable: true
  17764. });
  17765. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17766. /**
  17767. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17768. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17769. */
  17770. get: function () {
  17771. return this._partitioningBBoxRatio;
  17772. },
  17773. set: function (ratio) {
  17774. this._partitioningBBoxRatio = ratio;
  17775. },
  17776. enumerable: true,
  17777. configurable: true
  17778. });
  17779. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17780. /**
  17781. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17782. * Works only for updatable meshes.
  17783. * Doesn't work with multi-materials.
  17784. */
  17785. get: function () {
  17786. return this._facetDepthSort;
  17787. },
  17788. set: function (sort) {
  17789. this._facetDepthSort = sort;
  17790. },
  17791. enumerable: true,
  17792. configurable: true
  17793. });
  17794. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17795. /**
  17796. * The location (Vector3) where the facet depth sort must be computed from.
  17797. * By default, the active camera position.
  17798. * Used only when facet depth sort is enabled.
  17799. */
  17800. get: function () {
  17801. return this._facetDepthSortFrom;
  17802. },
  17803. set: function (location) {
  17804. this._facetDepthSortFrom = location;
  17805. },
  17806. enumerable: true,
  17807. configurable: true
  17808. });
  17809. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17810. /**
  17811. * Read-only boolean : is the feature facetData enabled ?
  17812. */
  17813. get: function () {
  17814. return this._facetDataEnabled;
  17815. },
  17816. enumerable: true,
  17817. configurable: true
  17818. });
  17819. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17820. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17821. return false;
  17822. }
  17823. this._markSubMeshesAsMiscDirty();
  17824. return true;
  17825. };
  17826. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17827. set: function (callback) {
  17828. if (this._onCollideObserver) {
  17829. this.onCollideObservable.remove(this._onCollideObserver);
  17830. }
  17831. this._onCollideObserver = this.onCollideObservable.add(callback);
  17832. },
  17833. enumerable: true,
  17834. configurable: true
  17835. });
  17836. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17837. set: function (callback) {
  17838. if (this._onCollisionPositionChangeObserver) {
  17839. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17840. }
  17841. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17842. },
  17843. enumerable: true,
  17844. configurable: true
  17845. });
  17846. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17847. /**
  17848. * 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.
  17849. */
  17850. get: function () {
  17851. return this._isOccluded;
  17852. },
  17853. set: function (value) {
  17854. this._isOccluded = value;
  17855. },
  17856. enumerable: true,
  17857. configurable: true
  17858. });
  17859. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17860. /**
  17861. * Flag to check the progress status of the query
  17862. */
  17863. get: function () {
  17864. return this._isOcclusionQueryInProgress;
  17865. },
  17866. enumerable: true,
  17867. configurable: true
  17868. });
  17869. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17870. /**
  17871. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17872. */
  17873. get: function () {
  17874. return this._visibility;
  17875. },
  17876. /**
  17877. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17878. */
  17879. set: function (value) {
  17880. if (this._visibility === value) {
  17881. return;
  17882. }
  17883. this._visibility = value;
  17884. this._markSubMeshesAsMiscDirty();
  17885. },
  17886. enumerable: true,
  17887. configurable: true
  17888. });
  17889. Object.defineProperty(AbstractMesh.prototype, "material", {
  17890. get: function () {
  17891. return this._material;
  17892. },
  17893. set: function (value) {
  17894. if (this._material === value) {
  17895. return;
  17896. }
  17897. this._material = value;
  17898. if (this.onMaterialChangedObservable.hasObservers) {
  17899. this.onMaterialChangedObservable.notifyObservers(this);
  17900. }
  17901. if (!this.subMeshes) {
  17902. return;
  17903. }
  17904. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17905. var subMesh = _a[_i];
  17906. subMesh.setEffect(null);
  17907. }
  17908. },
  17909. enumerable: true,
  17910. configurable: true
  17911. });
  17912. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17913. get: function () {
  17914. return this._receiveShadows;
  17915. },
  17916. set: function (value) {
  17917. if (this._receiveShadows === value) {
  17918. return;
  17919. }
  17920. this._receiveShadows = value;
  17921. this._markSubMeshesAsLightDirty();
  17922. },
  17923. enumerable: true,
  17924. configurable: true
  17925. });
  17926. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17927. get: function () {
  17928. return this._hasVertexAlpha;
  17929. },
  17930. set: function (value) {
  17931. if (this._hasVertexAlpha === value) {
  17932. return;
  17933. }
  17934. this._hasVertexAlpha = value;
  17935. this._markSubMeshesAsAttributesDirty();
  17936. this._markSubMeshesAsMiscDirty();
  17937. },
  17938. enumerable: true,
  17939. configurable: true
  17940. });
  17941. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17942. get: function () {
  17943. return this._useVertexColors;
  17944. },
  17945. set: function (value) {
  17946. if (this._useVertexColors === value) {
  17947. return;
  17948. }
  17949. this._useVertexColors = value;
  17950. this._markSubMeshesAsAttributesDirty();
  17951. },
  17952. enumerable: true,
  17953. configurable: true
  17954. });
  17955. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17956. get: function () {
  17957. return this._computeBonesUsingShaders;
  17958. },
  17959. set: function (value) {
  17960. if (this._computeBonesUsingShaders === value) {
  17961. return;
  17962. }
  17963. this._computeBonesUsingShaders = value;
  17964. this._markSubMeshesAsAttributesDirty();
  17965. },
  17966. enumerable: true,
  17967. configurable: true
  17968. });
  17969. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17970. get: function () {
  17971. return this._numBoneInfluencers;
  17972. },
  17973. set: function (value) {
  17974. if (this._numBoneInfluencers === value) {
  17975. return;
  17976. }
  17977. this._numBoneInfluencers = value;
  17978. this._markSubMeshesAsAttributesDirty();
  17979. },
  17980. enumerable: true,
  17981. configurable: true
  17982. });
  17983. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17984. get: function () {
  17985. return this._applyFog;
  17986. },
  17987. set: function (value) {
  17988. if (this._applyFog === value) {
  17989. return;
  17990. }
  17991. this._applyFog = value;
  17992. this._markSubMeshesAsMiscDirty();
  17993. },
  17994. enumerable: true,
  17995. configurable: true
  17996. });
  17997. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17998. get: function () {
  17999. return this._layerMask;
  18000. },
  18001. set: function (value) {
  18002. if (value === this._layerMask) {
  18003. return;
  18004. }
  18005. this._layerMask = value;
  18006. this._resyncLightSources();
  18007. },
  18008. enumerable: true,
  18009. configurable: true
  18010. });
  18011. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  18012. get: function () {
  18013. return this._collisionMask;
  18014. },
  18015. set: function (mask) {
  18016. this._collisionMask = !isNaN(mask) ? mask : -1;
  18017. },
  18018. enumerable: true,
  18019. configurable: true
  18020. });
  18021. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  18022. get: function () {
  18023. return this._collisionGroup;
  18024. },
  18025. set: function (mask) {
  18026. this._collisionGroup = !isNaN(mask) ? mask : -1;
  18027. },
  18028. enumerable: true,
  18029. configurable: true
  18030. });
  18031. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  18032. get: function () {
  18033. return null;
  18034. },
  18035. enumerable: true,
  18036. configurable: true
  18037. });
  18038. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  18039. get: function () {
  18040. return this._skeleton;
  18041. },
  18042. set: function (value) {
  18043. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  18044. this._skeleton._unregisterMeshWithPoseMatrix(this);
  18045. }
  18046. if (value && value.needInitialSkinMatrix) {
  18047. value._registerMeshWithPoseMatrix(this);
  18048. }
  18049. this._skeleton = value;
  18050. if (!this._skeleton) {
  18051. this._bonesTransformMatrices = null;
  18052. }
  18053. this._markSubMeshesAsAttributesDirty();
  18054. },
  18055. enumerable: true,
  18056. configurable: true
  18057. });
  18058. /**
  18059. * Returns the string "AbstractMesh"
  18060. */
  18061. AbstractMesh.prototype.getClassName = function () {
  18062. return "AbstractMesh";
  18063. };
  18064. /**
  18065. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18066. */
  18067. AbstractMesh.prototype.toString = function (fullDetails) {
  18068. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  18069. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  18070. if (this._skeleton) {
  18071. ret += ", skeleton: " + this._skeleton.name;
  18072. }
  18073. if (fullDetails) {
  18074. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  18075. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  18076. }
  18077. return ret;
  18078. };
  18079. AbstractMesh.prototype._rebuild = function () {
  18080. if (this._occlusionQuery) {
  18081. this._occlusionQuery = null;
  18082. }
  18083. if (this._edgesRenderer) {
  18084. this._edgesRenderer._rebuild();
  18085. }
  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. subMesh._rebuild();
  18092. }
  18093. };
  18094. AbstractMesh.prototype._resyncLightSources = function () {
  18095. this._lightSources.length = 0;
  18096. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  18097. var light = _a[_i];
  18098. if (!light.isEnabled()) {
  18099. continue;
  18100. }
  18101. if (light.canAffectMesh(this)) {
  18102. this._lightSources.push(light);
  18103. }
  18104. }
  18105. this._markSubMeshesAsLightDirty();
  18106. };
  18107. AbstractMesh.prototype._resyncLighSource = function (light) {
  18108. var isIn = light.isEnabled() && light.canAffectMesh(this);
  18109. var index = this._lightSources.indexOf(light);
  18110. if (index === -1) {
  18111. if (!isIn) {
  18112. return;
  18113. }
  18114. this._lightSources.push(light);
  18115. }
  18116. else {
  18117. if (isIn) {
  18118. return;
  18119. }
  18120. this._lightSources.splice(index, 1);
  18121. }
  18122. this._markSubMeshesAsLightDirty();
  18123. };
  18124. AbstractMesh.prototype._removeLightSource = function (light) {
  18125. var index = this._lightSources.indexOf(light);
  18126. if (index === -1) {
  18127. return;
  18128. }
  18129. this._lightSources.splice(index, 1);
  18130. this._markSubMeshesAsLightDirty();
  18131. };
  18132. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  18133. if (!this.subMeshes) {
  18134. return;
  18135. }
  18136. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18137. var subMesh = _a[_i];
  18138. if (subMesh._materialDefines) {
  18139. func(subMesh._materialDefines);
  18140. }
  18141. }
  18142. };
  18143. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  18144. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  18145. };
  18146. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  18147. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  18148. };
  18149. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  18150. if (!this.subMeshes) {
  18151. return;
  18152. }
  18153. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18154. var subMesh = _a[_i];
  18155. var material = subMesh.getMaterial();
  18156. if (material) {
  18157. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  18158. }
  18159. }
  18160. };
  18161. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  18162. /**
  18163. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18164. * Default : (1.0, 1.0, 1.0)
  18165. */
  18166. get: function () {
  18167. return this._scaling;
  18168. },
  18169. /**
  18170. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18171. * Default : (1.0, 1.0, 1.0)
  18172. */
  18173. set: function (newScaling) {
  18174. this._scaling = newScaling;
  18175. if (this.physicsImpostor) {
  18176. this.physicsImpostor.forceUpdate();
  18177. }
  18178. },
  18179. enumerable: true,
  18180. configurable: true
  18181. });
  18182. // Methods
  18183. /**
  18184. * Disables the mesh edger rendering mode.
  18185. * Returns the AbstractMesh.
  18186. */
  18187. AbstractMesh.prototype.disableEdgesRendering = function () {
  18188. if (this._edgesRenderer) {
  18189. this._edgesRenderer.dispose();
  18190. this._edgesRenderer = null;
  18191. }
  18192. return this;
  18193. };
  18194. /**
  18195. * Enables the edge rendering mode on the mesh.
  18196. * This mode makes the mesh edges visible.
  18197. * Returns the AbstractMesh.
  18198. */
  18199. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  18200. if (epsilon === void 0) { epsilon = 0.95; }
  18201. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  18202. this.disableEdgesRendering();
  18203. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  18204. return this;
  18205. };
  18206. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  18207. /**
  18208. * Returns true if the mesh is blocked. Used by the class Mesh.
  18209. * Returns the boolean `false` by default.
  18210. */
  18211. get: function () {
  18212. return false;
  18213. },
  18214. enumerable: true,
  18215. configurable: true
  18216. });
  18217. /**
  18218. * Returns the mesh itself by default, used by the class Mesh.
  18219. * Returned type : AbstractMesh
  18220. */
  18221. AbstractMesh.prototype.getLOD = function (camera) {
  18222. return this;
  18223. };
  18224. /**
  18225. * Returns 0 by default, used by the class Mesh.
  18226. * Returns an integer.
  18227. */
  18228. AbstractMesh.prototype.getTotalVertices = function () {
  18229. return 0;
  18230. };
  18231. /**
  18232. * Returns null by default, used by the class Mesh.
  18233. * Returned type : integer array
  18234. */
  18235. AbstractMesh.prototype.getIndices = function () {
  18236. return null;
  18237. };
  18238. /**
  18239. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  18240. * Returned type : float array or Float32Array
  18241. */
  18242. AbstractMesh.prototype.getVerticesData = function (kind) {
  18243. return null;
  18244. };
  18245. /**
  18246. * Sets the vertex data of the mesh geometry for the requested `kind`.
  18247. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  18248. * The `data` are either a numeric array either a Float32Array.
  18249. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  18250. * 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).
  18251. * Note that a new underlying VertexBuffer object is created each call.
  18252. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18253. *
  18254. * Possible `kind` values :
  18255. * - BABYLON.VertexBuffer.PositionKind
  18256. * - BABYLON.VertexBuffer.UVKind
  18257. * - BABYLON.VertexBuffer.UV2Kind
  18258. * - BABYLON.VertexBuffer.UV3Kind
  18259. * - BABYLON.VertexBuffer.UV4Kind
  18260. * - BABYLON.VertexBuffer.UV5Kind
  18261. * - BABYLON.VertexBuffer.UV6Kind
  18262. * - BABYLON.VertexBuffer.ColorKind
  18263. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18264. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18265. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18266. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18267. *
  18268. * Returns the Mesh.
  18269. */
  18270. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18271. return this;
  18272. };
  18273. /**
  18274. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18275. * If the mesh has no geometry, it is simply returned as it is.
  18276. * The `data` are either a numeric array either a Float32Array.
  18277. * No new underlying VertexBuffer object is created.
  18278. * 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.
  18279. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18280. *
  18281. * Possible `kind` values :
  18282. * - BABYLON.VertexBuffer.PositionKind
  18283. * - BABYLON.VertexBuffer.UVKind
  18284. * - BABYLON.VertexBuffer.UV2Kind
  18285. * - BABYLON.VertexBuffer.UV3Kind
  18286. * - BABYLON.VertexBuffer.UV4Kind
  18287. * - BABYLON.VertexBuffer.UV5Kind
  18288. * - BABYLON.VertexBuffer.UV6Kind
  18289. * - BABYLON.VertexBuffer.ColorKind
  18290. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18291. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18292. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18293. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18294. *
  18295. * Returns the Mesh.
  18296. */
  18297. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18298. return this;
  18299. };
  18300. /**
  18301. * Sets the mesh indices.
  18302. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  18303. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  18304. * This method creates a new index buffer each call.
  18305. * Returns the Mesh.
  18306. */
  18307. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  18308. return this;
  18309. };
  18310. /** Returns false by default, used by the class Mesh.
  18311. * Returns a boolean
  18312. */
  18313. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  18314. return false;
  18315. };
  18316. /**
  18317. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  18318. * Returns a BoundingInfo
  18319. */
  18320. AbstractMesh.prototype.getBoundingInfo = function () {
  18321. if (this._masterMesh) {
  18322. return this._masterMesh.getBoundingInfo();
  18323. }
  18324. if (!this._boundingInfo) {
  18325. // this._boundingInfo is being created here
  18326. this._updateBoundingInfo();
  18327. }
  18328. // cannot be null.
  18329. return this._boundingInfo;
  18330. };
  18331. /**
  18332. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  18333. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  18334. */
  18335. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  18336. if (includeDescendants === void 0) { includeDescendants = true; }
  18337. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  18338. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  18339. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  18340. if (maxDimension === 0) {
  18341. return this;
  18342. }
  18343. var scale = 1 / maxDimension;
  18344. this.scaling.scaleInPlace(scale);
  18345. return this;
  18346. };
  18347. /**
  18348. * Sets a mesh new object BoundingInfo.
  18349. * Returns the AbstractMesh.
  18350. */
  18351. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  18352. this._boundingInfo = boundingInfo;
  18353. return this;
  18354. };
  18355. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  18356. get: function () {
  18357. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  18358. },
  18359. enumerable: true,
  18360. configurable: true
  18361. });
  18362. AbstractMesh.prototype._preActivate = function () {
  18363. };
  18364. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18365. };
  18366. AbstractMesh.prototype._activate = function (renderId) {
  18367. this._renderId = renderId;
  18368. };
  18369. /**
  18370. * Returns the latest update of the World matrix
  18371. * Returns a Matrix.
  18372. */
  18373. AbstractMesh.prototype.getWorldMatrix = function () {
  18374. if (this._masterMesh) {
  18375. return this._masterMesh.getWorldMatrix();
  18376. }
  18377. return _super.prototype.getWorldMatrix.call(this);
  18378. };
  18379. /**
  18380. * Returns the latest update of the World matrix determinant.
  18381. */
  18382. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  18383. if (this._masterMesh) {
  18384. return this._masterMesh._getWorldMatrixDeterminant();
  18385. }
  18386. return _super.prototype._getWorldMatrixDeterminant.call(this);
  18387. };
  18388. // ================================== Point of View Movement =================================
  18389. /**
  18390. * Perform relative position change from the point of view of behind the front of the mesh.
  18391. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18392. * Supports definition of mesh facing forward or backward.
  18393. * @param {number} amountRight
  18394. * @param {number} amountUp
  18395. * @param {number} amountForward
  18396. *
  18397. * Returns the AbstractMesh.
  18398. */
  18399. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18400. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18401. return this;
  18402. };
  18403. /**
  18404. * Calculate relative position change from the point of view of behind the front of the mesh.
  18405. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18406. * Supports definition of mesh facing forward or backward.
  18407. * @param {number} amountRight
  18408. * @param {number} amountUp
  18409. * @param {number} amountForward
  18410. *
  18411. * Returns a new Vector3.
  18412. */
  18413. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18414. var rotMatrix = new BABYLON.Matrix();
  18415. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18416. rotQuaternion.toRotationMatrix(rotMatrix);
  18417. var translationDelta = BABYLON.Vector3.Zero();
  18418. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18419. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18420. return translationDelta;
  18421. };
  18422. // ================================== Point of View Rotation =================================
  18423. /**
  18424. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18425. * Supports definition of mesh facing forward or backward.
  18426. * @param {number} flipBack
  18427. * @param {number} twirlClockwise
  18428. * @param {number} tiltRight
  18429. *
  18430. * Returns the AbstractMesh.
  18431. */
  18432. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18433. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18434. return this;
  18435. };
  18436. /**
  18437. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18438. * Supports definition of mesh facing forward or backward.
  18439. * @param {number} flipBack
  18440. * @param {number} twirlClockwise
  18441. * @param {number} tiltRight
  18442. *
  18443. * Returns a new Vector3.
  18444. */
  18445. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18446. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18447. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18448. };
  18449. /**
  18450. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18451. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18452. */
  18453. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18454. if (includeDescendants === void 0) { includeDescendants = true; }
  18455. this.computeWorldMatrix(true);
  18456. var min;
  18457. var max;
  18458. var boundingInfo = this.getBoundingInfo();
  18459. if (!this.subMeshes) {
  18460. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18461. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18462. }
  18463. else {
  18464. min = boundingInfo.boundingBox.minimumWorld;
  18465. max = boundingInfo.boundingBox.maximumWorld;
  18466. }
  18467. if (includeDescendants) {
  18468. var descendants = this.getDescendants(false);
  18469. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18470. var descendant = descendants_1[_i];
  18471. var childMesh = descendant;
  18472. childMesh.computeWorldMatrix(true);
  18473. //make sure we have the needed params to get mix and max
  18474. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18475. continue;
  18476. }
  18477. var childBoundingInfo = childMesh.getBoundingInfo();
  18478. var boundingBox = childBoundingInfo.boundingBox;
  18479. var minBox = boundingBox.minimumWorld;
  18480. var maxBox = boundingBox.maximumWorld;
  18481. BABYLON.Tools.CheckExtends(minBox, min, max);
  18482. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18483. }
  18484. }
  18485. return {
  18486. min: min,
  18487. max: max
  18488. };
  18489. };
  18490. /**
  18491. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18492. * Returns the AbstractMesh.
  18493. */
  18494. AbstractMesh.prototype._updateBoundingInfo = function () {
  18495. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18496. this._boundingInfo.update(this.worldMatrixFromCache);
  18497. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18498. return this;
  18499. };
  18500. /**
  18501. * Update a mesh's children BoundingInfo objects only.
  18502. * Returns the AbstractMesh.
  18503. */
  18504. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18505. if (!this.subMeshes) {
  18506. return this;
  18507. }
  18508. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18509. var subMesh = this.subMeshes[subIndex];
  18510. if (!subMesh.IsGlobal) {
  18511. subMesh.updateBoundingInfo(matrix);
  18512. }
  18513. }
  18514. return this;
  18515. };
  18516. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18517. // Bounding info
  18518. this._updateBoundingInfo();
  18519. };
  18520. /**
  18521. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18522. * A mesh is in the frustum if its bounding box intersects the frustum.
  18523. * Boolean returned.
  18524. */
  18525. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18526. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18527. };
  18528. /**
  18529. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18530. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18531. * Boolean returned.
  18532. */
  18533. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18534. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18535. ;
  18536. };
  18537. /**
  18538. * True if the mesh intersects another mesh or a SolidParticle object.
  18539. * 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)
  18540. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18541. * Returns a boolean.
  18542. */
  18543. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18544. if (precise === void 0) { precise = false; }
  18545. if (!this._boundingInfo || !mesh._boundingInfo) {
  18546. return false;
  18547. }
  18548. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18549. return true;
  18550. }
  18551. if (includeDescendants) {
  18552. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18553. var child = _a[_i];
  18554. if (child.intersectsMesh(mesh, precise, true)) {
  18555. return true;
  18556. }
  18557. }
  18558. }
  18559. return false;
  18560. };
  18561. /**
  18562. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18563. * Returns a boolean.
  18564. */
  18565. AbstractMesh.prototype.intersectsPoint = function (point) {
  18566. if (!this._boundingInfo) {
  18567. return false;
  18568. }
  18569. return this._boundingInfo.intersectsPoint(point);
  18570. };
  18571. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18572. return this.physicsImpostor;
  18573. };
  18574. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18575. if (camera === void 0) { camera = null; }
  18576. if (!camera) {
  18577. camera = this.getScene().activeCamera;
  18578. }
  18579. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18580. };
  18581. /**
  18582. * Returns the distance from the mesh to the active camera.
  18583. * Returns a float.
  18584. */
  18585. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18586. if (camera === void 0) { camera = null; }
  18587. if (!camera) {
  18588. camera = this.getScene().activeCamera;
  18589. }
  18590. return this.absolutePosition.subtract(camera.position).length();
  18591. };
  18592. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18593. if (!this.physicsImpostor) {
  18594. return this;
  18595. }
  18596. this.physicsImpostor.applyImpulse(force, contactPoint);
  18597. return this;
  18598. };
  18599. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18600. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18601. return this;
  18602. }
  18603. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18604. mainPivot: pivot1,
  18605. connectedPivot: pivot2,
  18606. nativeParams: options
  18607. });
  18608. return this;
  18609. };
  18610. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18611. // Collisions
  18612. /**
  18613. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18614. * Default `false`.
  18615. */
  18616. get: function () {
  18617. return this._checkCollisions;
  18618. },
  18619. set: function (collisionEnabled) {
  18620. this._checkCollisions = collisionEnabled;
  18621. if (this.getScene().workerCollisions) {
  18622. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18623. }
  18624. },
  18625. enumerable: true,
  18626. configurable: true
  18627. });
  18628. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18629. /**
  18630. * Gets Collider object used to compute collisions (not physics)
  18631. */
  18632. get: function () {
  18633. return this._collider;
  18634. },
  18635. enumerable: true,
  18636. configurable: true
  18637. });
  18638. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18639. var globalPosition = this.getAbsolutePosition();
  18640. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18641. if (!this._collider) {
  18642. this._collider = new BABYLON.Collider();
  18643. }
  18644. this._collider._radius = this.ellipsoid;
  18645. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18646. return this;
  18647. };
  18648. // Submeshes octree
  18649. /**
  18650. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18651. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18652. * Returns an Octree of submeshes.
  18653. */
  18654. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18655. if (maxCapacity === void 0) { maxCapacity = 64; }
  18656. if (maxDepth === void 0) { maxDepth = 2; }
  18657. if (!this._submeshesOctree) {
  18658. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18659. }
  18660. this.computeWorldMatrix(true);
  18661. var boundingInfo = this.getBoundingInfo();
  18662. // Update octree
  18663. var bbox = boundingInfo.boundingBox;
  18664. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18665. return this._submeshesOctree;
  18666. };
  18667. // Collisions
  18668. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18669. this._generatePointsArray();
  18670. if (!this._positions) {
  18671. return this;
  18672. }
  18673. // Transformation
  18674. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18675. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18676. subMesh._lastColliderWorldVertices = [];
  18677. subMesh._trianglePlanes = [];
  18678. var start = subMesh.verticesStart;
  18679. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18680. for (var i = start; i < end; i++) {
  18681. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18682. }
  18683. }
  18684. // Collide
  18685. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18686. if (collider.collisionFound) {
  18687. collider.collidedMesh = this;
  18688. }
  18689. return this;
  18690. };
  18691. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18692. var subMeshes;
  18693. var len;
  18694. // Octrees
  18695. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18696. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18697. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18698. len = intersections.length;
  18699. subMeshes = intersections.data;
  18700. }
  18701. else {
  18702. subMeshes = this.subMeshes;
  18703. len = subMeshes.length;
  18704. }
  18705. for (var index = 0; index < len; index++) {
  18706. var subMesh = subMeshes[index];
  18707. // Bounding test
  18708. if (len > 1 && !subMesh._checkCollision(collider))
  18709. continue;
  18710. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18711. }
  18712. return this;
  18713. };
  18714. AbstractMesh.prototype._checkCollision = function (collider) {
  18715. // Bounding box test
  18716. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18717. return this;
  18718. // Transformation matrix
  18719. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18720. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18721. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18722. return this;
  18723. };
  18724. // Picking
  18725. AbstractMesh.prototype._generatePointsArray = function () {
  18726. return false;
  18727. };
  18728. /**
  18729. * Checks if the passed Ray intersects with the mesh.
  18730. * Returns an object PickingInfo.
  18731. */
  18732. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18733. var pickingInfo = new BABYLON.PickingInfo();
  18734. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18735. return pickingInfo;
  18736. }
  18737. if (!this._generatePointsArray()) {
  18738. return pickingInfo;
  18739. }
  18740. var intersectInfo = null;
  18741. // Octrees
  18742. var subMeshes;
  18743. var len;
  18744. if (this._submeshesOctree && this.useOctreeForPicking) {
  18745. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18746. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18747. len = intersections.length;
  18748. subMeshes = intersections.data;
  18749. }
  18750. else {
  18751. subMeshes = this.subMeshes;
  18752. len = subMeshes.length;
  18753. }
  18754. for (var index = 0; index < len; index++) {
  18755. var subMesh = subMeshes[index];
  18756. // Bounding test
  18757. if (len > 1 && !subMesh.canIntersects(ray))
  18758. continue;
  18759. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18760. if (currentIntersectInfo) {
  18761. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18762. intersectInfo = currentIntersectInfo;
  18763. intersectInfo.subMeshId = index;
  18764. if (fastCheck) {
  18765. break;
  18766. }
  18767. }
  18768. }
  18769. }
  18770. if (intersectInfo) {
  18771. // Get picked point
  18772. var world = this.getWorldMatrix();
  18773. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18774. var direction = ray.direction.clone();
  18775. direction = direction.scale(intersectInfo.distance);
  18776. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18777. var pickedPoint = worldOrigin.add(worldDirection);
  18778. // Return result
  18779. pickingInfo.hit = true;
  18780. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18781. pickingInfo.pickedPoint = pickedPoint;
  18782. pickingInfo.pickedMesh = this;
  18783. pickingInfo.bu = intersectInfo.bu || 0;
  18784. pickingInfo.bv = intersectInfo.bv || 0;
  18785. pickingInfo.faceId = intersectInfo.faceId;
  18786. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18787. return pickingInfo;
  18788. }
  18789. return pickingInfo;
  18790. };
  18791. /**
  18792. * Clones the mesh, used by the class Mesh.
  18793. * Just returns `null` for an AbstractMesh.
  18794. */
  18795. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18796. return null;
  18797. };
  18798. /**
  18799. * Disposes all the mesh submeshes.
  18800. * Returns the AbstractMesh.
  18801. */
  18802. AbstractMesh.prototype.releaseSubMeshes = function () {
  18803. if (this.subMeshes) {
  18804. while (this.subMeshes.length) {
  18805. this.subMeshes[0].dispose();
  18806. }
  18807. }
  18808. else {
  18809. this.subMeshes = new Array();
  18810. }
  18811. return this;
  18812. };
  18813. /**
  18814. * Releases resources associated with this abstract mesh.
  18815. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18816. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18817. */
  18818. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18819. var _this = this;
  18820. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18821. var index;
  18822. // Smart Array Retainers.
  18823. this.getScene().freeActiveMeshes();
  18824. this.getScene().freeRenderingGroups();
  18825. // Action manager
  18826. if (this.actionManager !== undefined && this.actionManager !== null) {
  18827. this.actionManager.dispose();
  18828. this.actionManager = null;
  18829. }
  18830. // Skeleton
  18831. this.skeleton = null;
  18832. // Physics
  18833. if (this.physicsImpostor) {
  18834. this.physicsImpostor.dispose();
  18835. }
  18836. // Intersections in progress
  18837. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18838. var other = this._intersectionsInProgress[index];
  18839. var pos = other._intersectionsInProgress.indexOf(this);
  18840. other._intersectionsInProgress.splice(pos, 1);
  18841. }
  18842. this._intersectionsInProgress = [];
  18843. // Lights
  18844. var lights = this.getScene().lights;
  18845. lights.forEach(function (light) {
  18846. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18847. if (meshIndex !== -1) {
  18848. light.includedOnlyMeshes.splice(meshIndex, 1);
  18849. }
  18850. meshIndex = light.excludedMeshes.indexOf(_this);
  18851. if (meshIndex !== -1) {
  18852. light.excludedMeshes.splice(meshIndex, 1);
  18853. }
  18854. // Shadow generators
  18855. var generator = light.getShadowGenerator();
  18856. if (generator) {
  18857. var shadowMap = generator.getShadowMap();
  18858. if (shadowMap && shadowMap.renderList) {
  18859. meshIndex = shadowMap.renderList.indexOf(_this);
  18860. if (meshIndex !== -1) {
  18861. shadowMap.renderList.splice(meshIndex, 1);
  18862. }
  18863. }
  18864. }
  18865. });
  18866. // Edges
  18867. if (this._edgesRenderer) {
  18868. this._edgesRenderer.dispose();
  18869. this._edgesRenderer = null;
  18870. }
  18871. // SubMeshes
  18872. if (this.getClassName() !== "InstancedMesh") {
  18873. this.releaseSubMeshes();
  18874. }
  18875. // Octree
  18876. var sceneOctree = this.getScene().selectionOctree;
  18877. if (sceneOctree !== undefined && sceneOctree !== null) {
  18878. var index = sceneOctree.dynamicContent.indexOf(this);
  18879. if (index !== -1) {
  18880. sceneOctree.dynamicContent.splice(index, 1);
  18881. }
  18882. }
  18883. // Query
  18884. var engine = this.getScene().getEngine();
  18885. if (this._occlusionQuery) {
  18886. this._isOcclusionQueryInProgress = false;
  18887. engine.deleteQuery(this._occlusionQuery);
  18888. this._occlusionQuery = null;
  18889. }
  18890. // Engine
  18891. engine.wipeCaches();
  18892. // Remove from scene
  18893. this.getScene().removeMesh(this);
  18894. if (disposeMaterialAndTextures) {
  18895. if (this.material) {
  18896. this.material.dispose(false, true);
  18897. }
  18898. }
  18899. if (!doNotRecurse) {
  18900. // Particles
  18901. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18902. if (this.getScene().particleSystems[index].emitter === this) {
  18903. this.getScene().particleSystems[index].dispose();
  18904. index--;
  18905. }
  18906. }
  18907. }
  18908. // facet data
  18909. if (this._facetDataEnabled) {
  18910. this.disableFacetData();
  18911. }
  18912. this.onAfterWorldMatrixUpdateObservable.clear();
  18913. this.onCollideObservable.clear();
  18914. this.onCollisionPositionChangeObservable.clear();
  18915. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18916. };
  18917. /**
  18918. * Adds the passed mesh as a child to the current mesh.
  18919. * Returns the AbstractMesh.
  18920. */
  18921. AbstractMesh.prototype.addChild = function (mesh) {
  18922. mesh.setParent(this);
  18923. return this;
  18924. };
  18925. /**
  18926. * Removes the passed mesh from the current mesh children list.
  18927. * Returns the AbstractMesh.
  18928. */
  18929. AbstractMesh.prototype.removeChild = function (mesh) {
  18930. mesh.setParent(null);
  18931. return this;
  18932. };
  18933. // Facet data
  18934. /**
  18935. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18936. * Returns the AbstractMesh.
  18937. */
  18938. AbstractMesh.prototype._initFacetData = function () {
  18939. if (!this._facetNormals) {
  18940. this._facetNormals = new Array();
  18941. }
  18942. if (!this._facetPositions) {
  18943. this._facetPositions = new Array();
  18944. }
  18945. if (!this._facetPartitioning) {
  18946. this._facetPartitioning = new Array();
  18947. }
  18948. this._facetNb = (this.getIndices().length / 3) | 0;
  18949. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18950. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18951. for (var f = 0; f < this._facetNb; f++) {
  18952. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18953. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18954. }
  18955. this._facetDataEnabled = true;
  18956. return this;
  18957. };
  18958. /**
  18959. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18960. * This method can be called within the render loop.
  18961. * 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.
  18962. * Returns the AbstractMesh.
  18963. */
  18964. AbstractMesh.prototype.updateFacetData = function () {
  18965. if (!this._facetDataEnabled) {
  18966. this._initFacetData();
  18967. }
  18968. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18969. var indices = this.getIndices();
  18970. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18971. var bInfo = this.getBoundingInfo();
  18972. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18973. // init arrays, matrix and sort function on first call
  18974. this._facetDepthSortEnabled = true;
  18975. if (indices instanceof Uint16Array) {
  18976. this._depthSortedIndices = new Uint16Array(indices);
  18977. }
  18978. else if (indices instanceof Uint32Array) {
  18979. this._depthSortedIndices = new Uint32Array(indices);
  18980. }
  18981. else {
  18982. var needs32bits = false;
  18983. for (var i = 0; i < indices.length; i++) {
  18984. if (indices[i] > 65535) {
  18985. needs32bits = true;
  18986. break;
  18987. }
  18988. }
  18989. if (needs32bits) {
  18990. this._depthSortedIndices = new Uint32Array(indices);
  18991. }
  18992. else {
  18993. this._depthSortedIndices = new Uint16Array(indices);
  18994. }
  18995. }
  18996. this._facetDepthSortFunction = function (f1, f2) {
  18997. return (f2.sqDistance - f1.sqDistance);
  18998. };
  18999. if (!this._facetDepthSortFrom) {
  19000. var camera = this.getScene().activeCamera;
  19001. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  19002. }
  19003. this._depthSortedFacets = [];
  19004. for (var f = 0; f < this._facetNb; f++) {
  19005. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  19006. this._depthSortedFacets.push(depthSortedFacet);
  19007. }
  19008. this._invertedMatrix = BABYLON.Matrix.Identity();
  19009. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  19010. }
  19011. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  19012. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  19013. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  19014. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  19015. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  19016. this._subDiv.max = this._partitioningSubdivisions;
  19017. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  19018. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  19019. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  19020. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  19021. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  19022. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  19023. // set the parameters for ComputeNormals()
  19024. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  19025. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  19026. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  19027. this._facetParameters.bInfo = bInfo;
  19028. this._facetParameters.bbSize = this._bbSize;
  19029. this._facetParameters.subDiv = this._subDiv;
  19030. this._facetParameters.ratio = this.partitioningBBoxRatio;
  19031. this._facetParameters.depthSort = this._facetDepthSort;
  19032. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  19033. this.computeWorldMatrix(true);
  19034. this._worldMatrix.invertToRef(this._invertedMatrix);
  19035. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  19036. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  19037. }
  19038. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  19039. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  19040. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  19041. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  19042. var l = (this._depthSortedIndices.length / 3) | 0;
  19043. for (var f = 0; f < l; f++) {
  19044. var sind = this._depthSortedFacets[f].ind;
  19045. this._depthSortedIndices[f * 3] = indices[sind];
  19046. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  19047. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  19048. }
  19049. this.updateIndices(this._depthSortedIndices);
  19050. }
  19051. return this;
  19052. };
  19053. /**
  19054. * Returns the facetLocalNormals array.
  19055. * The normals are expressed in the mesh local space.
  19056. */
  19057. AbstractMesh.prototype.getFacetLocalNormals = function () {
  19058. if (!this._facetNormals) {
  19059. this.updateFacetData();
  19060. }
  19061. return this._facetNormals;
  19062. };
  19063. /**
  19064. * Returns the facetLocalPositions array.
  19065. * The facet positions are expressed in the mesh local space.
  19066. */
  19067. AbstractMesh.prototype.getFacetLocalPositions = function () {
  19068. if (!this._facetPositions) {
  19069. this.updateFacetData();
  19070. }
  19071. return this._facetPositions;
  19072. };
  19073. /**
  19074. * Returns the facetLocalPartioning array.
  19075. */
  19076. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  19077. if (!this._facetPartitioning) {
  19078. this.updateFacetData();
  19079. }
  19080. return this._facetPartitioning;
  19081. };
  19082. /**
  19083. * Returns the i-th facet position in the world system.
  19084. * This method allocates a new Vector3 per call.
  19085. */
  19086. AbstractMesh.prototype.getFacetPosition = function (i) {
  19087. var pos = BABYLON.Vector3.Zero();
  19088. this.getFacetPositionToRef(i, pos);
  19089. return pos;
  19090. };
  19091. /**
  19092. * Sets the reference Vector3 with the i-th facet position in the world system.
  19093. * Returns the AbstractMesh.
  19094. */
  19095. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  19096. var localPos = (this.getFacetLocalPositions())[i];
  19097. var world = this.getWorldMatrix();
  19098. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  19099. return this;
  19100. };
  19101. /**
  19102. * Returns the i-th facet normal in the world system.
  19103. * This method allocates a new Vector3 per call.
  19104. */
  19105. AbstractMesh.prototype.getFacetNormal = function (i) {
  19106. var norm = BABYLON.Vector3.Zero();
  19107. this.getFacetNormalToRef(i, norm);
  19108. return norm;
  19109. };
  19110. /**
  19111. * Sets the reference Vector3 with the i-th facet normal in the world system.
  19112. * Returns the AbstractMesh.
  19113. */
  19114. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  19115. var localNorm = (this.getFacetLocalNormals())[i];
  19116. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  19117. return this;
  19118. };
  19119. /**
  19120. * 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).
  19121. */
  19122. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  19123. var bInfo = this.getBoundingInfo();
  19124. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  19125. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  19126. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  19127. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  19128. return null;
  19129. }
  19130. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  19131. };
  19132. /**
  19133. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  19134. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  19135. * 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.
  19136. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19137. * 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.
  19138. */
  19139. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  19140. if (checkFace === void 0) { checkFace = false; }
  19141. if (facing === void 0) { facing = true; }
  19142. var world = this.getWorldMatrix();
  19143. var invMat = BABYLON.Tmp.Matrix[5];
  19144. world.invertToRef(invMat);
  19145. var invVect = BABYLON.Tmp.Vector3[8];
  19146. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  19147. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  19148. if (projected) {
  19149. // tranform the local computed projected vector to world coordinates
  19150. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  19151. }
  19152. return closest;
  19153. };
  19154. /**
  19155. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  19156. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  19157. * 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.
  19158. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19159. * 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.
  19160. */
  19161. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  19162. if (checkFace === void 0) { checkFace = false; }
  19163. if (facing === void 0) { facing = true; }
  19164. var closest = null;
  19165. var tmpx = 0.0;
  19166. var tmpy = 0.0;
  19167. var tmpz = 0.0;
  19168. var d = 0.0; // tmp dot facet normal * facet position
  19169. var t0 = 0.0;
  19170. var projx = 0.0;
  19171. var projy = 0.0;
  19172. var projz = 0.0;
  19173. // Get all the facets in the same partitioning block than (x, y, z)
  19174. var facetPositions = this.getFacetLocalPositions();
  19175. var facetNormals = this.getFacetLocalNormals();
  19176. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  19177. if (!facetsInBlock) {
  19178. return null;
  19179. }
  19180. // Get the closest facet to (x, y, z)
  19181. var shortest = Number.MAX_VALUE; // init distance vars
  19182. var tmpDistance = shortest;
  19183. var fib; // current facet in the block
  19184. var norm; // current facet normal
  19185. var p0; // current facet barycenter position
  19186. // loop on all the facets in the current partitioning block
  19187. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  19188. fib = facetsInBlock[idx];
  19189. norm = facetNormals[fib];
  19190. p0 = facetPositions[fib];
  19191. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  19192. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  19193. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  19194. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  19195. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  19196. projx = x + norm.x * t0;
  19197. projy = y + norm.y * t0;
  19198. projz = z + norm.z * t0;
  19199. tmpx = projx - x;
  19200. tmpy = projy - y;
  19201. tmpz = projz - z;
  19202. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  19203. if (tmpDistance < shortest) {
  19204. shortest = tmpDistance;
  19205. closest = fib;
  19206. if (projected) {
  19207. projected.x = projx;
  19208. projected.y = projy;
  19209. projected.z = projz;
  19210. }
  19211. }
  19212. }
  19213. }
  19214. return closest;
  19215. };
  19216. /**
  19217. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  19218. */
  19219. AbstractMesh.prototype.getFacetDataParameters = function () {
  19220. return this._facetParameters;
  19221. };
  19222. /**
  19223. * Disables the feature FacetData and frees the related memory.
  19224. * Returns the AbstractMesh.
  19225. */
  19226. AbstractMesh.prototype.disableFacetData = function () {
  19227. if (this._facetDataEnabled) {
  19228. this._facetDataEnabled = false;
  19229. this._facetPositions = new Array();
  19230. this._facetNormals = new Array();
  19231. this._facetPartitioning = new Array();
  19232. this._facetParameters = null;
  19233. this._depthSortedIndices = new Uint32Array(0);
  19234. }
  19235. return this;
  19236. };
  19237. /**
  19238. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  19239. * Returns the mesh.
  19240. */
  19241. AbstractMesh.prototype.updateIndices = function (indices) {
  19242. return this;
  19243. };
  19244. /**
  19245. * The mesh Geometry. Actually used by the Mesh object.
  19246. * Returns a blank geometry object.
  19247. */
  19248. /**
  19249. * Creates new normals data for the mesh.
  19250. * @param updatable.
  19251. */
  19252. AbstractMesh.prototype.createNormals = function (updatable) {
  19253. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19254. var indices = this.getIndices();
  19255. var normals;
  19256. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19257. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19258. }
  19259. else {
  19260. normals = [];
  19261. }
  19262. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  19263. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  19264. };
  19265. /**
  19266. * Align the mesh with a normal.
  19267. * Returns the mesh.
  19268. */
  19269. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  19270. if (!upDirection) {
  19271. upDirection = BABYLON.Axis.Y;
  19272. }
  19273. var axisX = BABYLON.Tmp.Vector3[0];
  19274. var axisZ = BABYLON.Tmp.Vector3[1];
  19275. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  19276. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  19277. if (this.rotationQuaternion) {
  19278. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  19279. }
  19280. else {
  19281. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  19282. }
  19283. return this;
  19284. };
  19285. AbstractMesh.prototype.checkOcclusionQuery = function () {
  19286. var engine = this.getEngine();
  19287. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  19288. this._isOccluded = false;
  19289. return;
  19290. }
  19291. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  19292. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  19293. if (isOcclusionQueryAvailable) {
  19294. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  19295. this._isOcclusionQueryInProgress = false;
  19296. this._occlusionInternalRetryCounter = 0;
  19297. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  19298. }
  19299. else {
  19300. this._occlusionInternalRetryCounter++;
  19301. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  19302. this._isOcclusionQueryInProgress = false;
  19303. this._occlusionInternalRetryCounter = 0;
  19304. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  19305. // if strict continue the last state of the object.
  19306. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  19307. }
  19308. else {
  19309. return;
  19310. }
  19311. }
  19312. }
  19313. var scene = this.getScene();
  19314. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  19315. if (!this._occlusionQuery) {
  19316. this._occlusionQuery = engine.createQuery();
  19317. }
  19318. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  19319. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  19320. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  19321. this._isOcclusionQueryInProgress = true;
  19322. };
  19323. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  19324. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  19325. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  19326. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  19327. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  19328. return AbstractMesh;
  19329. }(BABYLON.TransformNode));
  19330. BABYLON.AbstractMesh = AbstractMesh;
  19331. })(BABYLON || (BABYLON = {}));
  19332. //# sourceMappingURL=babylon.abstractMesh.js.map
  19333. "use strict";
  19334. var BABYLON;
  19335. (function (BABYLON) {
  19336. /**
  19337. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  19338. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  19339. * 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.
  19340. */
  19341. var Light = /** @class */ (function (_super) {
  19342. __extends(Light, _super);
  19343. /**
  19344. * Creates a Light object in the scene.
  19345. * Documentation : http://doc.babylonjs.com/tutorials/lights
  19346. * @param name The firendly name of the light
  19347. * @param scene The scene the light belongs too
  19348. */
  19349. function Light(name, scene) {
  19350. var _this = _super.call(this, name, scene) || this;
  19351. /**
  19352. * Diffuse gives the basic color to an object.
  19353. */
  19354. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  19355. /**
  19356. * Specular produces a highlight color on an object.
  19357. * Note: This is note affecting PBR materials.
  19358. */
  19359. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  19360. /**
  19361. * Strength of the light.
  19362. * Note: By default it is define in the framework own unit.
  19363. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  19364. */
  19365. _this.intensity = 1.0;
  19366. /**
  19367. * Defines how far from the source the light is impacting in scene units.
  19368. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  19369. */
  19370. _this.range = Number.MAX_VALUE;
  19371. /**
  19372. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  19373. * of light.
  19374. */
  19375. _this._photometricScale = 1.0;
  19376. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  19377. _this._radius = 0.00001;
  19378. /**
  19379. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  19380. * exceeding the number allowed of the materials.
  19381. */
  19382. _this.renderPriority = 0;
  19383. /**
  19384. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  19385. * the current shadow generator.
  19386. */
  19387. _this.shadowEnabled = true;
  19388. _this._excludeWithLayerMask = 0;
  19389. _this._includeOnlyWithLayerMask = 0;
  19390. _this._lightmapMode = 0;
  19391. /**
  19392. * @ignore Internal use only.
  19393. */
  19394. _this._excludedMeshesIds = new Array();
  19395. /**
  19396. * @ignore Internal use only.
  19397. */
  19398. _this._includedOnlyMeshesIds = new Array();
  19399. _this.getScene().addLight(_this);
  19400. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19401. _this._buildUniformLayout();
  19402. _this.includedOnlyMeshes = new Array();
  19403. _this.excludedMeshes = new Array();
  19404. _this._resyncMeshes();
  19405. return _this;
  19406. }
  19407. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19408. /**
  19409. * If every light affecting the material is in this lightmapMode,
  19410. * material.lightmapTexture adds or multiplies
  19411. * (depends on material.useLightmapAsShadowmap)
  19412. * after every other light calculations.
  19413. */
  19414. get: function () {
  19415. return Light._LIGHTMAP_DEFAULT;
  19416. },
  19417. enumerable: true,
  19418. configurable: true
  19419. });
  19420. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19421. /**
  19422. * material.lightmapTexture as only diffuse lighting from this light
  19423. * adds only specular lighting from this light
  19424. * adds dynamic shadows
  19425. */
  19426. get: function () {
  19427. return Light._LIGHTMAP_SPECULAR;
  19428. },
  19429. enumerable: true,
  19430. configurable: true
  19431. });
  19432. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19433. /**
  19434. * material.lightmapTexture as only lighting
  19435. * no light calculation from this light
  19436. * only adds dynamic shadows from this light
  19437. */
  19438. get: function () {
  19439. return Light._LIGHTMAP_SHADOWSONLY;
  19440. },
  19441. enumerable: true,
  19442. configurable: true
  19443. });
  19444. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19445. /**
  19446. * Each light type uses the default quantity according to its type:
  19447. * point/spot lights use luminous intensity
  19448. * directional lights use illuminance
  19449. */
  19450. get: function () {
  19451. return Light._INTENSITYMODE_AUTOMATIC;
  19452. },
  19453. enumerable: true,
  19454. configurable: true
  19455. });
  19456. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19457. /**
  19458. * lumen (lm)
  19459. */
  19460. get: function () {
  19461. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19462. },
  19463. enumerable: true,
  19464. configurable: true
  19465. });
  19466. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19467. /**
  19468. * candela (lm/sr)
  19469. */
  19470. get: function () {
  19471. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19472. },
  19473. enumerable: true,
  19474. configurable: true
  19475. });
  19476. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19477. /**
  19478. * lux (lm/m^2)
  19479. */
  19480. get: function () {
  19481. return Light._INTENSITYMODE_ILLUMINANCE;
  19482. },
  19483. enumerable: true,
  19484. configurable: true
  19485. });
  19486. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19487. /**
  19488. * nit (cd/m^2)
  19489. */
  19490. get: function () {
  19491. return Light._INTENSITYMODE_LUMINANCE;
  19492. },
  19493. enumerable: true,
  19494. configurable: true
  19495. });
  19496. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19497. /**
  19498. * Light type const id of the point light.
  19499. */
  19500. get: function () {
  19501. return Light._LIGHTTYPEID_POINTLIGHT;
  19502. },
  19503. enumerable: true,
  19504. configurable: true
  19505. });
  19506. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19507. /**
  19508. * Light type const id of the directional light.
  19509. */
  19510. get: function () {
  19511. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19512. },
  19513. enumerable: true,
  19514. configurable: true
  19515. });
  19516. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19517. /**
  19518. * Light type const id of the spot light.
  19519. */
  19520. get: function () {
  19521. return Light._LIGHTTYPEID_SPOTLIGHT;
  19522. },
  19523. enumerable: true,
  19524. configurable: true
  19525. });
  19526. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19527. /**
  19528. * Light type const id of the hemispheric light.
  19529. */
  19530. get: function () {
  19531. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19532. },
  19533. enumerable: true,
  19534. configurable: true
  19535. });
  19536. Object.defineProperty(Light.prototype, "intensityMode", {
  19537. /**
  19538. * Gets the photometric scale used to interpret the intensity.
  19539. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19540. */
  19541. get: function () {
  19542. return this._intensityMode;
  19543. },
  19544. /**
  19545. * Sets the photometric scale used to interpret the intensity.
  19546. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19547. */
  19548. set: function (value) {
  19549. this._intensityMode = value;
  19550. this._computePhotometricScale();
  19551. },
  19552. enumerable: true,
  19553. configurable: true
  19554. });
  19555. ;
  19556. ;
  19557. Object.defineProperty(Light.prototype, "radius", {
  19558. /**
  19559. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19560. */
  19561. get: function () {
  19562. return this._radius;
  19563. },
  19564. /**
  19565. * sets the light radius used by PBR Materials to simulate soft area lights.
  19566. */
  19567. set: function (value) {
  19568. this._radius = value;
  19569. this._computePhotometricScale();
  19570. },
  19571. enumerable: true,
  19572. configurable: true
  19573. });
  19574. ;
  19575. ;
  19576. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19577. /**
  19578. * Gets the only meshes impacted by this light.
  19579. */
  19580. get: function () {
  19581. return this._includedOnlyMeshes;
  19582. },
  19583. /**
  19584. * Sets the only meshes impacted by this light.
  19585. */
  19586. set: function (value) {
  19587. this._includedOnlyMeshes = value;
  19588. this._hookArrayForIncludedOnly(value);
  19589. },
  19590. enumerable: true,
  19591. configurable: true
  19592. });
  19593. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19594. /**
  19595. * Gets the meshes not impacted by this light.
  19596. */
  19597. get: function () {
  19598. return this._excludedMeshes;
  19599. },
  19600. /**
  19601. * Sets the meshes not impacted by this light.
  19602. */
  19603. set: function (value) {
  19604. this._excludedMeshes = value;
  19605. this._hookArrayForExcluded(value);
  19606. },
  19607. enumerable: true,
  19608. configurable: true
  19609. });
  19610. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19611. /**
  19612. * Gets the layer id use to find what meshes are not impacted by the light.
  19613. * Inactive if 0
  19614. */
  19615. get: function () {
  19616. return this._excludeWithLayerMask;
  19617. },
  19618. /**
  19619. * Sets the layer id use to find what meshes are not impacted by the light.
  19620. * Inactive if 0
  19621. */
  19622. set: function (value) {
  19623. this._excludeWithLayerMask = value;
  19624. this._resyncMeshes();
  19625. },
  19626. enumerable: true,
  19627. configurable: true
  19628. });
  19629. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19630. /**
  19631. * Gets the layer id use to find what meshes are impacted by the light.
  19632. * Inactive if 0
  19633. */
  19634. get: function () {
  19635. return this._includeOnlyWithLayerMask;
  19636. },
  19637. /**
  19638. * Sets the layer id use to find what meshes are impacted by the light.
  19639. * Inactive if 0
  19640. */
  19641. set: function (value) {
  19642. this._includeOnlyWithLayerMask = value;
  19643. this._resyncMeshes();
  19644. },
  19645. enumerable: true,
  19646. configurable: true
  19647. });
  19648. Object.defineProperty(Light.prototype, "lightmapMode", {
  19649. /**
  19650. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19651. */
  19652. get: function () {
  19653. return this._lightmapMode;
  19654. },
  19655. /**
  19656. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19657. */
  19658. set: function (value) {
  19659. if (this._lightmapMode === value) {
  19660. return;
  19661. }
  19662. this._lightmapMode = value;
  19663. this._markMeshesAsLightDirty();
  19664. },
  19665. enumerable: true,
  19666. configurable: true
  19667. });
  19668. /**
  19669. * Returns the string "Light".
  19670. * @returns the class name
  19671. */
  19672. Light.prototype.getClassName = function () {
  19673. return "Light";
  19674. };
  19675. /**
  19676. * Converts the light information to a readable string for debug purpose.
  19677. * @param fullDetails Supports for multiple levels of logging within scene loading
  19678. * @returns the human readable light info
  19679. */
  19680. Light.prototype.toString = function (fullDetails) {
  19681. var ret = "Name: " + this.name;
  19682. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19683. if (this.animations) {
  19684. for (var i = 0; i < this.animations.length; i++) {
  19685. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19686. }
  19687. }
  19688. if (fullDetails) {
  19689. }
  19690. return ret;
  19691. };
  19692. /**
  19693. * Set the enabled state of this node.
  19694. * @param value - the new enabled state
  19695. * @see isEnabled
  19696. */
  19697. Light.prototype.setEnabled = function (value) {
  19698. _super.prototype.setEnabled.call(this, value);
  19699. this._resyncMeshes();
  19700. };
  19701. /**
  19702. * Returns the Light associated shadow generator if any.
  19703. * @return the associated shadow generator.
  19704. */
  19705. Light.prototype.getShadowGenerator = function () {
  19706. return this._shadowGenerator;
  19707. };
  19708. /**
  19709. * Returns a Vector3, the absolute light position in the World.
  19710. * @returns the world space position of the light
  19711. */
  19712. Light.prototype.getAbsolutePosition = function () {
  19713. return BABYLON.Vector3.Zero();
  19714. };
  19715. /**
  19716. * Specifies if the light will affect the passed mesh.
  19717. * @param mesh The mesh to test against the light
  19718. * @return true the mesh is affected otherwise, false.
  19719. */
  19720. Light.prototype.canAffectMesh = function (mesh) {
  19721. if (!mesh) {
  19722. return true;
  19723. }
  19724. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19725. return false;
  19726. }
  19727. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19728. return false;
  19729. }
  19730. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19731. return false;
  19732. }
  19733. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19734. return false;
  19735. }
  19736. return true;
  19737. };
  19738. /**
  19739. * Computes and Returns the light World matrix.
  19740. * @returns the world matrix
  19741. */
  19742. Light.prototype.getWorldMatrix = function () {
  19743. this._currentRenderId = this.getScene().getRenderId();
  19744. var worldMatrix = this._getWorldMatrix();
  19745. if (this.parent && this.parent.getWorldMatrix) {
  19746. if (!this._parentedWorldMatrix) {
  19747. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19748. }
  19749. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19750. this._markSyncedWithParent();
  19751. return this._parentedWorldMatrix;
  19752. }
  19753. return worldMatrix;
  19754. };
  19755. /**
  19756. * Sort function to order lights for rendering.
  19757. * @param a First Light object to compare to second.
  19758. * @param b Second Light object to compare first.
  19759. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19760. */
  19761. Light.CompareLightsPriority = function (a, b) {
  19762. //shadow-casting lights have priority over non-shadow-casting lights
  19763. //the renderPrioirty is a secondary sort criterion
  19764. if (a.shadowEnabled !== b.shadowEnabled) {
  19765. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19766. }
  19767. return b.renderPriority - a.renderPriority;
  19768. };
  19769. /**
  19770. * Releases resources associated with this node.
  19771. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19772. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19773. */
  19774. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19775. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19776. if (this._shadowGenerator) {
  19777. this._shadowGenerator.dispose();
  19778. this._shadowGenerator = null;
  19779. }
  19780. // Animations
  19781. this.getScene().stopAnimation(this);
  19782. // Remove from meshes
  19783. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19784. var mesh = _a[_i];
  19785. mesh._removeLightSource(this);
  19786. }
  19787. this._uniformBuffer.dispose();
  19788. // Remove from scene
  19789. this.getScene().removeLight(this);
  19790. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19791. };
  19792. /**
  19793. * Returns the light type ID (integer).
  19794. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19795. */
  19796. Light.prototype.getTypeID = function () {
  19797. return 0;
  19798. };
  19799. /**
  19800. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19801. * @returns the scaled intensity in intensity mode unit
  19802. */
  19803. Light.prototype.getScaledIntensity = function () {
  19804. return this._photometricScale * this.intensity;
  19805. };
  19806. /**
  19807. * Returns a new Light object, named "name", from the current one.
  19808. * @param name The name of the cloned light
  19809. * @returns the new created light
  19810. */
  19811. Light.prototype.clone = function (name) {
  19812. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19813. if (!constructor) {
  19814. return null;
  19815. }
  19816. return BABYLON.SerializationHelper.Clone(constructor, this);
  19817. };
  19818. /**
  19819. * Serializes the current light into a Serialization object.
  19820. * @returns the serialized object.
  19821. */
  19822. Light.prototype.serialize = function () {
  19823. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19824. // Type
  19825. serializationObject.type = this.getTypeID();
  19826. // Parent
  19827. if (this.parent) {
  19828. serializationObject.parentId = this.parent.id;
  19829. }
  19830. // Inclusion / exclusions
  19831. if (this.excludedMeshes.length > 0) {
  19832. serializationObject.excludedMeshesIds = [];
  19833. this.excludedMeshes.forEach(function (mesh) {
  19834. serializationObject.excludedMeshesIds.push(mesh.id);
  19835. });
  19836. }
  19837. if (this.includedOnlyMeshes.length > 0) {
  19838. serializationObject.includedOnlyMeshesIds = [];
  19839. this.includedOnlyMeshes.forEach(function (mesh) {
  19840. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19841. });
  19842. }
  19843. // Animations
  19844. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19845. serializationObject.ranges = this.serializeAnimationRanges();
  19846. return serializationObject;
  19847. };
  19848. /**
  19849. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19850. * This new light is named "name" and added to the passed scene.
  19851. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19852. * @param name The friendly name of the light
  19853. * @param scene The scene the new light will belong to
  19854. * @returns the constructor function
  19855. */
  19856. Light.GetConstructorFromName = function (type, name, scene) {
  19857. switch (type) {
  19858. case 0:
  19859. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19860. case 1:
  19861. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19862. case 2:
  19863. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19864. case 3:
  19865. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19866. }
  19867. return null;
  19868. };
  19869. /**
  19870. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19871. * @param parsedLight The JSON representation of the light
  19872. * @param scene The scene to create the parsed light in
  19873. * @returns the created light after parsing
  19874. */
  19875. Light.Parse = function (parsedLight, scene) {
  19876. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19877. if (!constructor) {
  19878. return null;
  19879. }
  19880. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19881. // Inclusion / exclusions
  19882. if (parsedLight.excludedMeshesIds) {
  19883. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19884. }
  19885. if (parsedLight.includedOnlyMeshesIds) {
  19886. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19887. }
  19888. // Parent
  19889. if (parsedLight.parentId) {
  19890. light._waitingParentId = parsedLight.parentId;
  19891. }
  19892. // Animations
  19893. if (parsedLight.animations) {
  19894. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19895. var parsedAnimation = parsedLight.animations[animationIndex];
  19896. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19897. }
  19898. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19899. }
  19900. if (parsedLight.autoAnimate) {
  19901. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19902. }
  19903. return light;
  19904. };
  19905. Light.prototype._hookArrayForExcluded = function (array) {
  19906. var _this = this;
  19907. var oldPush = array.push;
  19908. array.push = function () {
  19909. var items = [];
  19910. for (var _i = 0; _i < arguments.length; _i++) {
  19911. items[_i] = arguments[_i];
  19912. }
  19913. var result = oldPush.apply(array, items);
  19914. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19915. var item = items_1[_a];
  19916. item._resyncLighSource(_this);
  19917. }
  19918. return result;
  19919. };
  19920. var oldSplice = array.splice;
  19921. array.splice = function (index, deleteCount) {
  19922. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19923. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19924. var item = deleted_1[_i];
  19925. item._resyncLighSource(_this);
  19926. }
  19927. return deleted;
  19928. };
  19929. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19930. var item = array_1[_i];
  19931. item._resyncLighSource(this);
  19932. }
  19933. };
  19934. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19935. var _this = this;
  19936. var oldPush = array.push;
  19937. array.push = function () {
  19938. var items = [];
  19939. for (var _i = 0; _i < arguments.length; _i++) {
  19940. items[_i] = arguments[_i];
  19941. }
  19942. var result = oldPush.apply(array, items);
  19943. _this._resyncMeshes();
  19944. return result;
  19945. };
  19946. var oldSplice = array.splice;
  19947. array.splice = function (index, deleteCount) {
  19948. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19949. _this._resyncMeshes();
  19950. return deleted;
  19951. };
  19952. this._resyncMeshes();
  19953. };
  19954. Light.prototype._resyncMeshes = function () {
  19955. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19956. var mesh = _a[_i];
  19957. mesh._resyncLighSource(this);
  19958. }
  19959. };
  19960. /**
  19961. * Forces the meshes to update their light related information in their rendering used effects
  19962. * @ignore Internal Use Only
  19963. */
  19964. Light.prototype._markMeshesAsLightDirty = function () {
  19965. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19966. var mesh = _a[_i];
  19967. if (mesh._lightSources.indexOf(this) !== -1) {
  19968. mesh._markSubMeshesAsLightDirty();
  19969. }
  19970. }
  19971. };
  19972. /**
  19973. * Recomputes the cached photometric scale if needed.
  19974. */
  19975. Light.prototype._computePhotometricScale = function () {
  19976. this._photometricScale = this._getPhotometricScale();
  19977. this.getScene().resetCachedMaterial();
  19978. };
  19979. /**
  19980. * Returns the Photometric Scale according to the light type and intensity mode.
  19981. */
  19982. Light.prototype._getPhotometricScale = function () {
  19983. var photometricScale = 0.0;
  19984. var lightTypeID = this.getTypeID();
  19985. //get photometric mode
  19986. var photometricMode = this.intensityMode;
  19987. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19988. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19989. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19990. }
  19991. else {
  19992. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19993. }
  19994. }
  19995. //compute photometric scale
  19996. switch (lightTypeID) {
  19997. case Light.LIGHTTYPEID_POINTLIGHT:
  19998. case Light.LIGHTTYPEID_SPOTLIGHT:
  19999. switch (photometricMode) {
  20000. case Light.INTENSITYMODE_LUMINOUSPOWER:
  20001. photometricScale = 1.0 / (4.0 * Math.PI);
  20002. break;
  20003. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  20004. photometricScale = 1.0;
  20005. break;
  20006. case Light.INTENSITYMODE_LUMINANCE:
  20007. photometricScale = this.radius * this.radius;
  20008. break;
  20009. }
  20010. break;
  20011. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  20012. switch (photometricMode) {
  20013. case Light.INTENSITYMODE_ILLUMINANCE:
  20014. photometricScale = 1.0;
  20015. break;
  20016. case Light.INTENSITYMODE_LUMINANCE:
  20017. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  20018. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  20019. var apexAngleRadians = this.radius;
  20020. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  20021. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  20022. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  20023. photometricScale = solidAngle;
  20024. break;
  20025. }
  20026. break;
  20027. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  20028. // No fall off in hemisperic light.
  20029. photometricScale = 1.0;
  20030. break;
  20031. }
  20032. return photometricScale;
  20033. };
  20034. /**
  20035. * Reorder the light in the scene according to their defined priority.
  20036. * @ignore Internal Use Only
  20037. */
  20038. Light.prototype._reorderLightsInScene = function () {
  20039. var scene = this.getScene();
  20040. if (this._renderPriority != 0) {
  20041. scene.requireLightSorting = true;
  20042. }
  20043. this.getScene().sortLightsByPriority();
  20044. };
  20045. //lightmapMode Consts
  20046. Light._LIGHTMAP_DEFAULT = 0;
  20047. Light._LIGHTMAP_SPECULAR = 1;
  20048. Light._LIGHTMAP_SHADOWSONLY = 2;
  20049. // Intensity Mode Consts
  20050. Light._INTENSITYMODE_AUTOMATIC = 0;
  20051. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  20052. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  20053. Light._INTENSITYMODE_ILLUMINANCE = 3;
  20054. Light._INTENSITYMODE_LUMINANCE = 4;
  20055. // Light types ids const.
  20056. Light._LIGHTTYPEID_POINTLIGHT = 0;
  20057. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  20058. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  20059. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  20060. __decorate([
  20061. BABYLON.serializeAsColor3()
  20062. ], Light.prototype, "diffuse", void 0);
  20063. __decorate([
  20064. BABYLON.serializeAsColor3()
  20065. ], Light.prototype, "specular", void 0);
  20066. __decorate([
  20067. BABYLON.serialize()
  20068. ], Light.prototype, "intensity", void 0);
  20069. __decorate([
  20070. BABYLON.serialize()
  20071. ], Light.prototype, "range", void 0);
  20072. __decorate([
  20073. BABYLON.serialize()
  20074. ], Light.prototype, "intensityMode", null);
  20075. __decorate([
  20076. BABYLON.serialize()
  20077. ], Light.prototype, "radius", null);
  20078. __decorate([
  20079. BABYLON.serialize()
  20080. ], Light.prototype, "_renderPriority", void 0);
  20081. __decorate([
  20082. BABYLON.expandToProperty("_reorderLightsInScene")
  20083. ], Light.prototype, "renderPriority", void 0);
  20084. __decorate([
  20085. BABYLON.serialize()
  20086. ], Light.prototype, "shadowEnabled", void 0);
  20087. __decorate([
  20088. BABYLON.serialize("excludeWithLayerMask")
  20089. ], Light.prototype, "_excludeWithLayerMask", void 0);
  20090. __decorate([
  20091. BABYLON.serialize("includeOnlyWithLayerMask")
  20092. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  20093. __decorate([
  20094. BABYLON.serialize("lightmapMode")
  20095. ], Light.prototype, "_lightmapMode", void 0);
  20096. return Light;
  20097. }(BABYLON.Node));
  20098. BABYLON.Light = Light;
  20099. })(BABYLON || (BABYLON = {}));
  20100. //# sourceMappingURL=babylon.light.js.map
  20101. "use strict";
  20102. var BABYLON;
  20103. (function (BABYLON) {
  20104. var Camera = /** @class */ (function (_super) {
  20105. __extends(Camera, _super);
  20106. function Camera(name, position, scene) {
  20107. var _this = _super.call(this, name, scene) || this;
  20108. /**
  20109. * The vector the camera should consider as up.
  20110. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  20111. */
  20112. _this.upVector = BABYLON.Vector3.Up();
  20113. _this.orthoLeft = null;
  20114. _this.orthoRight = null;
  20115. _this.orthoBottom = null;
  20116. _this.orthoTop = null;
  20117. /**
  20118. * FOV is set in Radians. (default is 0.8)
  20119. */
  20120. _this.fov = 0.8;
  20121. _this.minZ = 1;
  20122. _this.maxZ = 10000.0;
  20123. _this.inertia = 0.9;
  20124. _this.mode = Camera.PERSPECTIVE_CAMERA;
  20125. _this.isIntermediate = false;
  20126. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  20127. /**
  20128. * Restricts the camera to viewing objects with the same layerMask.
  20129. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  20130. */
  20131. _this.layerMask = 0x0FFFFFFF;
  20132. /**
  20133. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  20134. */
  20135. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  20136. // Camera rig members
  20137. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  20138. _this._rigCameras = new Array();
  20139. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  20140. _this._skipRendering = false;
  20141. _this.customRenderTargets = new Array();
  20142. // Observables
  20143. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  20144. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  20145. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  20146. _this.onRestoreStateObservable = new BABYLON.Observable();
  20147. // Cache
  20148. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  20149. _this._projectionMatrix = new BABYLON.Matrix();
  20150. _this._doNotComputeProjectionMatrix = false;
  20151. _this._postProcesses = new Array();
  20152. _this._transformMatrix = BABYLON.Matrix.Zero();
  20153. _this._activeMeshes = new BABYLON.SmartArray(256);
  20154. _this._globalPosition = BABYLON.Vector3.Zero();
  20155. _this._refreshFrustumPlanes = true;
  20156. _this.getScene().addCamera(_this);
  20157. if (!_this.getScene().activeCamera) {
  20158. _this.getScene().activeCamera = _this;
  20159. }
  20160. _this.position = position;
  20161. return _this;
  20162. }
  20163. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  20164. get: function () {
  20165. return Camera._PERSPECTIVE_CAMERA;
  20166. },
  20167. enumerable: true,
  20168. configurable: true
  20169. });
  20170. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  20171. get: function () {
  20172. return Camera._ORTHOGRAPHIC_CAMERA;
  20173. },
  20174. enumerable: true,
  20175. configurable: true
  20176. });
  20177. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  20178. /**
  20179. * This is the default FOV mode for perspective cameras.
  20180. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  20181. *
  20182. */
  20183. get: function () {
  20184. return Camera._FOVMODE_VERTICAL_FIXED;
  20185. },
  20186. enumerable: true,
  20187. configurable: true
  20188. });
  20189. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  20190. /**
  20191. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  20192. *
  20193. */
  20194. get: function () {
  20195. return Camera._FOVMODE_HORIZONTAL_FIXED;
  20196. },
  20197. enumerable: true,
  20198. configurable: true
  20199. });
  20200. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  20201. get: function () {
  20202. return Camera._RIG_MODE_NONE;
  20203. },
  20204. enumerable: true,
  20205. configurable: true
  20206. });
  20207. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  20208. get: function () {
  20209. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  20210. },
  20211. enumerable: true,
  20212. configurable: true
  20213. });
  20214. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  20215. get: function () {
  20216. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  20217. },
  20218. enumerable: true,
  20219. configurable: true
  20220. });
  20221. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  20222. get: function () {
  20223. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20224. },
  20225. enumerable: true,
  20226. configurable: true
  20227. });
  20228. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  20229. get: function () {
  20230. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  20231. },
  20232. enumerable: true,
  20233. configurable: true
  20234. });
  20235. Object.defineProperty(Camera, "RIG_MODE_VR", {
  20236. get: function () {
  20237. return Camera._RIG_MODE_VR;
  20238. },
  20239. enumerable: true,
  20240. configurable: true
  20241. });
  20242. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  20243. get: function () {
  20244. return Camera._RIG_MODE_WEBVR;
  20245. },
  20246. enumerable: true,
  20247. configurable: true
  20248. });
  20249. /**
  20250. * Store current camera state (fov, position, etc..)
  20251. */
  20252. Camera.prototype.storeState = function () {
  20253. this._stateStored = true;
  20254. this._storedFov = this.fov;
  20255. return this;
  20256. };
  20257. /**
  20258. * Restores the camera state values if it has been stored. You must call storeState() first
  20259. */
  20260. Camera.prototype._restoreStateValues = function () {
  20261. if (!this._stateStored) {
  20262. return false;
  20263. }
  20264. this.fov = this._storedFov;
  20265. return true;
  20266. };
  20267. /**
  20268. * Restored camera state. You must call storeState() first
  20269. */
  20270. Camera.prototype.restoreState = function () {
  20271. if (this._restoreStateValues()) {
  20272. this.onRestoreStateObservable.notifyObservers(this);
  20273. return true;
  20274. }
  20275. return false;
  20276. };
  20277. Camera.prototype.getClassName = function () {
  20278. return "Camera";
  20279. };
  20280. /**
  20281. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20282. */
  20283. Camera.prototype.toString = function (fullDetails) {
  20284. var ret = "Name: " + this.name;
  20285. ret += ", type: " + this.getClassName();
  20286. if (this.animations) {
  20287. for (var i = 0; i < this.animations.length; i++) {
  20288. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20289. }
  20290. }
  20291. if (fullDetails) {
  20292. }
  20293. return ret;
  20294. };
  20295. Object.defineProperty(Camera.prototype, "globalPosition", {
  20296. get: function () {
  20297. return this._globalPosition;
  20298. },
  20299. enumerable: true,
  20300. configurable: true
  20301. });
  20302. Camera.prototype.getActiveMeshes = function () {
  20303. return this._activeMeshes;
  20304. };
  20305. Camera.prototype.isActiveMesh = function (mesh) {
  20306. return (this._activeMeshes.indexOf(mesh) !== -1);
  20307. };
  20308. //Cache
  20309. Camera.prototype._initCache = function () {
  20310. _super.prototype._initCache.call(this);
  20311. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20312. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20313. this._cache.mode = undefined;
  20314. this._cache.minZ = undefined;
  20315. this._cache.maxZ = undefined;
  20316. this._cache.fov = undefined;
  20317. this._cache.fovMode = undefined;
  20318. this._cache.aspectRatio = undefined;
  20319. this._cache.orthoLeft = undefined;
  20320. this._cache.orthoRight = undefined;
  20321. this._cache.orthoBottom = undefined;
  20322. this._cache.orthoTop = undefined;
  20323. this._cache.renderWidth = undefined;
  20324. this._cache.renderHeight = undefined;
  20325. };
  20326. Camera.prototype._updateCache = function (ignoreParentClass) {
  20327. if (!ignoreParentClass) {
  20328. _super.prototype._updateCache.call(this);
  20329. }
  20330. this._cache.position.copyFrom(this.position);
  20331. this._cache.upVector.copyFrom(this.upVector);
  20332. };
  20333. // Synchronized
  20334. Camera.prototype._isSynchronized = function () {
  20335. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  20336. };
  20337. Camera.prototype._isSynchronizedViewMatrix = function () {
  20338. if (!_super.prototype._isSynchronized.call(this))
  20339. return false;
  20340. return this._cache.position.equals(this.position)
  20341. && this._cache.upVector.equals(this.upVector)
  20342. && this.isSynchronizedWithParent();
  20343. };
  20344. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  20345. var check = this._cache.mode === this.mode
  20346. && this._cache.minZ === this.minZ
  20347. && this._cache.maxZ === this.maxZ;
  20348. if (!check) {
  20349. return false;
  20350. }
  20351. var engine = this.getEngine();
  20352. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20353. check = this._cache.fov === this.fov
  20354. && this._cache.fovMode === this.fovMode
  20355. && this._cache.aspectRatio === engine.getAspectRatio(this);
  20356. }
  20357. else {
  20358. check = this._cache.orthoLeft === this.orthoLeft
  20359. && this._cache.orthoRight === this.orthoRight
  20360. && this._cache.orthoBottom === this.orthoBottom
  20361. && this._cache.orthoTop === this.orthoTop
  20362. && this._cache.renderWidth === engine.getRenderWidth()
  20363. && this._cache.renderHeight === engine.getRenderHeight();
  20364. }
  20365. return check;
  20366. };
  20367. // Controls
  20368. Camera.prototype.attachControl = function (element, noPreventDefault) {
  20369. };
  20370. Camera.prototype.detachControl = function (element) {
  20371. };
  20372. Camera.prototype.update = function () {
  20373. this._checkInputs();
  20374. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20375. this._updateRigCameras();
  20376. }
  20377. };
  20378. Camera.prototype._checkInputs = function () {
  20379. this.onAfterCheckInputsObservable.notifyObservers(this);
  20380. };
  20381. Object.defineProperty(Camera.prototype, "rigCameras", {
  20382. get: function () {
  20383. return this._rigCameras;
  20384. },
  20385. enumerable: true,
  20386. configurable: true
  20387. });
  20388. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  20389. get: function () {
  20390. return this._rigPostProcess;
  20391. },
  20392. enumerable: true,
  20393. configurable: true
  20394. });
  20395. /**
  20396. * Internal, gets the first post proces.
  20397. * @returns the first post process to be run on this camera.
  20398. */
  20399. Camera.prototype._getFirstPostProcess = function () {
  20400. for (var pp in this._postProcesses) {
  20401. if (this._postProcesses[pp] !== null) {
  20402. return this._postProcesses[pp];
  20403. }
  20404. }
  20405. return null;
  20406. };
  20407. Camera.prototype._cascadePostProcessesToRigCams = function () {
  20408. // invalidate framebuffer
  20409. var firstPostProcess = this._getFirstPostProcess();
  20410. if (firstPostProcess) {
  20411. firstPostProcess.markTextureDirty();
  20412. }
  20413. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20414. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20415. var cam = this._rigCameras[i];
  20416. var rigPostProcess = cam._rigPostProcess;
  20417. // for VR rig, there does not have to be a post process
  20418. if (rigPostProcess) {
  20419. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20420. if (isPass) {
  20421. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20422. cam.isIntermediate = this._postProcesses.length === 0;
  20423. }
  20424. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20425. rigPostProcess.markTextureDirty();
  20426. }
  20427. else {
  20428. cam._postProcesses = this._postProcesses.slice(0);
  20429. }
  20430. }
  20431. };
  20432. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20433. if (insertAt === void 0) { insertAt = null; }
  20434. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20435. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20436. return 0;
  20437. }
  20438. if (insertAt == null || insertAt < 0) {
  20439. this._postProcesses.push(postProcess);
  20440. }
  20441. else if (this._postProcesses[insertAt] === null) {
  20442. this._postProcesses[insertAt] = postProcess;
  20443. }
  20444. else {
  20445. this._postProcesses.splice(insertAt, 0, postProcess);
  20446. }
  20447. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20448. return this._postProcesses.indexOf(postProcess);
  20449. };
  20450. Camera.prototype.detachPostProcess = function (postProcess) {
  20451. var idx = this._postProcesses.indexOf(postProcess);
  20452. if (idx !== -1) {
  20453. this._postProcesses[idx] = null;
  20454. }
  20455. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20456. };
  20457. Camera.prototype.getWorldMatrix = function () {
  20458. if (!this._worldMatrix) {
  20459. this._worldMatrix = BABYLON.Matrix.Identity();
  20460. }
  20461. var viewMatrix = this.getViewMatrix();
  20462. viewMatrix.invertToRef(this._worldMatrix);
  20463. return this._worldMatrix;
  20464. };
  20465. Camera.prototype._getViewMatrix = function () {
  20466. return BABYLON.Matrix.Identity();
  20467. };
  20468. Camera.prototype.getViewMatrix = function (force) {
  20469. if (!force && this._isSynchronizedViewMatrix()) {
  20470. return this._computedViewMatrix;
  20471. }
  20472. this.updateCache();
  20473. this._computedViewMatrix = this._getViewMatrix();
  20474. this._currentRenderId = this.getScene().getRenderId();
  20475. this._refreshFrustumPlanes = true;
  20476. if (!this.parent || !this.parent.getWorldMatrix) {
  20477. this._globalPosition.copyFrom(this.position);
  20478. }
  20479. else {
  20480. if (!this._worldMatrix) {
  20481. this._worldMatrix = BABYLON.Matrix.Identity();
  20482. }
  20483. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20484. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20485. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20486. this._computedViewMatrix.invert();
  20487. this._markSyncedWithParent();
  20488. }
  20489. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20490. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20491. }
  20492. this.onViewMatrixChangedObservable.notifyObservers(this);
  20493. return this._computedViewMatrix;
  20494. };
  20495. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20496. this._doNotComputeProjectionMatrix = true;
  20497. if (projection !== undefined) {
  20498. this._projectionMatrix = projection;
  20499. }
  20500. };
  20501. ;
  20502. Camera.prototype.unfreezeProjectionMatrix = function () {
  20503. this._doNotComputeProjectionMatrix = false;
  20504. };
  20505. ;
  20506. Camera.prototype.getProjectionMatrix = function (force) {
  20507. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20508. return this._projectionMatrix;
  20509. }
  20510. // Cache
  20511. this._cache.mode = this.mode;
  20512. this._cache.minZ = this.minZ;
  20513. this._cache.maxZ = this.maxZ;
  20514. // Matrix
  20515. this._refreshFrustumPlanes = true;
  20516. var engine = this.getEngine();
  20517. var scene = this.getScene();
  20518. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20519. this._cache.fov = this.fov;
  20520. this._cache.fovMode = this.fovMode;
  20521. this._cache.aspectRatio = engine.getAspectRatio(this);
  20522. if (this.minZ <= 0) {
  20523. this.minZ = 0.1;
  20524. }
  20525. if (scene.useRightHandedSystem) {
  20526. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20527. }
  20528. else {
  20529. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20530. }
  20531. }
  20532. else {
  20533. var halfWidth = engine.getRenderWidth() / 2.0;
  20534. var halfHeight = engine.getRenderHeight() / 2.0;
  20535. if (scene.useRightHandedSystem) {
  20536. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20537. }
  20538. else {
  20539. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20540. }
  20541. this._cache.orthoLeft = this.orthoLeft;
  20542. this._cache.orthoRight = this.orthoRight;
  20543. this._cache.orthoBottom = this.orthoBottom;
  20544. this._cache.orthoTop = this.orthoTop;
  20545. this._cache.renderWidth = engine.getRenderWidth();
  20546. this._cache.renderHeight = engine.getRenderHeight();
  20547. }
  20548. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20549. return this._projectionMatrix;
  20550. };
  20551. Camera.prototype.getTranformationMatrix = function () {
  20552. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20553. return this._transformMatrix;
  20554. };
  20555. Camera.prototype.updateFrustumPlanes = function () {
  20556. if (!this._refreshFrustumPlanes) {
  20557. return;
  20558. }
  20559. this.getTranformationMatrix();
  20560. if (!this._frustumPlanes) {
  20561. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20562. }
  20563. else {
  20564. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20565. }
  20566. this._refreshFrustumPlanes = false;
  20567. };
  20568. Camera.prototype.isInFrustum = function (target) {
  20569. this.updateFrustumPlanes();
  20570. return target.isInFrustum(this._frustumPlanes);
  20571. };
  20572. Camera.prototype.isCompletelyInFrustum = function (target) {
  20573. this.updateFrustumPlanes();
  20574. return target.isCompletelyInFrustum(this._frustumPlanes);
  20575. };
  20576. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20577. if (length === void 0) { length = 100; }
  20578. if (!transform) {
  20579. transform = this.getWorldMatrix();
  20580. }
  20581. if (!origin) {
  20582. origin = this.position;
  20583. }
  20584. var forward = new BABYLON.Vector3(0, 0, 1);
  20585. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20586. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20587. return new BABYLON.Ray(origin, direction, length);
  20588. };
  20589. /**
  20590. * Releases resources associated with this node.
  20591. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20592. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20593. */
  20594. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20595. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20596. // Observables
  20597. this.onViewMatrixChangedObservable.clear();
  20598. this.onProjectionMatrixChangedObservable.clear();
  20599. this.onAfterCheckInputsObservable.clear();
  20600. this.onRestoreStateObservable.clear();
  20601. // Inputs
  20602. if (this.inputs) {
  20603. this.inputs.clear();
  20604. }
  20605. // Animations
  20606. this.getScene().stopAnimation(this);
  20607. // Remove from scene
  20608. this.getScene().removeCamera(this);
  20609. while (this._rigCameras.length > 0) {
  20610. var camera = this._rigCameras.pop();
  20611. if (camera) {
  20612. camera.dispose();
  20613. }
  20614. }
  20615. // Postprocesses
  20616. if (this._rigPostProcess) {
  20617. this._rigPostProcess.dispose(this);
  20618. this._rigPostProcess = null;
  20619. this._postProcesses = [];
  20620. }
  20621. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20622. this._rigPostProcess = null;
  20623. this._postProcesses = [];
  20624. }
  20625. else {
  20626. var i = this._postProcesses.length;
  20627. while (--i >= 0) {
  20628. var postProcess = this._postProcesses[i];
  20629. if (postProcess) {
  20630. postProcess.dispose(this);
  20631. }
  20632. }
  20633. }
  20634. // Render targets
  20635. var i = this.customRenderTargets.length;
  20636. while (--i >= 0) {
  20637. this.customRenderTargets[i].dispose();
  20638. }
  20639. this.customRenderTargets = [];
  20640. // Active Meshes
  20641. this._activeMeshes.dispose();
  20642. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20643. };
  20644. Object.defineProperty(Camera.prototype, "leftCamera", {
  20645. // ---- Camera rigs section ----
  20646. get: function () {
  20647. if (this._rigCameras.length < 1) {
  20648. return null;
  20649. }
  20650. return this._rigCameras[0];
  20651. },
  20652. enumerable: true,
  20653. configurable: true
  20654. });
  20655. Object.defineProperty(Camera.prototype, "rightCamera", {
  20656. get: function () {
  20657. if (this._rigCameras.length < 2) {
  20658. return null;
  20659. }
  20660. return this._rigCameras[1];
  20661. },
  20662. enumerable: true,
  20663. configurable: true
  20664. });
  20665. Camera.prototype.getLeftTarget = function () {
  20666. if (this._rigCameras.length < 1) {
  20667. return null;
  20668. }
  20669. return this._rigCameras[0].getTarget();
  20670. };
  20671. Camera.prototype.getRightTarget = function () {
  20672. if (this._rigCameras.length < 2) {
  20673. return null;
  20674. }
  20675. return this._rigCameras[1].getTarget();
  20676. };
  20677. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20678. if (this.cameraRigMode === mode) {
  20679. return;
  20680. }
  20681. while (this._rigCameras.length > 0) {
  20682. var camera = this._rigCameras.pop();
  20683. if (camera) {
  20684. camera.dispose();
  20685. }
  20686. }
  20687. this.cameraRigMode = mode;
  20688. this._cameraRigParams = {};
  20689. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20690. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20691. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20692. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20693. // create the rig cameras, unless none
  20694. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20695. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20696. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20697. if (leftCamera && rightCamera) {
  20698. this._rigCameras.push(leftCamera);
  20699. this._rigCameras.push(rightCamera);
  20700. }
  20701. }
  20702. switch (this.cameraRigMode) {
  20703. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20704. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20705. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20706. break;
  20707. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20708. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20709. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20710. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20711. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20712. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20713. break;
  20714. case Camera.RIG_MODE_VR:
  20715. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20716. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20717. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20718. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20719. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20720. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20721. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20722. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20723. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20724. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20725. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20726. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20727. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20728. if (metrics.compensateDistortion) {
  20729. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20730. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20731. }
  20732. break;
  20733. case Camera.RIG_MODE_WEBVR:
  20734. if (rigParams.vrDisplay) {
  20735. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20736. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20737. //Left eye
  20738. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20739. this._rigCameras[0].setCameraRigParameter("left", true);
  20740. //leaving this for future reference
  20741. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20742. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20743. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20744. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20745. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20746. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20747. this._rigCameras[0].parent = this;
  20748. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20749. //Right eye
  20750. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20751. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20752. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20753. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20754. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20755. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20756. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20757. this._rigCameras[1].parent = this;
  20758. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20759. if (Camera.UseAlternateWebVRRendering) {
  20760. this._rigCameras[1]._skipRendering = true;
  20761. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20762. }
  20763. }
  20764. break;
  20765. }
  20766. this._cascadePostProcessesToRigCams();
  20767. this.update();
  20768. };
  20769. Camera.prototype._getVRProjectionMatrix = function () {
  20770. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20771. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20772. return this._projectionMatrix;
  20773. };
  20774. Camera.prototype._updateCameraRotationMatrix = function () {
  20775. //Here for WebVR
  20776. };
  20777. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20778. //Here for WebVR
  20779. };
  20780. /**
  20781. * This function MUST be overwritten by the different WebVR cameras available.
  20782. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20783. */
  20784. Camera.prototype._getWebVRProjectionMatrix = function () {
  20785. return BABYLON.Matrix.Identity();
  20786. };
  20787. /**
  20788. * This function MUST be overwritten by the different WebVR cameras available.
  20789. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20790. */
  20791. Camera.prototype._getWebVRViewMatrix = function () {
  20792. return BABYLON.Matrix.Identity();
  20793. };
  20794. Camera.prototype.setCameraRigParameter = function (name, value) {
  20795. if (!this._cameraRigParams) {
  20796. this._cameraRigParams = {};
  20797. }
  20798. this._cameraRigParams[name] = value;
  20799. //provisionnally:
  20800. if (name === "interaxialDistance") {
  20801. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20802. }
  20803. };
  20804. /**
  20805. * needs to be overridden by children so sub has required properties to be copied
  20806. */
  20807. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20808. return null;
  20809. };
  20810. /**
  20811. * May need to be overridden by children
  20812. */
  20813. Camera.prototype._updateRigCameras = function () {
  20814. for (var i = 0; i < this._rigCameras.length; i++) {
  20815. this._rigCameras[i].minZ = this.minZ;
  20816. this._rigCameras[i].maxZ = this.maxZ;
  20817. this._rigCameras[i].fov = this.fov;
  20818. }
  20819. // only update viewport when ANAGLYPH
  20820. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20821. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20822. }
  20823. };
  20824. Camera.prototype._setupInputs = function () {
  20825. };
  20826. Camera.prototype.serialize = function () {
  20827. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20828. // Type
  20829. serializationObject.type = this.getClassName();
  20830. // Parent
  20831. if (this.parent) {
  20832. serializationObject.parentId = this.parent.id;
  20833. }
  20834. if (this.inputs) {
  20835. this.inputs.serialize(serializationObject);
  20836. }
  20837. // Animations
  20838. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20839. serializationObject.ranges = this.serializeAnimationRanges();
  20840. return serializationObject;
  20841. };
  20842. Camera.prototype.clone = function (name) {
  20843. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20844. };
  20845. Camera.prototype.getDirection = function (localAxis) {
  20846. var result = BABYLON.Vector3.Zero();
  20847. this.getDirectionToRef(localAxis, result);
  20848. return result;
  20849. };
  20850. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20851. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20852. };
  20853. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20854. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20855. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20856. switch (type) {
  20857. case "ArcRotateCamera":
  20858. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20859. case "DeviceOrientationCamera":
  20860. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20861. case "FollowCamera":
  20862. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20863. case "ArcFollowCamera":
  20864. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20865. case "GamepadCamera":
  20866. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20867. case "TouchCamera":
  20868. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20869. case "VirtualJoysticksCamera":
  20870. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20871. case "WebVRFreeCamera":
  20872. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20873. case "WebVRGamepadCamera":
  20874. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20875. case "VRDeviceOrientationFreeCamera":
  20876. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20877. case "VRDeviceOrientationGamepadCamera":
  20878. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20879. case "AnaglyphArcRotateCamera":
  20880. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20881. case "AnaglyphFreeCamera":
  20882. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20883. case "AnaglyphGamepadCamera":
  20884. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20885. case "AnaglyphUniversalCamera":
  20886. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20887. case "StereoscopicArcRotateCamera":
  20888. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20889. case "StereoscopicFreeCamera":
  20890. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20891. case "StereoscopicGamepadCamera":
  20892. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20893. case "StereoscopicUniversalCamera":
  20894. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20895. case "FreeCamera":// Forcing Universal here
  20896. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20897. default:// Universal Camera is the default value
  20898. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20899. }
  20900. };
  20901. Camera.prototype.computeWorldMatrix = function () {
  20902. return this.getWorldMatrix();
  20903. };
  20904. Camera.Parse = function (parsedCamera, scene) {
  20905. var type = parsedCamera.type;
  20906. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20907. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20908. // Parent
  20909. if (parsedCamera.parentId) {
  20910. camera._waitingParentId = parsedCamera.parentId;
  20911. }
  20912. //If camera has an input manager, let it parse inputs settings
  20913. if (camera.inputs) {
  20914. camera.inputs.parse(parsedCamera);
  20915. camera._setupInputs();
  20916. }
  20917. if (camera.setPosition) {
  20918. camera.position.copyFromFloats(0, 0, 0);
  20919. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20920. }
  20921. // Target
  20922. if (parsedCamera.target) {
  20923. if (camera.setTarget) {
  20924. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20925. }
  20926. }
  20927. // Apply 3d rig, when found
  20928. if (parsedCamera.cameraRigMode) {
  20929. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20930. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20931. }
  20932. // Animations
  20933. if (parsedCamera.animations) {
  20934. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20935. var parsedAnimation = parsedCamera.animations[animationIndex];
  20936. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20937. }
  20938. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20939. }
  20940. if (parsedCamera.autoAnimate) {
  20941. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20942. }
  20943. return camera;
  20944. };
  20945. // Statics
  20946. Camera._PERSPECTIVE_CAMERA = 0;
  20947. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20948. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20949. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20950. Camera._RIG_MODE_NONE = 0;
  20951. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20952. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20953. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20954. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20955. Camera._RIG_MODE_VR = 20;
  20956. Camera._RIG_MODE_WEBVR = 21;
  20957. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20958. Camera.UseAlternateWebVRRendering = false;
  20959. __decorate([
  20960. BABYLON.serializeAsVector3()
  20961. ], Camera.prototype, "position", void 0);
  20962. __decorate([
  20963. BABYLON.serializeAsVector3()
  20964. ], Camera.prototype, "upVector", void 0);
  20965. __decorate([
  20966. BABYLON.serialize()
  20967. ], Camera.prototype, "orthoLeft", void 0);
  20968. __decorate([
  20969. BABYLON.serialize()
  20970. ], Camera.prototype, "orthoRight", void 0);
  20971. __decorate([
  20972. BABYLON.serialize()
  20973. ], Camera.prototype, "orthoBottom", void 0);
  20974. __decorate([
  20975. BABYLON.serialize()
  20976. ], Camera.prototype, "orthoTop", void 0);
  20977. __decorate([
  20978. BABYLON.serialize()
  20979. ], Camera.prototype, "fov", void 0);
  20980. __decorate([
  20981. BABYLON.serialize()
  20982. ], Camera.prototype, "minZ", void 0);
  20983. __decorate([
  20984. BABYLON.serialize()
  20985. ], Camera.prototype, "maxZ", void 0);
  20986. __decorate([
  20987. BABYLON.serialize()
  20988. ], Camera.prototype, "inertia", void 0);
  20989. __decorate([
  20990. BABYLON.serialize()
  20991. ], Camera.prototype, "mode", void 0);
  20992. __decorate([
  20993. BABYLON.serialize()
  20994. ], Camera.prototype, "layerMask", void 0);
  20995. __decorate([
  20996. BABYLON.serialize()
  20997. ], Camera.prototype, "fovMode", void 0);
  20998. __decorate([
  20999. BABYLON.serialize()
  21000. ], Camera.prototype, "cameraRigMode", void 0);
  21001. __decorate([
  21002. BABYLON.serialize()
  21003. ], Camera.prototype, "interaxialDistance", void 0);
  21004. __decorate([
  21005. BABYLON.serialize()
  21006. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  21007. return Camera;
  21008. }(BABYLON.Node));
  21009. BABYLON.Camera = Camera;
  21010. })(BABYLON || (BABYLON = {}));
  21011. //# sourceMappingURL=babylon.camera.js.map
  21012. "use strict";
  21013. var BABYLON;
  21014. (function (BABYLON) {
  21015. var RenderingManager = /** @class */ (function () {
  21016. function RenderingManager(scene) {
  21017. this._renderingGroups = new Array();
  21018. this._autoClearDepthStencil = {};
  21019. this._customOpaqueSortCompareFn = {};
  21020. this._customAlphaTestSortCompareFn = {};
  21021. this._customTransparentSortCompareFn = {};
  21022. this._renderinGroupInfo = null;
  21023. this._scene = scene;
  21024. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  21025. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  21026. }
  21027. }
  21028. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  21029. if (depth === void 0) { depth = true; }
  21030. if (stencil === void 0) { stencil = true; }
  21031. if (this._depthStencilBufferAlreadyCleaned) {
  21032. return;
  21033. }
  21034. this._scene.getEngine().clear(null, false, depth, stencil);
  21035. this._depthStencilBufferAlreadyCleaned = true;
  21036. };
  21037. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  21038. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  21039. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  21040. var info = null;
  21041. if (observable) {
  21042. if (!this._renderinGroupInfo) {
  21043. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  21044. }
  21045. info = this._renderinGroupInfo;
  21046. info.scene = this._scene;
  21047. info.camera = this._scene.activeCamera;
  21048. }
  21049. // Dispatch sprites
  21050. if (renderSprites) {
  21051. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  21052. var manager = this._scene.spriteManagers[index];
  21053. this.dispatchSprites(manager);
  21054. }
  21055. }
  21056. // Render
  21057. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21058. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  21059. var renderingGroup = this._renderingGroups[index];
  21060. if (!renderingGroup && !observable)
  21061. continue;
  21062. var renderingGroupMask = 0;
  21063. // Fire PRECLEAR stage
  21064. if (observable && info) {
  21065. renderingGroupMask = Math.pow(2, index);
  21066. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  21067. info.renderingGroupId = index;
  21068. observable.notifyObservers(info, renderingGroupMask);
  21069. }
  21070. // Clear depth/stencil if needed
  21071. if (RenderingManager.AUTOCLEAR) {
  21072. var autoClear = this._autoClearDepthStencil[index];
  21073. if (autoClear && autoClear.autoClear) {
  21074. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  21075. }
  21076. }
  21077. if (observable && info) {
  21078. // Fire PREOPAQUE stage
  21079. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  21080. observable.notifyObservers(info, renderingGroupMask);
  21081. // Fire PRETRANSPARENT stage
  21082. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  21083. observable.notifyObservers(info, renderingGroupMask);
  21084. }
  21085. if (renderingGroup)
  21086. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  21087. // Fire POSTTRANSPARENT stage
  21088. if (observable && info) {
  21089. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  21090. observable.notifyObservers(info, renderingGroupMask);
  21091. }
  21092. }
  21093. };
  21094. RenderingManager.prototype.reset = function () {
  21095. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21096. var renderingGroup = this._renderingGroups[index];
  21097. if (renderingGroup) {
  21098. renderingGroup.prepare();
  21099. }
  21100. }
  21101. };
  21102. RenderingManager.prototype.dispose = function () {
  21103. this.freeRenderingGroups();
  21104. this._renderingGroups.length = 0;
  21105. };
  21106. /**
  21107. * Clear the info related to rendering groups preventing retention points during dispose.
  21108. */
  21109. RenderingManager.prototype.freeRenderingGroups = function () {
  21110. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21111. var renderingGroup = this._renderingGroups[index];
  21112. if (renderingGroup) {
  21113. renderingGroup.dispose();
  21114. }
  21115. }
  21116. };
  21117. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  21118. if (this._renderingGroups[renderingGroupId] === undefined) {
  21119. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  21120. }
  21121. };
  21122. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  21123. var renderingGroupId = spriteManager.renderingGroupId || 0;
  21124. this._prepareRenderingGroup(renderingGroupId);
  21125. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  21126. };
  21127. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  21128. var renderingGroupId = particleSystem.renderingGroupId || 0;
  21129. this._prepareRenderingGroup(renderingGroupId);
  21130. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  21131. };
  21132. /**
  21133. * @param subMesh The submesh to dispatch
  21134. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21135. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21136. */
  21137. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  21138. if (mesh === undefined) {
  21139. mesh = subMesh.getMesh();
  21140. }
  21141. var renderingGroupId = mesh.renderingGroupId || 0;
  21142. this._prepareRenderingGroup(renderingGroupId);
  21143. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  21144. };
  21145. /**
  21146. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21147. * This allowed control for front to back rendering or reversly depending of the special needs.
  21148. *
  21149. * @param renderingGroupId The rendering group id corresponding to its index
  21150. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21151. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21152. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21153. */
  21154. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21155. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21156. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21157. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21158. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  21159. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  21160. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  21161. if (this._renderingGroups[renderingGroupId]) {
  21162. var group = this._renderingGroups[renderingGroupId];
  21163. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  21164. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  21165. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  21166. }
  21167. };
  21168. /**
  21169. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21170. *
  21171. * @param renderingGroupId The rendering group id corresponding to its index
  21172. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21173. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21174. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21175. */
  21176. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21177. if (depth === void 0) { depth = true; }
  21178. if (stencil === void 0) { stencil = true; }
  21179. this._autoClearDepthStencil[renderingGroupId] = {
  21180. autoClear: autoClearDepthStencil,
  21181. depth: depth,
  21182. stencil: stencil
  21183. };
  21184. };
  21185. /**
  21186. * The max id used for rendering groups (not included)
  21187. */
  21188. RenderingManager.MAX_RENDERINGGROUPS = 4;
  21189. /**
  21190. * The min id used for rendering groups (included)
  21191. */
  21192. RenderingManager.MIN_RENDERINGGROUPS = 0;
  21193. /**
  21194. * Used to globally prevent autoclearing scenes.
  21195. */
  21196. RenderingManager.AUTOCLEAR = true;
  21197. return RenderingManager;
  21198. }());
  21199. BABYLON.RenderingManager = RenderingManager;
  21200. })(BABYLON || (BABYLON = {}));
  21201. //# sourceMappingURL=babylon.renderingManager.js.map
  21202. "use strict";
  21203. var BABYLON;
  21204. (function (BABYLON) {
  21205. var RenderingGroup = /** @class */ (function () {
  21206. /**
  21207. * Creates a new rendering group.
  21208. * @param index The rendering group index
  21209. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  21210. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  21211. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  21212. */
  21213. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21214. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21215. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21216. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21217. this.index = index;
  21218. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  21219. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  21220. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  21221. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  21222. this._particleSystems = new BABYLON.SmartArray(256);
  21223. this._spriteManagers = new BABYLON.SmartArray(256);
  21224. this._edgesRenderers = new BABYLON.SmartArray(16);
  21225. this._scene = scene;
  21226. this.opaqueSortCompareFn = opaqueSortCompareFn;
  21227. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  21228. this.transparentSortCompareFn = transparentSortCompareFn;
  21229. }
  21230. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  21231. /**
  21232. * Set the opaque sort comparison function.
  21233. * If null the sub meshes will be render in the order they were created
  21234. */
  21235. set: function (value) {
  21236. this._opaqueSortCompareFn = value;
  21237. if (value) {
  21238. this._renderOpaque = this.renderOpaqueSorted;
  21239. }
  21240. else {
  21241. this._renderOpaque = RenderingGroup.renderUnsorted;
  21242. }
  21243. },
  21244. enumerable: true,
  21245. configurable: true
  21246. });
  21247. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  21248. /**
  21249. * Set the alpha test sort comparison function.
  21250. * If null the sub meshes will be render in the order they were created
  21251. */
  21252. set: function (value) {
  21253. this._alphaTestSortCompareFn = value;
  21254. if (value) {
  21255. this._renderAlphaTest = this.renderAlphaTestSorted;
  21256. }
  21257. else {
  21258. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  21259. }
  21260. },
  21261. enumerable: true,
  21262. configurable: true
  21263. });
  21264. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  21265. /**
  21266. * Set the transparent sort comparison function.
  21267. * If null the sub meshes will be render in the order they were created
  21268. */
  21269. set: function (value) {
  21270. if (value) {
  21271. this._transparentSortCompareFn = value;
  21272. }
  21273. else {
  21274. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  21275. }
  21276. this._renderTransparent = this.renderTransparentSorted;
  21277. },
  21278. enumerable: true,
  21279. configurable: true
  21280. });
  21281. /**
  21282. * Render all the sub meshes contained in the group.
  21283. * @param customRenderFunction Used to override the default render behaviour of the group.
  21284. * @returns true if rendered some submeshes.
  21285. */
  21286. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  21287. if (customRenderFunction) {
  21288. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  21289. return;
  21290. }
  21291. var engine = this._scene.getEngine();
  21292. // Depth only
  21293. if (this._depthOnlySubMeshes.length !== 0) {
  21294. engine.setColorWrite(false);
  21295. this._renderAlphaTest(this._depthOnlySubMeshes);
  21296. engine.setColorWrite(true);
  21297. }
  21298. // Opaque
  21299. if (this._opaqueSubMeshes.length !== 0) {
  21300. this._renderOpaque(this._opaqueSubMeshes);
  21301. }
  21302. // Alpha test
  21303. if (this._alphaTestSubMeshes.length !== 0) {
  21304. this._renderAlphaTest(this._alphaTestSubMeshes);
  21305. }
  21306. var stencilState = engine.getStencilBuffer();
  21307. engine.setStencilBuffer(false);
  21308. // Sprites
  21309. if (renderSprites) {
  21310. this._renderSprites();
  21311. }
  21312. // Particles
  21313. if (renderParticles) {
  21314. this._renderParticles(activeMeshes);
  21315. }
  21316. if (this.onBeforeTransparentRendering) {
  21317. this.onBeforeTransparentRendering();
  21318. }
  21319. // Transparent
  21320. if (this._transparentSubMeshes.length !== 0) {
  21321. this._renderTransparent(this._transparentSubMeshes);
  21322. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21323. }
  21324. // Set back stencil to false in case it changes before the edge renderer.
  21325. engine.setStencilBuffer(false);
  21326. // Edges
  21327. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  21328. this._edgesRenderers.data[edgesRendererIndex].render();
  21329. }
  21330. // Restore Stencil state.
  21331. engine.setStencilBuffer(stencilState);
  21332. };
  21333. /**
  21334. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  21335. * @param subMeshes The submeshes to render
  21336. */
  21337. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  21338. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  21339. };
  21340. /**
  21341. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  21342. * @param subMeshes The submeshes to render
  21343. */
  21344. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  21345. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  21346. };
  21347. /**
  21348. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  21349. * @param subMeshes The submeshes to render
  21350. */
  21351. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  21352. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  21353. };
  21354. /**
  21355. * Renders the submeshes in a specified order.
  21356. * @param subMeshes The submeshes to sort before render
  21357. * @param sortCompareFn The comparison function use to sort
  21358. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  21359. * @param transparent Specifies to activate blending if true
  21360. */
  21361. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  21362. var subIndex = 0;
  21363. var subMesh;
  21364. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  21365. for (; subIndex < subMeshes.length; subIndex++) {
  21366. subMesh = subMeshes.data[subIndex];
  21367. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  21368. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  21369. }
  21370. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  21371. if (sortCompareFn) {
  21372. sortedArray.sort(sortCompareFn);
  21373. }
  21374. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  21375. subMesh = sortedArray[subIndex];
  21376. if (transparent) {
  21377. var material = subMesh.getMaterial();
  21378. if (material && material.needDepthPrePass) {
  21379. var engine = material.getScene().getEngine();
  21380. engine.setColorWrite(false);
  21381. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21382. subMesh.render(false);
  21383. engine.setColorWrite(true);
  21384. }
  21385. }
  21386. subMesh.render(transparent);
  21387. }
  21388. };
  21389. /**
  21390. * Renders the submeshes in the order they were dispatched (no sort applied).
  21391. * @param subMeshes The submeshes to render
  21392. */
  21393. RenderingGroup.renderUnsorted = function (subMeshes) {
  21394. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  21395. var submesh = subMeshes.data[subIndex];
  21396. submesh.render(false);
  21397. }
  21398. };
  21399. /**
  21400. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21401. * are rendered back to front if in the same alpha index.
  21402. *
  21403. * @param a The first submesh
  21404. * @param b The second submesh
  21405. * @returns The result of the comparison
  21406. */
  21407. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  21408. // Alpha index first
  21409. if (a._alphaIndex > b._alphaIndex) {
  21410. return 1;
  21411. }
  21412. if (a._alphaIndex < b._alphaIndex) {
  21413. return -1;
  21414. }
  21415. // Then distance to camera
  21416. return RenderingGroup.backToFrontSortCompare(a, b);
  21417. };
  21418. /**
  21419. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21420. * are rendered back to front.
  21421. *
  21422. * @param a The first submesh
  21423. * @param b The second submesh
  21424. * @returns The result of the comparison
  21425. */
  21426. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21427. // Then distance to camera
  21428. if (a._distanceToCamera < b._distanceToCamera) {
  21429. return 1;
  21430. }
  21431. if (a._distanceToCamera > b._distanceToCamera) {
  21432. return -1;
  21433. }
  21434. return 0;
  21435. };
  21436. /**
  21437. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21438. * are rendered front to back (prevent overdraw).
  21439. *
  21440. * @param a The first submesh
  21441. * @param b The second submesh
  21442. * @returns The result of the comparison
  21443. */
  21444. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21445. // Then distance to camera
  21446. if (a._distanceToCamera < b._distanceToCamera) {
  21447. return -1;
  21448. }
  21449. if (a._distanceToCamera > b._distanceToCamera) {
  21450. return 1;
  21451. }
  21452. return 0;
  21453. };
  21454. /**
  21455. * Resets the different lists of submeshes to prepare a new frame.
  21456. */
  21457. RenderingGroup.prototype.prepare = function () {
  21458. this._opaqueSubMeshes.reset();
  21459. this._transparentSubMeshes.reset();
  21460. this._alphaTestSubMeshes.reset();
  21461. this._depthOnlySubMeshes.reset();
  21462. this._particleSystems.reset();
  21463. this._spriteManagers.reset();
  21464. this._edgesRenderers.reset();
  21465. };
  21466. RenderingGroup.prototype.dispose = function () {
  21467. this._opaqueSubMeshes.dispose();
  21468. this._transparentSubMeshes.dispose();
  21469. this._alphaTestSubMeshes.dispose();
  21470. this._depthOnlySubMeshes.dispose();
  21471. this._particleSystems.dispose();
  21472. this._spriteManagers.dispose();
  21473. this._edgesRenderers.dispose();
  21474. };
  21475. /**
  21476. * Inserts the submesh in its correct queue depending on its material.
  21477. * @param subMesh The submesh to dispatch
  21478. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21479. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21480. */
  21481. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21482. // Get mesh and materials if not provided
  21483. if (mesh === undefined) {
  21484. mesh = subMesh.getMesh();
  21485. }
  21486. if (material === undefined) {
  21487. material = subMesh.getMaterial();
  21488. }
  21489. if (material === null || material === undefined) {
  21490. return;
  21491. }
  21492. if (material.needAlphaBlendingForMesh(mesh)) {
  21493. this._transparentSubMeshes.push(subMesh);
  21494. }
  21495. else if (material.needAlphaTesting()) {
  21496. if (material.needDepthPrePass) {
  21497. this._depthOnlySubMeshes.push(subMesh);
  21498. }
  21499. this._alphaTestSubMeshes.push(subMesh);
  21500. }
  21501. else {
  21502. if (material.needDepthPrePass) {
  21503. this._depthOnlySubMeshes.push(subMesh);
  21504. }
  21505. this._opaqueSubMeshes.push(subMesh); // Opaque
  21506. }
  21507. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21508. this._edgesRenderers.push(mesh._edgesRenderer);
  21509. }
  21510. };
  21511. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21512. this._spriteManagers.push(spriteManager);
  21513. };
  21514. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21515. this._particleSystems.push(particleSystem);
  21516. };
  21517. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21518. if (this._particleSystems.length === 0) {
  21519. return;
  21520. }
  21521. // Particles
  21522. var activeCamera = this._scene.activeCamera;
  21523. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21524. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21525. var particleSystem = this._particleSystems.data[particleIndex];
  21526. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21527. continue;
  21528. }
  21529. var emitter = particleSystem.emitter;
  21530. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21531. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21532. }
  21533. }
  21534. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21535. };
  21536. RenderingGroup.prototype._renderSprites = function () {
  21537. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21538. return;
  21539. }
  21540. // Sprites
  21541. var activeCamera = this._scene.activeCamera;
  21542. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21543. for (var id = 0; id < this._spriteManagers.length; id++) {
  21544. var spriteManager = this._spriteManagers.data[id];
  21545. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21546. spriteManager.render();
  21547. }
  21548. }
  21549. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21550. };
  21551. return RenderingGroup;
  21552. }());
  21553. BABYLON.RenderingGroup = RenderingGroup;
  21554. })(BABYLON || (BABYLON = {}));
  21555. //# sourceMappingURL=babylon.renderingGroup.js.map
  21556. "use strict";
  21557. var BABYLON;
  21558. (function (BABYLON) {
  21559. var ClickInfo = /** @class */ (function () {
  21560. function ClickInfo() {
  21561. this._singleClick = false;
  21562. this._doubleClick = false;
  21563. this._hasSwiped = false;
  21564. this._ignore = false;
  21565. }
  21566. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21567. get: function () {
  21568. return this._singleClick;
  21569. },
  21570. set: function (b) {
  21571. this._singleClick = b;
  21572. },
  21573. enumerable: true,
  21574. configurable: true
  21575. });
  21576. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21577. get: function () {
  21578. return this._doubleClick;
  21579. },
  21580. set: function (b) {
  21581. this._doubleClick = b;
  21582. },
  21583. enumerable: true,
  21584. configurable: true
  21585. });
  21586. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21587. get: function () {
  21588. return this._hasSwiped;
  21589. },
  21590. set: function (b) {
  21591. this._hasSwiped = b;
  21592. },
  21593. enumerable: true,
  21594. configurable: true
  21595. });
  21596. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21597. get: function () {
  21598. return this._ignore;
  21599. },
  21600. set: function (b) {
  21601. this._ignore = b;
  21602. },
  21603. enumerable: true,
  21604. configurable: true
  21605. });
  21606. return ClickInfo;
  21607. }());
  21608. /**
  21609. * This class is used by the onRenderingGroupObservable
  21610. */
  21611. var RenderingGroupInfo = /** @class */ (function () {
  21612. function RenderingGroupInfo() {
  21613. }
  21614. /**
  21615. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21616. * This stage will be fired no matter what
  21617. */
  21618. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21619. /**
  21620. * Called before opaque object are rendered.
  21621. * This stage will be fired only if there's 3D Opaque content to render
  21622. */
  21623. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21624. /**
  21625. * Called after the opaque objects are rendered and before the transparent ones
  21626. * This stage will be fired only if there's 3D transparent content to render
  21627. */
  21628. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21629. /**
  21630. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21631. * This stage will be fired no matter what
  21632. */
  21633. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21634. return RenderingGroupInfo;
  21635. }());
  21636. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21637. /**
  21638. * Represents a scene to be rendered by the engine.
  21639. * @see http://doc.babylonjs.com/page.php?p=21911
  21640. */
  21641. var Scene = /** @class */ (function () {
  21642. /**
  21643. * @constructor
  21644. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21645. */
  21646. function Scene(engine) {
  21647. // Members
  21648. this.autoClear = true;
  21649. this.autoClearDepthAndStencil = true;
  21650. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21651. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21652. this._forceWireframe = false;
  21653. this._forcePointsCloud = false;
  21654. this.forceShowBoundingBoxes = false;
  21655. this.animationsEnabled = true;
  21656. this.useConstantAnimationDeltaTime = false;
  21657. this.constantlyUpdateMeshUnderPointer = false;
  21658. this.hoverCursor = "pointer";
  21659. this.defaultCursor = "";
  21660. /**
  21661. * This is used to call preventDefault() on pointer down
  21662. * in order to block unwanted artifacts like system double clicks
  21663. */
  21664. this.preventDefaultOnPointerDown = true;
  21665. // Metadata
  21666. this.metadata = null;
  21667. /**
  21668. * An event triggered when the scene is disposed.
  21669. * @type {BABYLON.Observable}
  21670. */
  21671. this.onDisposeObservable = new BABYLON.Observable();
  21672. /**
  21673. * An event triggered before rendering the scene (right after animations and physics)
  21674. * @type {BABYLON.Observable}
  21675. */
  21676. this.onBeforeRenderObservable = new BABYLON.Observable();
  21677. /**
  21678. * An event triggered after rendering the scene
  21679. * @type {BABYLON.Observable}
  21680. */
  21681. this.onAfterRenderObservable = new BABYLON.Observable();
  21682. /**
  21683. * An event triggered before animating the scene
  21684. * @type {BABYLON.Observable}
  21685. */
  21686. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21687. /**
  21688. * An event triggered after animations processing
  21689. * @type {BABYLON.Observable}
  21690. */
  21691. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21692. /**
  21693. * An event triggered before draw calls are ready to be sent
  21694. * @type {BABYLON.Observable}
  21695. */
  21696. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21697. /**
  21698. * An event triggered after draw calls have been sent
  21699. * @type {BABYLON.Observable}
  21700. */
  21701. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21702. /**
  21703. * An event triggered when physic simulation is about to be run
  21704. * @type {BABYLON.Observable}
  21705. */
  21706. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21707. /**
  21708. * An event triggered when physic simulation has been done
  21709. * @type {BABYLON.Observable}
  21710. */
  21711. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21712. /**
  21713. * An event triggered when the scene is ready
  21714. * @type {BABYLON.Observable}
  21715. */
  21716. this.onReadyObservable = new BABYLON.Observable();
  21717. /**
  21718. * An event triggered before rendering a camera
  21719. * @type {BABYLON.Observable}
  21720. */
  21721. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21722. /**
  21723. * An event triggered after rendering a camera
  21724. * @type {BABYLON.Observable}
  21725. */
  21726. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21727. /**
  21728. * An event triggered when active meshes evaluation is about to start
  21729. * @type {BABYLON.Observable}
  21730. */
  21731. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21732. /**
  21733. * An event triggered when active meshes evaluation is done
  21734. * @type {BABYLON.Observable}
  21735. */
  21736. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21737. /**
  21738. * An event triggered when particles rendering is about to start
  21739. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21740. * @type {BABYLON.Observable}
  21741. */
  21742. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21743. /**
  21744. * An event triggered when particles rendering is done
  21745. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21746. * @type {BABYLON.Observable}
  21747. */
  21748. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21749. /**
  21750. * An event triggered when sprites rendering is about to start
  21751. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21752. * @type {BABYLON.Observable}
  21753. */
  21754. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21755. /**
  21756. * An event triggered when sprites rendering is done
  21757. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21758. * @type {BABYLON.Observable}
  21759. */
  21760. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21761. /**
  21762. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21763. * @type {BABYLON.Observable}
  21764. */
  21765. this.onDataLoadedObservable = new BABYLON.Observable();
  21766. /**
  21767. * An event triggered when a camera is created
  21768. * @type {BABYLON.Observable}
  21769. */
  21770. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21771. /**
  21772. * An event triggered when a camera is removed
  21773. * @type {BABYLON.Observable}
  21774. */
  21775. this.onCameraRemovedObservable = new BABYLON.Observable();
  21776. /**
  21777. * An event triggered when a light is created
  21778. * @type {BABYLON.Observable}
  21779. */
  21780. this.onNewLightAddedObservable = new BABYLON.Observable();
  21781. /**
  21782. * An event triggered when a light is removed
  21783. * @type {BABYLON.Observable}
  21784. */
  21785. this.onLightRemovedObservable = new BABYLON.Observable();
  21786. /**
  21787. * An event triggered when a geometry is created
  21788. * @type {BABYLON.Observable}
  21789. */
  21790. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21791. /**
  21792. * An event triggered when a geometry is removed
  21793. * @type {BABYLON.Observable}
  21794. */
  21795. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21796. /**
  21797. * An event triggered when a transform node is created
  21798. * @type {BABYLON.Observable}
  21799. */
  21800. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21801. /**
  21802. * An event triggered when a transform node is removed
  21803. * @type {BABYLON.Observable}
  21804. */
  21805. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21806. /**
  21807. * An event triggered when a mesh is created
  21808. * @type {BABYLON.Observable}
  21809. */
  21810. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21811. /**
  21812. * An event triggered when a mesh is removed
  21813. * @type {BABYLON.Observable}
  21814. */
  21815. this.onMeshRemovedObservable = new BABYLON.Observable();
  21816. /**
  21817. * An event triggered when render targets are about to be rendered
  21818. * Can happen multiple times per frame.
  21819. * @type {BABYLON.Observable}
  21820. */
  21821. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21822. /**
  21823. * An event triggered when render targets were rendered.
  21824. * Can happen multiple times per frame.
  21825. * @type {BABYLON.Observable}
  21826. */
  21827. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21828. /**
  21829. * An event triggered before calculating deterministic simulation step
  21830. * @type {BABYLON.Observable}
  21831. */
  21832. this.onBeforeStepObservable = new BABYLON.Observable();
  21833. /**
  21834. * An event triggered after calculating deterministic simulation step
  21835. * @type {BABYLON.Observable}
  21836. */
  21837. this.onAfterStepObservable = new BABYLON.Observable();
  21838. /**
  21839. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21840. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21841. * 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)
  21842. */
  21843. this.onRenderingGroupObservable = new BABYLON.Observable();
  21844. // Animations
  21845. this.animations = [];
  21846. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  21847. /**
  21848. * 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).
  21849. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21850. */
  21851. this.onPrePointerObservable = new BABYLON.Observable();
  21852. /**
  21853. * Observable event triggered each time an input event is received from the rendering canvas
  21854. */
  21855. this.onPointerObservable = new BABYLON.Observable();
  21856. this._meshPickProceed = false;
  21857. this._currentPickResult = null;
  21858. this._previousPickResult = null;
  21859. this._totalPointersPressed = 0;
  21860. this._doubleClickOccured = false;
  21861. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21862. this.cameraToUseForPointers = null;
  21863. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21864. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21865. this._startingPointerTime = 0;
  21866. this._previousStartingPointerTime = 0;
  21867. // Deterministic lockstep
  21868. this._timeAccumulator = 0;
  21869. this._currentStepId = 0;
  21870. this._currentInternalStep = 0;
  21871. // Keyboard
  21872. /**
  21873. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21874. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21875. */
  21876. this.onPreKeyboardObservable = new BABYLON.Observable();
  21877. /**
  21878. * Observable event triggered each time an keyboard event is received from the hosting window
  21879. */
  21880. this.onKeyboardObservable = new BABYLON.Observable();
  21881. // Coordinate system
  21882. /**
  21883. * use right-handed coordinate system on this scene.
  21884. * @type {boolean}
  21885. */
  21886. this._useRightHandedSystem = false;
  21887. // Fog
  21888. this._fogEnabled = true;
  21889. this._fogMode = Scene.FOGMODE_NONE;
  21890. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21891. this.fogDensity = 0.1;
  21892. this.fogStart = 0;
  21893. this.fogEnd = 1000.0;
  21894. // Lights
  21895. /**
  21896. * is shadow enabled on this scene.
  21897. * @type {boolean}
  21898. */
  21899. this._shadowsEnabled = true;
  21900. /**
  21901. * is light enabled on this scene.
  21902. * @type {boolean}
  21903. */
  21904. this._lightsEnabled = true;
  21905. /**
  21906. * All of the lights added to this scene.
  21907. * @see BABYLON.Light
  21908. * @type {BABYLON.Light[]}
  21909. */
  21910. this.lights = new Array();
  21911. // Cameras
  21912. /** All of the cameras added to this scene. */
  21913. this.cameras = new Array();
  21914. /** All of the active cameras added to this scene. */
  21915. this.activeCameras = new Array();
  21916. // Meshes
  21917. /**
  21918. * All of the tranform nodes added to this scene.
  21919. * @see BABYLON.TransformNode
  21920. * @type {BABYLON.TransformNode[]}
  21921. */
  21922. this.transformNodes = new Array();
  21923. /**
  21924. * All of the (abstract) meshes added to this scene.
  21925. * @see BABYLON.AbstractMesh
  21926. * @type {BABYLON.AbstractMesh[]}
  21927. */
  21928. this.meshes = new Array();
  21929. /**
  21930. * All of the animation groups added to this scene.
  21931. * @see BABYLON.AnimationGroup
  21932. * @type {BABYLON.AnimationGroup[]}
  21933. */
  21934. this.animationGroups = new Array();
  21935. // Geometries
  21936. this._geometries = new Array();
  21937. this.materials = new Array();
  21938. this.multiMaterials = new Array();
  21939. // Textures
  21940. this._texturesEnabled = true;
  21941. this.textures = new Array();
  21942. // Particles
  21943. this.particlesEnabled = true;
  21944. this.particleSystems = new Array();
  21945. // Sprites
  21946. this.spritesEnabled = true;
  21947. this.spriteManagers = new Array();
  21948. /**
  21949. * The list of layers (background and foreground) of the scene.
  21950. */
  21951. this.layers = new Array();
  21952. /**
  21953. * The list of effect layers (highlights/glow) contained in the scene.
  21954. */
  21955. this.effectLayers = new Array();
  21956. // Skeletons
  21957. this._skeletonsEnabled = true;
  21958. this.skeletons = new Array();
  21959. // Morph targets
  21960. this.morphTargetManagers = new Array();
  21961. // Lens flares
  21962. this.lensFlaresEnabled = true;
  21963. this.lensFlareSystems = new Array();
  21964. // Collisions
  21965. this.collisionsEnabled = true;
  21966. /** Defines the gravity applied to this scene */
  21967. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21968. // Postprocesses
  21969. this.postProcesses = new Array();
  21970. this.postProcessesEnabled = true;
  21971. // Customs render targets
  21972. this.renderTargetsEnabled = true;
  21973. this.dumpNextRenderTargets = false;
  21974. this.customRenderTargets = new Array();
  21975. // Imported meshes
  21976. this.importedMeshesFiles = new Array();
  21977. // Probes
  21978. this.probesEnabled = true;
  21979. this.reflectionProbes = new Array();
  21980. this._actionManagers = new Array();
  21981. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21982. // Procedural textures
  21983. this.proceduralTexturesEnabled = true;
  21984. this._proceduralTextures = new Array();
  21985. this.soundTracks = new Array();
  21986. this._audioEnabled = true;
  21987. this._headphone = false;
  21988. // Performance counters
  21989. this._totalVertices = new BABYLON.PerfCounter();
  21990. this._activeIndices = new BABYLON.PerfCounter();
  21991. this._activeParticles = new BABYLON.PerfCounter();
  21992. this._activeBones = new BABYLON.PerfCounter();
  21993. this._animationTime = 0;
  21994. this.animationTimeScale = 1;
  21995. this._renderId = 0;
  21996. this._executeWhenReadyTimeoutId = -1;
  21997. this._intermediateRendering = false;
  21998. this._viewUpdateFlag = -1;
  21999. this._projectionUpdateFlag = -1;
  22000. this._alternateViewUpdateFlag = -1;
  22001. this._alternateProjectionUpdateFlag = -1;
  22002. this._toBeDisposed = new BABYLON.SmartArray(256);
  22003. this._activeRequests = new Array();
  22004. this._pendingData = new Array();
  22005. this._isDisposed = false;
  22006. this.dispatchAllSubMeshesOfActiveMeshes = false;
  22007. this._activeMeshes = new BABYLON.SmartArray(256);
  22008. this._processedMaterials = new BABYLON.SmartArray(256);
  22009. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  22010. this._activeParticleSystems = new BABYLON.SmartArray(256);
  22011. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  22012. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  22013. this._activeAnimatables = new Array();
  22014. this._transformMatrix = BABYLON.Matrix.Zero();
  22015. this._useAlternateCameraConfiguration = false;
  22016. this._alternateRendering = false;
  22017. this.requireLightSorting = false;
  22018. this._depthRenderer = {};
  22019. this._activeMeshesFrozen = false;
  22020. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  22021. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  22022. this._engine.scenes.push(this);
  22023. this._uid = null;
  22024. this._renderingManager = new BABYLON.RenderingManager(this);
  22025. this.postProcessManager = new BABYLON.PostProcessManager(this);
  22026. if (BABYLON.OutlineRenderer) {
  22027. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  22028. }
  22029. if (BABYLON.Tools.IsWindowObjectExist()) {
  22030. this.attachControl();
  22031. }
  22032. //simplification queue
  22033. if (BABYLON.SimplificationQueue) {
  22034. this.simplificationQueue = new BABYLON.SimplificationQueue();
  22035. }
  22036. //collision coordinator initialization. For now legacy per default.
  22037. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  22038. // Uniform Buffer
  22039. this._createUbo();
  22040. // Default Image processing definition.
  22041. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  22042. }
  22043. Object.defineProperty(Scene, "FOGMODE_NONE", {
  22044. /** The fog is deactivated */
  22045. get: function () {
  22046. return Scene._FOGMODE_NONE;
  22047. },
  22048. enumerable: true,
  22049. configurable: true
  22050. });
  22051. Object.defineProperty(Scene, "FOGMODE_EXP", {
  22052. /** The fog density is following an exponential function */
  22053. get: function () {
  22054. return Scene._FOGMODE_EXP;
  22055. },
  22056. enumerable: true,
  22057. configurable: true
  22058. });
  22059. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  22060. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  22061. get: function () {
  22062. return Scene._FOGMODE_EXP2;
  22063. },
  22064. enumerable: true,
  22065. configurable: true
  22066. });
  22067. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  22068. /** The fog density is following a linear function. */
  22069. get: function () {
  22070. return Scene._FOGMODE_LINEAR;
  22071. },
  22072. enumerable: true,
  22073. configurable: true
  22074. });
  22075. Object.defineProperty(Scene.prototype, "environmentTexture", {
  22076. /**
  22077. * Texture used in all pbr material as the reflection texture.
  22078. * As in the majority of the scene they are the same (exception for multi room and so on),
  22079. * this is easier to reference from here than from all the materials.
  22080. */
  22081. get: function () {
  22082. return this._environmentTexture;
  22083. },
  22084. /**
  22085. * Texture used in all pbr material as the reflection texture.
  22086. * As in the majority of the scene they are the same (exception for multi room and so on),
  22087. * this is easier to set here than in all the materials.
  22088. */
  22089. set: function (value) {
  22090. if (this._environmentTexture === value) {
  22091. return;
  22092. }
  22093. this._environmentTexture = value;
  22094. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22095. },
  22096. enumerable: true,
  22097. configurable: true
  22098. });
  22099. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  22100. /**
  22101. * Default image processing configuration used either in the rendering
  22102. * Forward main pass or through the imageProcessingPostProcess if present.
  22103. * As in the majority of the scene they are the same (exception for multi camera),
  22104. * this is easier to reference from here than from all the materials and post process.
  22105. *
  22106. * No setter as we it is a shared configuration, you can set the values instead.
  22107. */
  22108. get: function () {
  22109. return this._imageProcessingConfiguration;
  22110. },
  22111. enumerable: true,
  22112. configurable: true
  22113. });
  22114. Object.defineProperty(Scene.prototype, "forceWireframe", {
  22115. get: function () {
  22116. return this._forceWireframe;
  22117. },
  22118. set: function (value) {
  22119. if (this._forceWireframe === value) {
  22120. return;
  22121. }
  22122. this._forceWireframe = value;
  22123. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22124. },
  22125. enumerable: true,
  22126. configurable: true
  22127. });
  22128. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  22129. get: function () {
  22130. return this._forcePointsCloud;
  22131. },
  22132. set: function (value) {
  22133. if (this._forcePointsCloud === value) {
  22134. return;
  22135. }
  22136. this._forcePointsCloud = value;
  22137. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22138. },
  22139. enumerable: true,
  22140. configurable: true
  22141. });
  22142. Object.defineProperty(Scene.prototype, "onDispose", {
  22143. /** A function to be executed when this scene is disposed. */
  22144. set: function (callback) {
  22145. if (this._onDisposeObserver) {
  22146. this.onDisposeObservable.remove(this._onDisposeObserver);
  22147. }
  22148. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22149. },
  22150. enumerable: true,
  22151. configurable: true
  22152. });
  22153. Object.defineProperty(Scene.prototype, "beforeRender", {
  22154. /** A function to be executed before rendering this scene */
  22155. set: function (callback) {
  22156. if (this._onBeforeRenderObserver) {
  22157. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  22158. }
  22159. if (callback) {
  22160. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  22161. }
  22162. },
  22163. enumerable: true,
  22164. configurable: true
  22165. });
  22166. Object.defineProperty(Scene.prototype, "afterRender", {
  22167. /** A function to be executed after rendering this scene */
  22168. set: function (callback) {
  22169. if (this._onAfterRenderObserver) {
  22170. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  22171. }
  22172. if (callback) {
  22173. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  22174. }
  22175. },
  22176. enumerable: true,
  22177. configurable: true
  22178. });
  22179. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  22180. set: function (callback) {
  22181. if (this._onBeforeCameraRenderObserver) {
  22182. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  22183. }
  22184. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  22185. },
  22186. enumerable: true,
  22187. configurable: true
  22188. });
  22189. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  22190. set: function (callback) {
  22191. if (this._onAfterCameraRenderObserver) {
  22192. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  22193. }
  22194. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  22195. },
  22196. enumerable: true,
  22197. configurable: true
  22198. });
  22199. Object.defineProperty(Scene.prototype, "gamepadManager", {
  22200. get: function () {
  22201. if (!this._gamepadManager) {
  22202. this._gamepadManager = new BABYLON.GamepadManager(this);
  22203. }
  22204. return this._gamepadManager;
  22205. },
  22206. enumerable: true,
  22207. configurable: true
  22208. });
  22209. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  22210. get: function () {
  22211. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  22212. },
  22213. enumerable: true,
  22214. configurable: true
  22215. });
  22216. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  22217. get: function () {
  22218. return this._useRightHandedSystem;
  22219. },
  22220. set: function (value) {
  22221. if (this._useRightHandedSystem === value) {
  22222. return;
  22223. }
  22224. this._useRightHandedSystem = value;
  22225. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22226. },
  22227. enumerable: true,
  22228. configurable: true
  22229. });
  22230. Scene.prototype.setStepId = function (newStepId) {
  22231. this._currentStepId = newStepId;
  22232. };
  22233. ;
  22234. Scene.prototype.getStepId = function () {
  22235. return this._currentStepId;
  22236. };
  22237. ;
  22238. Scene.prototype.getInternalStep = function () {
  22239. return this._currentInternalStep;
  22240. };
  22241. ;
  22242. Object.defineProperty(Scene.prototype, "fogEnabled", {
  22243. get: function () {
  22244. return this._fogEnabled;
  22245. },
  22246. /**
  22247. * is fog enabled on this scene.
  22248. */
  22249. set: function (value) {
  22250. if (this._fogEnabled === value) {
  22251. return;
  22252. }
  22253. this._fogEnabled = value;
  22254. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22255. },
  22256. enumerable: true,
  22257. configurable: true
  22258. });
  22259. Object.defineProperty(Scene.prototype, "fogMode", {
  22260. get: function () {
  22261. return this._fogMode;
  22262. },
  22263. set: function (value) {
  22264. if (this._fogMode === value) {
  22265. return;
  22266. }
  22267. this._fogMode = value;
  22268. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22269. },
  22270. enumerable: true,
  22271. configurable: true
  22272. });
  22273. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  22274. get: function () {
  22275. return this._shadowsEnabled;
  22276. },
  22277. set: function (value) {
  22278. if (this._shadowsEnabled === value) {
  22279. return;
  22280. }
  22281. this._shadowsEnabled = value;
  22282. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22283. },
  22284. enumerable: true,
  22285. configurable: true
  22286. });
  22287. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  22288. get: function () {
  22289. return this._lightsEnabled;
  22290. },
  22291. set: function (value) {
  22292. if (this._lightsEnabled === value) {
  22293. return;
  22294. }
  22295. this._lightsEnabled = value;
  22296. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22297. },
  22298. enumerable: true,
  22299. configurable: true
  22300. });
  22301. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  22302. /** The default material used on meshes when no material is affected */
  22303. get: function () {
  22304. if (!this._defaultMaterial) {
  22305. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  22306. }
  22307. return this._defaultMaterial;
  22308. },
  22309. /** The default material used on meshes when no material is affected */
  22310. set: function (value) {
  22311. this._defaultMaterial = value;
  22312. },
  22313. enumerable: true,
  22314. configurable: true
  22315. });
  22316. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  22317. get: function () {
  22318. return this._texturesEnabled;
  22319. },
  22320. set: function (value) {
  22321. if (this._texturesEnabled === value) {
  22322. return;
  22323. }
  22324. this._texturesEnabled = value;
  22325. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22326. },
  22327. enumerable: true,
  22328. configurable: true
  22329. });
  22330. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  22331. get: function () {
  22332. return this._skeletonsEnabled;
  22333. },
  22334. set: function (value) {
  22335. if (this._skeletonsEnabled === value) {
  22336. return;
  22337. }
  22338. this._skeletonsEnabled = value;
  22339. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  22340. },
  22341. enumerable: true,
  22342. configurable: true
  22343. });
  22344. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  22345. get: function () {
  22346. if (!this._postProcessRenderPipelineManager) {
  22347. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  22348. }
  22349. return this._postProcessRenderPipelineManager;
  22350. },
  22351. enumerable: true,
  22352. configurable: true
  22353. });
  22354. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  22355. get: function () {
  22356. if (!this._mainSoundTrack) {
  22357. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  22358. }
  22359. return this._mainSoundTrack;
  22360. },
  22361. enumerable: true,
  22362. configurable: true
  22363. });
  22364. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  22365. get: function () {
  22366. return this._alternateRendering;
  22367. },
  22368. enumerable: true,
  22369. configurable: true
  22370. });
  22371. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  22372. get: function () {
  22373. return this._frustumPlanes;
  22374. },
  22375. enumerable: true,
  22376. configurable: true
  22377. });
  22378. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  22379. /**
  22380. * Gets the current geometry buffer associated to the scene.
  22381. */
  22382. get: function () {
  22383. return this._geometryBufferRenderer;
  22384. },
  22385. /**
  22386. * Sets the current geometry buffer for the scene.
  22387. */
  22388. set: function (geometryBufferRenderer) {
  22389. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  22390. this._geometryBufferRenderer = geometryBufferRenderer;
  22391. }
  22392. },
  22393. enumerable: true,
  22394. configurable: true
  22395. });
  22396. Object.defineProperty(Scene.prototype, "debugLayer", {
  22397. // Properties
  22398. get: function () {
  22399. if (!this._debugLayer) {
  22400. this._debugLayer = new BABYLON.DebugLayer(this);
  22401. }
  22402. return this._debugLayer;
  22403. },
  22404. enumerable: true,
  22405. configurable: true
  22406. });
  22407. Object.defineProperty(Scene.prototype, "workerCollisions", {
  22408. get: function () {
  22409. return this._workerCollisions;
  22410. },
  22411. set: function (enabled) {
  22412. if (!BABYLON.CollisionCoordinatorLegacy) {
  22413. return;
  22414. }
  22415. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  22416. this._workerCollisions = enabled;
  22417. if (this.collisionCoordinator) {
  22418. this.collisionCoordinator.destroy();
  22419. }
  22420. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  22421. this.collisionCoordinator.init(this);
  22422. },
  22423. enumerable: true,
  22424. configurable: true
  22425. });
  22426. Object.defineProperty(Scene.prototype, "selectionOctree", {
  22427. get: function () {
  22428. return this._selectionOctree;
  22429. },
  22430. enumerable: true,
  22431. configurable: true
  22432. });
  22433. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  22434. /**
  22435. * The mesh that is currently under the pointer.
  22436. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  22437. */
  22438. get: function () {
  22439. return this._pointerOverMesh;
  22440. },
  22441. enumerable: true,
  22442. configurable: true
  22443. });
  22444. Object.defineProperty(Scene.prototype, "pointerX", {
  22445. /**
  22446. * Current on-screen X position of the pointer
  22447. * @return {number} X position of the pointer
  22448. */
  22449. get: function () {
  22450. return this._pointerX;
  22451. },
  22452. enumerable: true,
  22453. configurable: true
  22454. });
  22455. Object.defineProperty(Scene.prototype, "pointerY", {
  22456. /**
  22457. * Current on-screen Y position of the pointer
  22458. * @return {number} Y position of the pointer
  22459. */
  22460. get: function () {
  22461. return this._pointerY;
  22462. },
  22463. enumerable: true,
  22464. configurable: true
  22465. });
  22466. Scene.prototype.getCachedMaterial = function () {
  22467. return this._cachedMaterial;
  22468. };
  22469. Scene.prototype.getCachedEffect = function () {
  22470. return this._cachedEffect;
  22471. };
  22472. Scene.prototype.getCachedVisibility = function () {
  22473. return this._cachedVisibility;
  22474. };
  22475. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22476. if (visibility === void 0) { visibility = 1; }
  22477. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22478. };
  22479. Scene.prototype.getBoundingBoxRenderer = function () {
  22480. if (!this._boundingBoxRenderer) {
  22481. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22482. }
  22483. return this._boundingBoxRenderer;
  22484. };
  22485. Scene.prototype.getOutlineRenderer = function () {
  22486. return this._outlineRenderer;
  22487. };
  22488. Scene.prototype.getEngine = function () {
  22489. return this._engine;
  22490. };
  22491. Scene.prototype.getTotalVertices = function () {
  22492. return this._totalVertices.current;
  22493. };
  22494. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22495. get: function () {
  22496. return this._totalVertices;
  22497. },
  22498. enumerable: true,
  22499. configurable: true
  22500. });
  22501. Scene.prototype.getActiveIndices = function () {
  22502. return this._activeIndices.current;
  22503. };
  22504. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22505. get: function () {
  22506. return this._activeIndices;
  22507. },
  22508. enumerable: true,
  22509. configurable: true
  22510. });
  22511. Scene.prototype.getActiveParticles = function () {
  22512. return this._activeParticles.current;
  22513. };
  22514. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22515. get: function () {
  22516. return this._activeParticles;
  22517. },
  22518. enumerable: true,
  22519. configurable: true
  22520. });
  22521. Scene.prototype.getActiveBones = function () {
  22522. return this._activeBones.current;
  22523. };
  22524. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22525. get: function () {
  22526. return this._activeBones;
  22527. },
  22528. enumerable: true,
  22529. configurable: true
  22530. });
  22531. // Stats
  22532. Scene.prototype.getInterFramePerfCounter = function () {
  22533. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22534. return 0;
  22535. };
  22536. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22537. get: function () {
  22538. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22539. return null;
  22540. },
  22541. enumerable: true,
  22542. configurable: true
  22543. });
  22544. Scene.prototype.getLastFrameDuration = function () {
  22545. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22546. return 0;
  22547. };
  22548. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22549. get: function () {
  22550. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22551. return null;
  22552. },
  22553. enumerable: true,
  22554. configurable: true
  22555. });
  22556. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22557. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22558. return 0;
  22559. };
  22560. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22561. get: function () {
  22562. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22563. return null;
  22564. },
  22565. enumerable: true,
  22566. configurable: true
  22567. });
  22568. Scene.prototype.getActiveMeshes = function () {
  22569. return this._activeMeshes;
  22570. };
  22571. Scene.prototype.getRenderTargetsDuration = function () {
  22572. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22573. return 0;
  22574. };
  22575. Scene.prototype.getRenderDuration = function () {
  22576. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22577. return 0;
  22578. };
  22579. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22580. get: function () {
  22581. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22582. return null;
  22583. },
  22584. enumerable: true,
  22585. configurable: true
  22586. });
  22587. Scene.prototype.getParticlesDuration = function () {
  22588. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22589. return 0;
  22590. };
  22591. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22592. get: function () {
  22593. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22594. return null;
  22595. },
  22596. enumerable: true,
  22597. configurable: true
  22598. });
  22599. Scene.prototype.getSpritesDuration = function () {
  22600. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22601. return 0;
  22602. };
  22603. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22604. get: function () {
  22605. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22606. return null;
  22607. },
  22608. enumerable: true,
  22609. configurable: true
  22610. });
  22611. Scene.prototype.getAnimationRatio = function () {
  22612. return this._animationRatio;
  22613. };
  22614. Scene.prototype.getRenderId = function () {
  22615. return this._renderId;
  22616. };
  22617. Scene.prototype.incrementRenderId = function () {
  22618. this._renderId++;
  22619. };
  22620. Scene.prototype._updatePointerPosition = function (evt) {
  22621. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22622. if (!canvasRect) {
  22623. return;
  22624. }
  22625. this._pointerX = evt.clientX - canvasRect.left;
  22626. this._pointerY = evt.clientY - canvasRect.top;
  22627. this._unTranslatedPointerX = this._pointerX;
  22628. this._unTranslatedPointerY = this._pointerY;
  22629. };
  22630. Scene.prototype._createUbo = function () {
  22631. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22632. this._sceneUbo.addUniform("viewProjection", 16);
  22633. this._sceneUbo.addUniform("view", 16);
  22634. };
  22635. Scene.prototype._createAlternateUbo = function () {
  22636. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22637. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22638. this._alternateSceneUbo.addUniform("view", 16);
  22639. };
  22640. // Pointers handling
  22641. /**
  22642. * Use this method to simulate a pointer move on a mesh
  22643. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22644. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22645. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22646. */
  22647. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22648. var evt = new PointerEvent("pointermove", pointerEventInit);
  22649. return this._processPointerMove(pickResult, evt);
  22650. };
  22651. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22652. var canvas = this._engine.getRenderingCanvas();
  22653. if (!canvas) {
  22654. return this;
  22655. }
  22656. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22657. this.setPointerOverSprite(null);
  22658. this.setPointerOverMesh(pickResult.pickedMesh);
  22659. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22660. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22661. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22662. }
  22663. else {
  22664. canvas.style.cursor = this.hoverCursor;
  22665. }
  22666. }
  22667. else {
  22668. canvas.style.cursor = this.defaultCursor;
  22669. }
  22670. }
  22671. else {
  22672. this.setPointerOverMesh(null);
  22673. // Sprites
  22674. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22675. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22676. this.setPointerOverSprite(pickResult.pickedSprite);
  22677. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22678. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22679. }
  22680. else {
  22681. canvas.style.cursor = this.hoverCursor;
  22682. }
  22683. }
  22684. else {
  22685. this.setPointerOverSprite(null);
  22686. // Restore pointer
  22687. canvas.style.cursor = this.defaultCursor;
  22688. }
  22689. }
  22690. if (pickResult) {
  22691. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22692. if (this.onPointerMove) {
  22693. this.onPointerMove(evt, pickResult, type);
  22694. }
  22695. if (this.onPointerObservable.hasObservers()) {
  22696. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22697. this.onPointerObservable.notifyObservers(pi, type);
  22698. }
  22699. }
  22700. return this;
  22701. };
  22702. /**
  22703. * Use this method to simulate a pointer down on a mesh
  22704. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22705. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22706. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22707. */
  22708. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22709. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22710. return this._processPointerDown(pickResult, evt);
  22711. };
  22712. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22713. var _this = this;
  22714. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22715. this._pickedDownMesh = pickResult.pickedMesh;
  22716. var actionManager = pickResult.pickedMesh.actionManager;
  22717. if (actionManager) {
  22718. if (actionManager.hasPickTriggers) {
  22719. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22720. switch (evt.button) {
  22721. case 0:
  22722. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22723. break;
  22724. case 1:
  22725. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22726. break;
  22727. case 2:
  22728. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22729. break;
  22730. }
  22731. }
  22732. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22733. window.setTimeout(function () {
  22734. 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);
  22735. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22736. if (_this._totalPointersPressed !== 0 &&
  22737. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22738. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22739. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22740. _this._startingPointerTime = 0;
  22741. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22742. }
  22743. }
  22744. }, Scene.LongPressDelay);
  22745. }
  22746. }
  22747. }
  22748. if (pickResult) {
  22749. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22750. if (this.onPointerDown) {
  22751. this.onPointerDown(evt, pickResult, type);
  22752. }
  22753. if (this.onPointerObservable.hasObservers()) {
  22754. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22755. this.onPointerObservable.notifyObservers(pi, type);
  22756. }
  22757. }
  22758. return this;
  22759. };
  22760. /**
  22761. * Use this method to simulate a pointer up on a mesh
  22762. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22763. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22764. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22765. */
  22766. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22767. var evt = new PointerEvent("pointerup", pointerEventInit);
  22768. var clickInfo = new ClickInfo();
  22769. clickInfo.singleClick = true;
  22770. clickInfo.ignore = true;
  22771. return this._processPointerUp(pickResult, evt, clickInfo);
  22772. };
  22773. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22774. if (pickResult && pickResult && pickResult.pickedMesh) {
  22775. this._pickedUpMesh = pickResult.pickedMesh;
  22776. if (this._pickedDownMesh === this._pickedUpMesh) {
  22777. if (this.onPointerPick) {
  22778. this.onPointerPick(evt, pickResult);
  22779. }
  22780. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22781. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  22782. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  22783. this.onPointerObservable.notifyObservers(pi, type_1);
  22784. }
  22785. }
  22786. if (pickResult.pickedMesh.actionManager) {
  22787. if (clickInfo.ignore) {
  22788. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22789. }
  22790. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22791. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22792. }
  22793. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22794. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22795. }
  22796. }
  22797. }
  22798. if (this._pickedDownMesh &&
  22799. this._pickedDownMesh.actionManager &&
  22800. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22801. this._pickedDownMesh !== this._pickedUpMesh) {
  22802. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22803. }
  22804. var type = BABYLON.PointerEventTypes.POINTERUP;
  22805. if (this.onPointerObservable.hasObservers()) {
  22806. if (!clickInfo.ignore) {
  22807. if (!clickInfo.hasSwiped) {
  22808. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22809. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  22810. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  22811. this.onPointerObservable.notifyObservers(pi, type_2);
  22812. }
  22813. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22814. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22815. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  22816. this.onPointerObservable.notifyObservers(pi, type_3);
  22817. }
  22818. }
  22819. }
  22820. else {
  22821. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22822. this.onPointerObservable.notifyObservers(pi, type);
  22823. }
  22824. }
  22825. if (this.onPointerUp) {
  22826. this.onPointerUp(evt, pickResult, type);
  22827. }
  22828. return this;
  22829. };
  22830. /**
  22831. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22832. * @param attachUp defines if you want to attach events to pointerup
  22833. * @param attachDown defines if you want to attach events to pointerdown
  22834. * @param attachMove defines if you want to attach events to pointermove
  22835. */
  22836. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22837. var _this = this;
  22838. if (attachUp === void 0) { attachUp = true; }
  22839. if (attachDown === void 0) { attachDown = true; }
  22840. if (attachMove === void 0) { attachMove = true; }
  22841. this._initActionManager = function (act, clickInfo) {
  22842. if (!_this._meshPickProceed) {
  22843. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22844. _this._currentPickResult = pickResult;
  22845. if (pickResult) {
  22846. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22847. }
  22848. _this._meshPickProceed = true;
  22849. }
  22850. return act;
  22851. };
  22852. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22853. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22854. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22855. btn !== _this._previousButtonPressed) {
  22856. _this._doubleClickOccured = false;
  22857. clickInfo.singleClick = true;
  22858. clickInfo.ignore = false;
  22859. cb(clickInfo, _this._currentPickResult);
  22860. }
  22861. };
  22862. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22863. var clickInfo = new ClickInfo();
  22864. _this._currentPickResult = null;
  22865. var act = null;
  22866. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22867. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22868. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22869. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22870. act = _this._initActionManager(act, clickInfo);
  22871. if (act)
  22872. checkPicking = act.hasPickTriggers;
  22873. }
  22874. if (checkPicking) {
  22875. var btn = evt.button;
  22876. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22877. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22878. if (!clickInfo.hasSwiped) {
  22879. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22880. if (!checkSingleClickImmediately) {
  22881. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22882. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22883. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22884. act = _this._initActionManager(act, clickInfo);
  22885. if (act)
  22886. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22887. }
  22888. }
  22889. if (checkSingleClickImmediately) {
  22890. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22891. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22892. btn !== _this._previousButtonPressed) {
  22893. clickInfo.singleClick = true;
  22894. cb(clickInfo, _this._currentPickResult);
  22895. }
  22896. }
  22897. else {
  22898. // wait that no double click has been raised during the double click delay
  22899. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22900. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22901. }
  22902. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22903. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22904. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22905. act = _this._initActionManager(act, clickInfo);
  22906. if (act)
  22907. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22908. }
  22909. if (checkDoubleClick) {
  22910. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22911. if (btn === _this._previousButtonPressed &&
  22912. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22913. !_this._doubleClickOccured) {
  22914. // pointer has not moved for 2 clicks, it's a double click
  22915. if (!clickInfo.hasSwiped &&
  22916. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22917. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22918. _this._previousStartingPointerTime = 0;
  22919. _this._doubleClickOccured = true;
  22920. clickInfo.doubleClick = true;
  22921. clickInfo.ignore = false;
  22922. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22923. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22924. }
  22925. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22926. cb(clickInfo, _this._currentPickResult);
  22927. }
  22928. else {
  22929. _this._doubleClickOccured = false;
  22930. _this._previousStartingPointerTime = _this._startingPointerTime;
  22931. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22932. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22933. _this._previousButtonPressed = btn;
  22934. if (Scene.ExclusiveDoubleClickMode) {
  22935. if (_this._previousDelayedSimpleClickTimeout) {
  22936. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22937. }
  22938. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22939. cb(clickInfo, _this._previousPickResult);
  22940. }
  22941. else {
  22942. cb(clickInfo, _this._currentPickResult);
  22943. }
  22944. }
  22945. }
  22946. else {
  22947. _this._doubleClickOccured = false;
  22948. _this._previousStartingPointerTime = _this._startingPointerTime;
  22949. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22950. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22951. _this._previousButtonPressed = btn;
  22952. }
  22953. }
  22954. }
  22955. }
  22956. clickInfo.ignore = true;
  22957. cb(clickInfo, _this._currentPickResult);
  22958. };
  22959. this._spritePredicate = function (sprite) {
  22960. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22961. };
  22962. this._onPointerMove = function (evt) {
  22963. _this._updatePointerPosition(evt);
  22964. // PreObservable support
  22965. if (_this.onPrePointerObservable.hasObservers()) {
  22966. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22967. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22968. _this.onPrePointerObservable.notifyObservers(pi, type);
  22969. if (pi.skipOnPointerObservable) {
  22970. return;
  22971. }
  22972. }
  22973. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22974. return;
  22975. }
  22976. if (!_this.pointerMovePredicate) {
  22977. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22978. }
  22979. // Meshes
  22980. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22981. _this._processPointerMove(pickResult, evt);
  22982. };
  22983. this._onPointerDown = function (evt) {
  22984. _this._totalPointersPressed++;
  22985. _this._pickedDownMesh = null;
  22986. _this._meshPickProceed = false;
  22987. _this._updatePointerPosition(evt);
  22988. if (_this.preventDefaultOnPointerDown && canvas) {
  22989. evt.preventDefault();
  22990. canvas.focus();
  22991. }
  22992. // PreObservable support
  22993. if (_this.onPrePointerObservable.hasObservers()) {
  22994. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22995. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22996. _this.onPrePointerObservable.notifyObservers(pi, type);
  22997. if (pi.skipOnPointerObservable) {
  22998. return;
  22999. }
  23000. }
  23001. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  23002. return;
  23003. }
  23004. _this._startingPointerPosition.x = _this._pointerX;
  23005. _this._startingPointerPosition.y = _this._pointerY;
  23006. _this._startingPointerTime = new Date().getTime();
  23007. if (!_this.pointerDownPredicate) {
  23008. _this.pointerDownPredicate = function (mesh) {
  23009. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  23010. };
  23011. }
  23012. // Meshes
  23013. _this._pickedDownMesh = null;
  23014. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  23015. _this._processPointerDown(pickResult, evt);
  23016. // Sprites
  23017. _this._pickedDownSprite = null;
  23018. if (_this.spriteManagers.length > 0) {
  23019. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  23020. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  23021. if (pickResult.pickedSprite.actionManager) {
  23022. _this._pickedDownSprite = pickResult.pickedSprite;
  23023. switch (evt.button) {
  23024. case 0:
  23025. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  23026. break;
  23027. case 1:
  23028. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  23029. break;
  23030. case 2:
  23031. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  23032. break;
  23033. }
  23034. if (pickResult.pickedSprite.actionManager) {
  23035. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  23036. }
  23037. }
  23038. }
  23039. }
  23040. };
  23041. this._onPointerUp = function (evt) {
  23042. if (_this._totalPointersPressed === 0) {
  23043. return; // So we need to test it the pointer down was pressed before.
  23044. }
  23045. _this._totalPointersPressed--;
  23046. _this._pickedUpMesh = null;
  23047. _this._meshPickProceed = false;
  23048. _this._updatePointerPosition(evt);
  23049. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  23050. // PreObservable support
  23051. if (_this.onPrePointerObservable.hasObservers()) {
  23052. if (!clickInfo.ignore) {
  23053. if (!clickInfo.hasSwiped) {
  23054. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  23055. var type = BABYLON.PointerEventTypes.POINTERTAP;
  23056. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  23057. _this.onPrePointerObservable.notifyObservers(pi, type);
  23058. if (pi.skipOnPointerObservable) {
  23059. return;
  23060. }
  23061. }
  23062. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  23063. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  23064. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  23065. _this.onPrePointerObservable.notifyObservers(pi, type);
  23066. if (pi.skipOnPointerObservable) {
  23067. return;
  23068. }
  23069. }
  23070. }
  23071. }
  23072. else {
  23073. var type = BABYLON.PointerEventTypes.POINTERUP;
  23074. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  23075. _this.onPrePointerObservable.notifyObservers(pi, type);
  23076. if (pi.skipOnPointerObservable) {
  23077. return;
  23078. }
  23079. }
  23080. }
  23081. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  23082. return;
  23083. }
  23084. if (!_this.pointerUpPredicate) {
  23085. _this.pointerUpPredicate = function (mesh) {
  23086. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  23087. };
  23088. }
  23089. // Meshes
  23090. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  23091. _this._initActionManager(null, clickInfo);
  23092. }
  23093. if (!pickResult) {
  23094. pickResult = _this._currentPickResult;
  23095. }
  23096. _this._processPointerUp(pickResult, evt, clickInfo);
  23097. // Sprites
  23098. if (_this.spriteManagers.length > 0) {
  23099. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  23100. if (spritePickResult) {
  23101. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  23102. if (spritePickResult.pickedSprite.actionManager) {
  23103. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  23104. if (spritePickResult.pickedSprite.actionManager) {
  23105. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  23106. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  23107. }
  23108. }
  23109. }
  23110. }
  23111. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  23112. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  23113. }
  23114. }
  23115. }
  23116. _this._previousPickResult = _this._currentPickResult;
  23117. });
  23118. };
  23119. this._onKeyDown = function (evt) {
  23120. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  23121. if (_this.onPreKeyboardObservable.hasObservers()) {
  23122. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23123. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23124. if (pi.skipOnPointerObservable) {
  23125. return;
  23126. }
  23127. }
  23128. if (_this.onKeyboardObservable.hasObservers()) {
  23129. var pi = new BABYLON.KeyboardInfo(type, evt);
  23130. _this.onKeyboardObservable.notifyObservers(pi, type);
  23131. }
  23132. if (_this.actionManager) {
  23133. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23134. }
  23135. };
  23136. this._onKeyUp = function (evt) {
  23137. var type = BABYLON.KeyboardEventTypes.KEYUP;
  23138. if (_this.onPreKeyboardObservable.hasObservers()) {
  23139. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23140. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23141. if (pi.skipOnPointerObservable) {
  23142. return;
  23143. }
  23144. }
  23145. if (_this.onKeyboardObservable.hasObservers()) {
  23146. var pi = new BABYLON.KeyboardInfo(type, evt);
  23147. _this.onKeyboardObservable.notifyObservers(pi, type);
  23148. }
  23149. if (_this.actionManager) {
  23150. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23151. }
  23152. };
  23153. var engine = this.getEngine();
  23154. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  23155. if (!canvas) {
  23156. return;
  23157. }
  23158. canvas.addEventListener("keydown", _this._onKeyDown, false);
  23159. canvas.addEventListener("keyup", _this._onKeyUp, false);
  23160. });
  23161. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  23162. if (!canvas) {
  23163. return;
  23164. }
  23165. canvas.removeEventListener("keydown", _this._onKeyDown);
  23166. canvas.removeEventListener("keyup", _this._onKeyUp);
  23167. });
  23168. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23169. var canvas = this._engine.getRenderingCanvas();
  23170. if (!canvas) {
  23171. return;
  23172. }
  23173. if (attachMove) {
  23174. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  23175. // Wheel
  23176. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  23177. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  23178. }
  23179. if (attachDown) {
  23180. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  23181. }
  23182. if (attachUp) {
  23183. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  23184. }
  23185. canvas.tabIndex = 1;
  23186. };
  23187. Scene.prototype.detachControl = function () {
  23188. var engine = this.getEngine();
  23189. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23190. var canvas = engine.getRenderingCanvas();
  23191. if (!canvas) {
  23192. return;
  23193. }
  23194. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  23195. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  23196. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  23197. if (this._onCanvasBlurObserver) {
  23198. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  23199. }
  23200. if (this._onCanvasFocusObserver) {
  23201. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  23202. }
  23203. // Wheel
  23204. canvas.removeEventListener('mousewheel', this._onPointerMove);
  23205. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  23206. // Keyboard
  23207. canvas.removeEventListener("keydown", this._onKeyDown);
  23208. canvas.removeEventListener("keyup", this._onKeyUp);
  23209. // Observables
  23210. this.onKeyboardObservable.clear();
  23211. this.onPreKeyboardObservable.clear();
  23212. this.onPointerObservable.clear();
  23213. this.onPrePointerObservable.clear();
  23214. };
  23215. /**
  23216. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  23217. * Delay loaded resources are not taking in account
  23218. * @return true if all required resources are ready
  23219. */
  23220. Scene.prototype.isReady = function () {
  23221. if (this._isDisposed) {
  23222. return false;
  23223. }
  23224. if (this._pendingData.length > 0) {
  23225. return false;
  23226. }
  23227. var index;
  23228. var engine = this.getEngine();
  23229. // Geometries
  23230. for (index = 0; index < this._geometries.length; index++) {
  23231. var geometry = this._geometries[index];
  23232. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23233. return false;
  23234. }
  23235. }
  23236. // Meshes
  23237. for (index = 0; index < this.meshes.length; index++) {
  23238. var mesh = this.meshes[index];
  23239. if (!mesh.isEnabled()) {
  23240. continue;
  23241. }
  23242. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  23243. continue;
  23244. }
  23245. if (!mesh.isReady(true)) {
  23246. return false;
  23247. }
  23248. // Effect layers
  23249. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  23250. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  23251. var layer = _a[_i];
  23252. if (!layer.hasMesh(mesh)) {
  23253. continue;
  23254. }
  23255. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  23256. var subMesh = _c[_b];
  23257. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  23258. return false;
  23259. }
  23260. }
  23261. }
  23262. }
  23263. // Particles
  23264. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  23265. var particleSystem = _e[_d];
  23266. if (!particleSystem.isReady()) {
  23267. return false;
  23268. }
  23269. }
  23270. return true;
  23271. };
  23272. Scene.prototype.resetCachedMaterial = function () {
  23273. this._cachedMaterial = null;
  23274. this._cachedEffect = null;
  23275. this._cachedVisibility = null;
  23276. };
  23277. Scene.prototype.registerBeforeRender = function (func) {
  23278. this.onBeforeRenderObservable.add(func);
  23279. };
  23280. Scene.prototype.unregisterBeforeRender = function (func) {
  23281. this.onBeforeRenderObservable.removeCallback(func);
  23282. };
  23283. Scene.prototype.registerAfterRender = function (func) {
  23284. this.onAfterRenderObservable.add(func);
  23285. };
  23286. Scene.prototype.unregisterAfterRender = function (func) {
  23287. this.onAfterRenderObservable.removeCallback(func);
  23288. };
  23289. Scene.prototype._executeOnceBeforeRender = function (func) {
  23290. var _this = this;
  23291. var execFunc = function () {
  23292. func();
  23293. setTimeout(function () {
  23294. _this.unregisterBeforeRender(execFunc);
  23295. });
  23296. };
  23297. this.registerBeforeRender(execFunc);
  23298. };
  23299. /**
  23300. * The provided function will run before render once and will be disposed afterwards.
  23301. * A timeout delay can be provided so that the function will be executed in N ms.
  23302. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  23303. * @param func The function to be executed.
  23304. * @param timeout optional delay in ms
  23305. */
  23306. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  23307. var _this = this;
  23308. if (timeout !== undefined) {
  23309. setTimeout(function () {
  23310. _this._executeOnceBeforeRender(func);
  23311. }, timeout);
  23312. }
  23313. else {
  23314. this._executeOnceBeforeRender(func);
  23315. }
  23316. };
  23317. Scene.prototype._addPendingData = function (data) {
  23318. this._pendingData.push(data);
  23319. };
  23320. Scene.prototype._removePendingData = function (data) {
  23321. var wasLoading = this.isLoading;
  23322. var index = this._pendingData.indexOf(data);
  23323. if (index !== -1) {
  23324. this._pendingData.splice(index, 1);
  23325. }
  23326. if (wasLoading && !this.isLoading) {
  23327. this.onDataLoadedObservable.notifyObservers(this);
  23328. }
  23329. };
  23330. Scene.prototype.getWaitingItemsCount = function () {
  23331. return this._pendingData.length;
  23332. };
  23333. Object.defineProperty(Scene.prototype, "isLoading", {
  23334. get: function () {
  23335. return this._pendingData.length > 0;
  23336. },
  23337. enumerable: true,
  23338. configurable: true
  23339. });
  23340. /**
  23341. * Registers a function to be executed when the scene is ready.
  23342. * @param {Function} func - the function to be executed.
  23343. */
  23344. Scene.prototype.executeWhenReady = function (func) {
  23345. var _this = this;
  23346. this.onReadyObservable.add(func);
  23347. if (this._executeWhenReadyTimeoutId !== -1) {
  23348. return;
  23349. }
  23350. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23351. _this._checkIsReady();
  23352. }, 150);
  23353. };
  23354. /**
  23355. * Returns a promise that resolves when the scene is ready.
  23356. * @returns A promise that resolves when the scene is ready.
  23357. */
  23358. Scene.prototype.whenReadyAsync = function () {
  23359. var _this = this;
  23360. return new Promise(function (resolve) {
  23361. _this.executeWhenReady(function () {
  23362. resolve();
  23363. });
  23364. });
  23365. };
  23366. Scene.prototype._checkIsReady = function () {
  23367. var _this = this;
  23368. if (this.isReady()) {
  23369. this.onReadyObservable.notifyObservers(this);
  23370. this.onReadyObservable.clear();
  23371. this._executeWhenReadyTimeoutId = -1;
  23372. return;
  23373. }
  23374. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23375. _this._checkIsReady();
  23376. }, 150);
  23377. };
  23378. // Animations
  23379. /**
  23380. * Will start the animation sequence of a given target
  23381. * @param target defines the target
  23382. * @param from defines from which frame should animation start
  23383. * @param to defines until which frame should animation run.
  23384. * @param weight defines the weight to apply to the animation (1.0 by default)
  23385. * @param loop defines if the animation loops
  23386. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23387. * @param onAnimationEnd defines the function to be executed when the animation ends
  23388. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23389. * @returns the animatable object created for this animation
  23390. * @see BABYLON.Animatable
  23391. */
  23392. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  23393. if (weight === void 0) { weight = 1.0; }
  23394. if (speedRatio === void 0) { speedRatio = 1.0; }
  23395. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  23396. returnedAnimatable.weight = weight;
  23397. return returnedAnimatable;
  23398. };
  23399. /**
  23400. * Will start the animation sequence of a given target
  23401. * @param target defines the target
  23402. * @param from defines from which frame should animation start
  23403. * @param to defines until which frame should animation run.
  23404. * @param loop defines if the animation loops
  23405. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23406. * @param onAnimationEnd defines the function to be executed when the animation ends
  23407. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23408. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  23409. * @returns the animatable object created for this animation
  23410. * @see BABYLON.Animatable
  23411. */
  23412. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  23413. if (speedRatio === void 0) { speedRatio = 1.0; }
  23414. if (stopCurrent === void 0) { stopCurrent = true; }
  23415. if (from > to && speedRatio > 0) {
  23416. speedRatio *= -1;
  23417. }
  23418. if (stopCurrent) {
  23419. this.stopAnimation(target);
  23420. }
  23421. if (!animatable) {
  23422. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  23423. }
  23424. // Local animations
  23425. if (target.animations) {
  23426. animatable.appendAnimations(target, target.animations);
  23427. }
  23428. // Children animations
  23429. if (target.getAnimatables) {
  23430. var animatables = target.getAnimatables();
  23431. for (var index = 0; index < animatables.length; index++) {
  23432. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  23433. }
  23434. }
  23435. if (stopCurrent) {
  23436. animatable.reset();
  23437. }
  23438. return animatable;
  23439. };
  23440. /**
  23441. * Begin a new animation on a given node
  23442. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23443. * @param {BABYLON.Animation[]} defines the list of animations to start
  23444. * @param {number} from defines the initial value
  23445. * @param {number} to defines the final value
  23446. * @param {boolean} loop defines if you want animation to loop (off by default)
  23447. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23448. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23449. * @returns the list of created animatables
  23450. */
  23451. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23452. if (speedRatio === undefined) {
  23453. speedRatio = 1.0;
  23454. }
  23455. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  23456. return animatable;
  23457. };
  23458. /**
  23459. * Begin a new animation on a given node and its hierarchy
  23460. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23461. * @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.
  23462. * @param {BABYLON.Animation[]} defines the list of animations to start
  23463. * @param {number} from defines the initial value
  23464. * @param {number} to defines the final value
  23465. * @param {boolean} loop defines if you want animation to loop (off by default)
  23466. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23467. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23468. * @returns the list of animatables created for all nodes
  23469. */
  23470. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23471. var children = target.getDescendants(directDescendantsOnly);
  23472. var result = [];
  23473. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  23474. var child = children_1[_i];
  23475. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23476. }
  23477. return result;
  23478. };
  23479. Scene.prototype.getAnimatableByTarget = function (target) {
  23480. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23481. if (this._activeAnimatables[index].target === target) {
  23482. return this._activeAnimatables[index];
  23483. }
  23484. }
  23485. return null;
  23486. };
  23487. Object.defineProperty(Scene.prototype, "animatables", {
  23488. get: function () {
  23489. return this._activeAnimatables;
  23490. },
  23491. enumerable: true,
  23492. configurable: true
  23493. });
  23494. /**
  23495. * Will stop the animation of the given target
  23496. * @param target - the target
  23497. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  23498. * @see beginAnimation
  23499. */
  23500. Scene.prototype.stopAnimation = function (target, animationName) {
  23501. var animatable = this.getAnimatableByTarget(target);
  23502. if (animatable) {
  23503. animatable.stop(animationName);
  23504. }
  23505. };
  23506. /**
  23507. * Stops and removes all animations that have been applied to the scene
  23508. */
  23509. Scene.prototype.stopAllAnimations = function () {
  23510. if (this._activeAnimatables) {
  23511. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23512. this._activeAnimatables[i].stop();
  23513. }
  23514. this._activeAnimatables = [];
  23515. }
  23516. };
  23517. Scene.prototype._animate = function () {
  23518. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23519. return;
  23520. }
  23521. // Getting time
  23522. var now = BABYLON.Tools.Now;
  23523. if (!this._animationTimeLast) {
  23524. if (this._pendingData.length > 0) {
  23525. return;
  23526. }
  23527. this._animationTimeLast = now;
  23528. }
  23529. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23530. this._animationTime += deltaTime;
  23531. this._animationTimeLast = now;
  23532. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23533. this._activeAnimatables[index]._animate(this._animationTime);
  23534. }
  23535. // Late animation bindings
  23536. this._processLateAnimationBindings();
  23537. };
  23538. /** @ignore */
  23539. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  23540. var target = runtimeAnimation.target;
  23541. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  23542. if (!target._lateAnimationHolders) {
  23543. target._lateAnimationHolders = {};
  23544. }
  23545. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  23546. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  23547. totalWeight: 0,
  23548. animations: []
  23549. };
  23550. }
  23551. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  23552. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  23553. };
  23554. Scene.prototype._processLateAnimationBindings = function () {
  23555. if (!this._registeredForLateAnimationBindings.length) {
  23556. return;
  23557. }
  23558. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  23559. var target = this._registeredForLateAnimationBindings.data[index];
  23560. for (var path in target._lateAnimationHolders) {
  23561. var holder = target._lateAnimationHolders[path];
  23562. // Sanity check
  23563. if (!holder.animations[0].originalValue.scaleAndAddToRef) {
  23564. continue;
  23565. }
  23566. var normalizer = 1.0;
  23567. var finalValue = void 0;
  23568. if (holder.totalWeight < 1.0) {
  23569. // We need to mix the original value in
  23570. var originalValue = holder.animations[0].originalValue;
  23571. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  23572. }
  23573. else {
  23574. // We need to normalize the weights
  23575. normalizer = holder.totalWeight;
  23576. }
  23577. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  23578. var runtimeAnimation = holder.animations[animIndex];
  23579. if (finalValue) {
  23580. runtimeAnimation.currentValue.scaleAndAddToRef(runtimeAnimation.weight / normalizer, finalValue);
  23581. }
  23582. else {
  23583. finalValue = runtimeAnimation.currentValue.scale(runtimeAnimation.weight / normalizer);
  23584. }
  23585. }
  23586. runtimeAnimation.target[path] = finalValue;
  23587. }
  23588. target._lateAnimationHolders = {};
  23589. }
  23590. this._registeredForLateAnimationBindings.reset();
  23591. };
  23592. // Matrix
  23593. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23594. this._useAlternateCameraConfiguration = active;
  23595. };
  23596. Scene.prototype.getViewMatrix = function () {
  23597. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23598. };
  23599. Scene.prototype.getProjectionMatrix = function () {
  23600. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23601. };
  23602. Scene.prototype.getTransformMatrix = function () {
  23603. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23604. };
  23605. Scene.prototype.setTransformMatrix = function (view, projection) {
  23606. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23607. return;
  23608. }
  23609. this._viewUpdateFlag = view.updateFlag;
  23610. this._projectionUpdateFlag = projection.updateFlag;
  23611. this._viewMatrix = view;
  23612. this._projectionMatrix = projection;
  23613. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23614. // Update frustum
  23615. if (!this._frustumPlanes) {
  23616. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23617. }
  23618. else {
  23619. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23620. }
  23621. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23622. var otherCamera = this.activeCamera._alternateCamera;
  23623. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23624. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23625. }
  23626. if (this._sceneUbo.useUbo) {
  23627. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23628. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23629. this._sceneUbo.update();
  23630. }
  23631. };
  23632. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23633. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23634. return;
  23635. }
  23636. this._alternateViewUpdateFlag = view.updateFlag;
  23637. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23638. this._alternateViewMatrix = view;
  23639. this._alternateProjectionMatrix = projection;
  23640. if (!this._alternateTransformMatrix) {
  23641. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23642. }
  23643. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23644. if (!this._alternateSceneUbo) {
  23645. this._createAlternateUbo();
  23646. }
  23647. if (this._alternateSceneUbo.useUbo) {
  23648. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23649. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23650. this._alternateSceneUbo.update();
  23651. }
  23652. };
  23653. Scene.prototype.getSceneUniformBuffer = function () {
  23654. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23655. };
  23656. // Methods
  23657. Scene.prototype.getUniqueId = function () {
  23658. var result = Scene._uniqueIdCounter;
  23659. Scene._uniqueIdCounter++;
  23660. return result;
  23661. };
  23662. Scene.prototype.addMesh = function (newMesh) {
  23663. this.meshes.push(newMesh);
  23664. //notify the collision coordinator
  23665. if (this.collisionCoordinator) {
  23666. this.collisionCoordinator.onMeshAdded(newMesh);
  23667. }
  23668. newMesh._resyncLightSources();
  23669. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23670. };
  23671. Scene.prototype.removeMesh = function (toRemove) {
  23672. var index = this.meshes.indexOf(toRemove);
  23673. if (index !== -1) {
  23674. // Remove from the scene if mesh found
  23675. this.meshes.splice(index, 1);
  23676. }
  23677. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23678. return index;
  23679. };
  23680. Scene.prototype.addTransformNode = function (newTransformNode) {
  23681. this.transformNodes.push(newTransformNode);
  23682. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23683. };
  23684. Scene.prototype.removeTransformNode = function (toRemove) {
  23685. var index = this.transformNodes.indexOf(toRemove);
  23686. if (index !== -1) {
  23687. // Remove from the scene if found
  23688. this.transformNodes.splice(index, 1);
  23689. }
  23690. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23691. return index;
  23692. };
  23693. Scene.prototype.removeSkeleton = function (toRemove) {
  23694. var index = this.skeletons.indexOf(toRemove);
  23695. if (index !== -1) {
  23696. // Remove from the scene if found
  23697. this.skeletons.splice(index, 1);
  23698. }
  23699. return index;
  23700. };
  23701. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23702. var index = this.morphTargetManagers.indexOf(toRemove);
  23703. if (index !== -1) {
  23704. // Remove from the scene if found
  23705. this.morphTargetManagers.splice(index, 1);
  23706. }
  23707. return index;
  23708. };
  23709. Scene.prototype.removeLight = function (toRemove) {
  23710. var index = this.lights.indexOf(toRemove);
  23711. if (index !== -1) {
  23712. // Remove from meshes
  23713. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23714. var mesh = _a[_i];
  23715. mesh._removeLightSource(toRemove);
  23716. }
  23717. // Remove from the scene if mesh found
  23718. this.lights.splice(index, 1);
  23719. this.sortLightsByPriority();
  23720. }
  23721. this.onLightRemovedObservable.notifyObservers(toRemove);
  23722. return index;
  23723. };
  23724. Scene.prototype.removeCamera = function (toRemove) {
  23725. var index = this.cameras.indexOf(toRemove);
  23726. if (index !== -1) {
  23727. // Remove from the scene if mesh found
  23728. this.cameras.splice(index, 1);
  23729. }
  23730. // Remove from activeCameras
  23731. var index2 = this.activeCameras.indexOf(toRemove);
  23732. if (index2 !== -1) {
  23733. // Remove from the scene if mesh found
  23734. this.activeCameras.splice(index2, 1);
  23735. }
  23736. // Reset the activeCamera
  23737. if (this.activeCamera === toRemove) {
  23738. if (this.cameras.length > 0) {
  23739. this.activeCamera = this.cameras[0];
  23740. }
  23741. else {
  23742. this.activeCamera = null;
  23743. }
  23744. }
  23745. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23746. return index;
  23747. };
  23748. Scene.prototype.removeParticleSystem = function (toRemove) {
  23749. var index = this.particleSystems.indexOf(toRemove);
  23750. if (index !== -1) {
  23751. this.particleSystems.splice(index, 1);
  23752. }
  23753. return index;
  23754. };
  23755. ;
  23756. Scene.prototype.removeAnimation = function (toRemove) {
  23757. var index = this.animations.indexOf(toRemove);
  23758. if (index !== -1) {
  23759. this.animations.splice(index, 1);
  23760. }
  23761. return index;
  23762. };
  23763. ;
  23764. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23765. var index = this.multiMaterials.indexOf(toRemove);
  23766. if (index !== -1) {
  23767. this.multiMaterials.splice(index, 1);
  23768. }
  23769. return index;
  23770. };
  23771. ;
  23772. Scene.prototype.removeMaterial = function (toRemove) {
  23773. var index = this.materials.indexOf(toRemove);
  23774. if (index !== -1) {
  23775. this.materials.splice(index, 1);
  23776. }
  23777. return index;
  23778. };
  23779. ;
  23780. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23781. var index = this.lensFlareSystems.indexOf(toRemove);
  23782. if (index !== -1) {
  23783. this.lensFlareSystems.splice(index, 1);
  23784. }
  23785. return index;
  23786. };
  23787. ;
  23788. Scene.prototype.removeActionManager = function (toRemove) {
  23789. var index = this._actionManagers.indexOf(toRemove);
  23790. if (index !== -1) {
  23791. this._actionManagers.splice(index, 1);
  23792. }
  23793. return index;
  23794. };
  23795. ;
  23796. Scene.prototype.addLight = function (newLight) {
  23797. this.lights.push(newLight);
  23798. this.sortLightsByPriority();
  23799. // Add light to all meshes (To support if the light is removed and then readded)
  23800. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23801. var mesh = _a[_i];
  23802. if (mesh._lightSources.indexOf(newLight) === -1) {
  23803. mesh._lightSources.push(newLight);
  23804. mesh._resyncLightSources();
  23805. }
  23806. }
  23807. this.onNewLightAddedObservable.notifyObservers(newLight);
  23808. };
  23809. Scene.prototype.sortLightsByPriority = function () {
  23810. if (this.requireLightSorting) {
  23811. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23812. }
  23813. };
  23814. Scene.prototype.addCamera = function (newCamera) {
  23815. this.cameras.push(newCamera);
  23816. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23817. };
  23818. Scene.prototype.addSkeleton = function (newSkeleton) {
  23819. this.skeletons.push(newSkeleton);
  23820. };
  23821. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23822. this.particleSystems.push(newParticleSystem);
  23823. };
  23824. Scene.prototype.addAnimation = function (newAnimation) {
  23825. this.animations.push(newAnimation);
  23826. };
  23827. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23828. this.multiMaterials.push(newMultiMaterial);
  23829. };
  23830. Scene.prototype.addMaterial = function (newMaterial) {
  23831. this.materials.push(newMaterial);
  23832. };
  23833. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23834. this.morphTargetManagers.push(newMorphTargetManager);
  23835. };
  23836. Scene.prototype.addGeometry = function (newGeometrie) {
  23837. this._geometries.push(newGeometrie);
  23838. };
  23839. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23840. this.lensFlareSystems.push(newLensFlareSystem);
  23841. };
  23842. Scene.prototype.addActionManager = function (newActionManager) {
  23843. this._actionManagers.push(newActionManager);
  23844. };
  23845. /**
  23846. * Switch active camera
  23847. * @param {Camera} newCamera - new active camera
  23848. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23849. */
  23850. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23851. if (attachControl === void 0) { attachControl = true; }
  23852. var canvas = this._engine.getRenderingCanvas();
  23853. if (!canvas) {
  23854. return;
  23855. }
  23856. if (this.activeCamera) {
  23857. this.activeCamera.detachControl(canvas);
  23858. }
  23859. this.activeCamera = newCamera;
  23860. if (attachControl) {
  23861. newCamera.attachControl(canvas);
  23862. }
  23863. };
  23864. /**
  23865. * sets the active camera of the scene using its ID
  23866. * @param {string} id - the camera's ID
  23867. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23868. * @see activeCamera
  23869. */
  23870. Scene.prototype.setActiveCameraByID = function (id) {
  23871. var camera = this.getCameraByID(id);
  23872. if (camera) {
  23873. this.activeCamera = camera;
  23874. return camera;
  23875. }
  23876. return null;
  23877. };
  23878. /**
  23879. * sets the active camera of the scene using its name
  23880. * @param {string} name - the camera's name
  23881. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23882. * @see activeCamera
  23883. */
  23884. Scene.prototype.setActiveCameraByName = function (name) {
  23885. var camera = this.getCameraByName(name);
  23886. if (camera) {
  23887. this.activeCamera = camera;
  23888. return camera;
  23889. }
  23890. return null;
  23891. };
  23892. /**
  23893. * get an animation group using its name
  23894. * @param {string} the material's name
  23895. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23896. */
  23897. Scene.prototype.getAnimationGroupByName = function (name) {
  23898. for (var index = 0; index < this.animationGroups.length; index++) {
  23899. if (this.animationGroups[index].name === name) {
  23900. return this.animationGroups[index];
  23901. }
  23902. }
  23903. return null;
  23904. };
  23905. /**
  23906. * get a material using its id
  23907. * @param {string} the material's ID
  23908. * @return {BABYLON.Material|null} the material or null if none found.
  23909. */
  23910. Scene.prototype.getMaterialByID = function (id) {
  23911. for (var index = 0; index < this.materials.length; index++) {
  23912. if (this.materials[index].id === id) {
  23913. return this.materials[index];
  23914. }
  23915. }
  23916. return null;
  23917. };
  23918. /**
  23919. * get a material using its name
  23920. * @param {string} the material's name
  23921. * @return {BABYLON.Material|null} the material or null if none found.
  23922. */
  23923. Scene.prototype.getMaterialByName = function (name) {
  23924. for (var index = 0; index < this.materials.length; index++) {
  23925. if (this.materials[index].name === name) {
  23926. return this.materials[index];
  23927. }
  23928. }
  23929. return null;
  23930. };
  23931. Scene.prototype.getLensFlareSystemByName = function (name) {
  23932. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23933. if (this.lensFlareSystems[index].name === name) {
  23934. return this.lensFlareSystems[index];
  23935. }
  23936. }
  23937. return null;
  23938. };
  23939. Scene.prototype.getLensFlareSystemByID = function (id) {
  23940. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23941. if (this.lensFlareSystems[index].id === id) {
  23942. return this.lensFlareSystems[index];
  23943. }
  23944. }
  23945. return null;
  23946. };
  23947. Scene.prototype.getCameraByID = function (id) {
  23948. for (var index = 0; index < this.cameras.length; index++) {
  23949. if (this.cameras[index].id === id) {
  23950. return this.cameras[index];
  23951. }
  23952. }
  23953. return null;
  23954. };
  23955. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23956. for (var index = 0; index < this.cameras.length; index++) {
  23957. if (this.cameras[index].uniqueId === uniqueId) {
  23958. return this.cameras[index];
  23959. }
  23960. }
  23961. return null;
  23962. };
  23963. /**
  23964. * get a camera using its name
  23965. * @param {string} the camera's name
  23966. * @return {BABYLON.Camera|null} the camera or null if none found.
  23967. */
  23968. Scene.prototype.getCameraByName = function (name) {
  23969. for (var index = 0; index < this.cameras.length; index++) {
  23970. if (this.cameras[index].name === name) {
  23971. return this.cameras[index];
  23972. }
  23973. }
  23974. return null;
  23975. };
  23976. /**
  23977. * get a bone using its id
  23978. * @param {string} the bone's id
  23979. * @return {BABYLON.Bone|null} the bone or null if not found
  23980. */
  23981. Scene.prototype.getBoneByID = function (id) {
  23982. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23983. var skeleton = this.skeletons[skeletonIndex];
  23984. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23985. if (skeleton.bones[boneIndex].id === id) {
  23986. return skeleton.bones[boneIndex];
  23987. }
  23988. }
  23989. }
  23990. return null;
  23991. };
  23992. /**
  23993. * get a bone using its id
  23994. * @param {string} the bone's name
  23995. * @return {BABYLON.Bone|null} the bone or null if not found
  23996. */
  23997. Scene.prototype.getBoneByName = function (name) {
  23998. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23999. var skeleton = this.skeletons[skeletonIndex];
  24000. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  24001. if (skeleton.bones[boneIndex].name === name) {
  24002. return skeleton.bones[boneIndex];
  24003. }
  24004. }
  24005. }
  24006. return null;
  24007. };
  24008. /**
  24009. * get a light node using its name
  24010. * @param {string} the light's name
  24011. * @return {BABYLON.Light|null} the light or null if none found.
  24012. */
  24013. Scene.prototype.getLightByName = function (name) {
  24014. for (var index = 0; index < this.lights.length; index++) {
  24015. if (this.lights[index].name === name) {
  24016. return this.lights[index];
  24017. }
  24018. }
  24019. return null;
  24020. };
  24021. /**
  24022. * get a light node using its ID
  24023. * @param {string} the light's id
  24024. * @return {BABYLON.Light|null} the light or null if none found.
  24025. */
  24026. Scene.prototype.getLightByID = function (id) {
  24027. for (var index = 0; index < this.lights.length; index++) {
  24028. if (this.lights[index].id === id) {
  24029. return this.lights[index];
  24030. }
  24031. }
  24032. return null;
  24033. };
  24034. /**
  24035. * get a light node using its scene-generated unique ID
  24036. * @param {number} the light's unique id
  24037. * @return {BABYLON.Light|null} the light or null if none found.
  24038. */
  24039. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  24040. for (var index = 0; index < this.lights.length; index++) {
  24041. if (this.lights[index].uniqueId === uniqueId) {
  24042. return this.lights[index];
  24043. }
  24044. }
  24045. return null;
  24046. };
  24047. /**
  24048. * get a particle system by id
  24049. * @param id {number} the particle system id
  24050. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  24051. */
  24052. Scene.prototype.getParticleSystemByID = function (id) {
  24053. for (var index = 0; index < this.particleSystems.length; index++) {
  24054. if (this.particleSystems[index].id === id) {
  24055. return this.particleSystems[index];
  24056. }
  24057. }
  24058. return null;
  24059. };
  24060. /**
  24061. * get a geometry using its ID
  24062. * @param {string} the geometry's id
  24063. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  24064. */
  24065. Scene.prototype.getGeometryByID = function (id) {
  24066. for (var index = 0; index < this._geometries.length; index++) {
  24067. if (this._geometries[index].id === id) {
  24068. return this._geometries[index];
  24069. }
  24070. }
  24071. return null;
  24072. };
  24073. /**
  24074. * add a new geometry to this scene.
  24075. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  24076. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  24077. * @return {boolean} was the geometry added or not
  24078. */
  24079. Scene.prototype.pushGeometry = function (geometry, force) {
  24080. if (!force && this.getGeometryByID(geometry.id)) {
  24081. return false;
  24082. }
  24083. this._geometries.push(geometry);
  24084. //notify the collision coordinator
  24085. if (this.collisionCoordinator) {
  24086. this.collisionCoordinator.onGeometryAdded(geometry);
  24087. }
  24088. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  24089. return true;
  24090. };
  24091. /**
  24092. * Removes an existing geometry
  24093. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  24094. * @return {boolean} was the geometry removed or not
  24095. */
  24096. Scene.prototype.removeGeometry = function (geometry) {
  24097. var index = this._geometries.indexOf(geometry);
  24098. if (index > -1) {
  24099. this._geometries.splice(index, 1);
  24100. //notify the collision coordinator
  24101. if (this.collisionCoordinator) {
  24102. this.collisionCoordinator.onGeometryDeleted(geometry);
  24103. }
  24104. this.onGeometryRemovedObservable.notifyObservers(geometry);
  24105. return true;
  24106. }
  24107. return false;
  24108. };
  24109. Scene.prototype.getGeometries = function () {
  24110. return this._geometries;
  24111. };
  24112. /**
  24113. * Get the first added mesh found of a given ID
  24114. * @param {string} id - the id to search for
  24115. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24116. */
  24117. Scene.prototype.getMeshByID = function (id) {
  24118. for (var index = 0; index < this.meshes.length; index++) {
  24119. if (this.meshes[index].id === id) {
  24120. return this.meshes[index];
  24121. }
  24122. }
  24123. return null;
  24124. };
  24125. Scene.prototype.getMeshesByID = function (id) {
  24126. return this.meshes.filter(function (m) {
  24127. return m.id === id;
  24128. });
  24129. };
  24130. /**
  24131. * Get the first added transform node found of a given ID
  24132. * @param {string} id - the id to search for
  24133. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  24134. */
  24135. Scene.prototype.getTransformNodeByID = function (id) {
  24136. for (var index = 0; index < this.transformNodes.length; index++) {
  24137. if (this.transformNodes[index].id === id) {
  24138. return this.transformNodes[index];
  24139. }
  24140. }
  24141. return null;
  24142. };
  24143. Scene.prototype.getTransformNodesByID = function (id) {
  24144. return this.transformNodes.filter(function (m) {
  24145. return m.id === id;
  24146. });
  24147. };
  24148. /**
  24149. * Get a mesh with its auto-generated unique id
  24150. * @param {number} uniqueId - the unique id to search for
  24151. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24152. */
  24153. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  24154. for (var index = 0; index < this.meshes.length; index++) {
  24155. if (this.meshes[index].uniqueId === uniqueId) {
  24156. return this.meshes[index];
  24157. }
  24158. }
  24159. return null;
  24160. };
  24161. /**
  24162. * Get a the last added mesh found of a given ID
  24163. * @param {string} id - the id to search for
  24164. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24165. */
  24166. Scene.prototype.getLastMeshByID = function (id) {
  24167. for (var index = this.meshes.length - 1; index >= 0; index--) {
  24168. if (this.meshes[index].id === id) {
  24169. return this.meshes[index];
  24170. }
  24171. }
  24172. return null;
  24173. };
  24174. /**
  24175. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  24176. * @param {string} id - the id to search for
  24177. * @return {BABYLON.Node|null} the node found or null if not found at all.
  24178. */
  24179. Scene.prototype.getLastEntryByID = function (id) {
  24180. var index;
  24181. for (index = this.meshes.length - 1; index >= 0; index--) {
  24182. if (this.meshes[index].id === id) {
  24183. return this.meshes[index];
  24184. }
  24185. }
  24186. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  24187. if (this.transformNodes[index].id === id) {
  24188. return this.transformNodes[index];
  24189. }
  24190. }
  24191. for (index = this.cameras.length - 1; index >= 0; index--) {
  24192. if (this.cameras[index].id === id) {
  24193. return this.cameras[index];
  24194. }
  24195. }
  24196. for (index = this.lights.length - 1; index >= 0; index--) {
  24197. if (this.lights[index].id === id) {
  24198. return this.lights[index];
  24199. }
  24200. }
  24201. return null;
  24202. };
  24203. Scene.prototype.getNodeByID = function (id) {
  24204. var mesh = this.getMeshByID(id);
  24205. if (mesh) {
  24206. return mesh;
  24207. }
  24208. var light = this.getLightByID(id);
  24209. if (light) {
  24210. return light;
  24211. }
  24212. var camera = this.getCameraByID(id);
  24213. if (camera) {
  24214. return camera;
  24215. }
  24216. var bone = this.getBoneByID(id);
  24217. return bone;
  24218. };
  24219. Scene.prototype.getNodeByName = function (name) {
  24220. var mesh = this.getMeshByName(name);
  24221. if (mesh) {
  24222. return mesh;
  24223. }
  24224. var light = this.getLightByName(name);
  24225. if (light) {
  24226. return light;
  24227. }
  24228. var camera = this.getCameraByName(name);
  24229. if (camera) {
  24230. return camera;
  24231. }
  24232. var bone = this.getBoneByName(name);
  24233. return bone;
  24234. };
  24235. Scene.prototype.getMeshByName = function (name) {
  24236. for (var index = 0; index < this.meshes.length; index++) {
  24237. if (this.meshes[index].name === name) {
  24238. return this.meshes[index];
  24239. }
  24240. }
  24241. return null;
  24242. };
  24243. Scene.prototype.getTransformNodeByName = function (name) {
  24244. for (var index = 0; index < this.transformNodes.length; index++) {
  24245. if (this.transformNodes[index].name === name) {
  24246. return this.transformNodes[index];
  24247. }
  24248. }
  24249. return null;
  24250. };
  24251. Scene.prototype.getSoundByName = function (name) {
  24252. var index;
  24253. if (BABYLON.AudioEngine) {
  24254. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  24255. if (this.mainSoundTrack.soundCollection[index].name === name) {
  24256. return this.mainSoundTrack.soundCollection[index];
  24257. }
  24258. }
  24259. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  24260. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  24261. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  24262. return this.soundTracks[sdIndex].soundCollection[index];
  24263. }
  24264. }
  24265. }
  24266. }
  24267. return null;
  24268. };
  24269. Scene.prototype.getLastSkeletonByID = function (id) {
  24270. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  24271. if (this.skeletons[index].id === id) {
  24272. return this.skeletons[index];
  24273. }
  24274. }
  24275. return null;
  24276. };
  24277. Scene.prototype.getSkeletonById = function (id) {
  24278. for (var index = 0; index < this.skeletons.length; index++) {
  24279. if (this.skeletons[index].id === id) {
  24280. return this.skeletons[index];
  24281. }
  24282. }
  24283. return null;
  24284. };
  24285. Scene.prototype.getSkeletonByName = function (name) {
  24286. for (var index = 0; index < this.skeletons.length; index++) {
  24287. if (this.skeletons[index].name === name) {
  24288. return this.skeletons[index];
  24289. }
  24290. }
  24291. return null;
  24292. };
  24293. Scene.prototype.getMorphTargetManagerById = function (id) {
  24294. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  24295. if (this.morphTargetManagers[index].uniqueId === id) {
  24296. return this.morphTargetManagers[index];
  24297. }
  24298. }
  24299. return null;
  24300. };
  24301. Scene.prototype.isActiveMesh = function (mesh) {
  24302. return (this._activeMeshes.indexOf(mesh) !== -1);
  24303. };
  24304. /**
  24305. * Return a the first highlight layer of the scene with a given name.
  24306. * @param name The name of the highlight layer to look for.
  24307. * @return The highlight layer if found otherwise null.
  24308. */
  24309. Scene.prototype.getHighlightLayerByName = function (name) {
  24310. for (var index = 0; index < this.effectLayers.length; index++) {
  24311. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  24312. return this.effectLayers[index];
  24313. }
  24314. }
  24315. return null;
  24316. };
  24317. /**
  24318. * Return a the first highlight layer of the scene with a given name.
  24319. * @param name The name of the highlight layer to look for.
  24320. * @return The highlight layer if found otherwise null.
  24321. */
  24322. Scene.prototype.getGlowLayerByName = function (name) {
  24323. for (var index = 0; index < this.effectLayers.length; index++) {
  24324. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  24325. return this.effectLayers[index];
  24326. }
  24327. }
  24328. return null;
  24329. };
  24330. Object.defineProperty(Scene.prototype, "uid", {
  24331. /**
  24332. * Return a unique id as a string which can serve as an identifier for the scene
  24333. */
  24334. get: function () {
  24335. if (!this._uid) {
  24336. this._uid = BABYLON.Tools.RandomId();
  24337. }
  24338. return this._uid;
  24339. },
  24340. enumerable: true,
  24341. configurable: true
  24342. });
  24343. /**
  24344. * Add an externaly attached data from its key.
  24345. * This method call will fail and return false, if such key already exists.
  24346. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  24347. * @param key the unique key that identifies the data
  24348. * @param data the data object to associate to the key for this Engine instance
  24349. * @return true if no such key were already present and the data was added successfully, false otherwise
  24350. */
  24351. Scene.prototype.addExternalData = function (key, data) {
  24352. if (!this._externalData) {
  24353. this._externalData = new BABYLON.StringDictionary();
  24354. }
  24355. return this._externalData.add(key, data);
  24356. };
  24357. /**
  24358. * Get an externaly attached data from its key
  24359. * @param key the unique key that identifies the data
  24360. * @return the associated data, if present (can be null), or undefined if not present
  24361. */
  24362. Scene.prototype.getExternalData = function (key) {
  24363. if (!this._externalData) {
  24364. return null;
  24365. }
  24366. return this._externalData.get(key);
  24367. };
  24368. /**
  24369. * Get an externaly attached data from its key, create it using a factory if it's not already present
  24370. * @param key the unique key that identifies the data
  24371. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  24372. * @return the associated data, can be null if the factory returned null.
  24373. */
  24374. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  24375. if (!this._externalData) {
  24376. this._externalData = new BABYLON.StringDictionary();
  24377. }
  24378. return this._externalData.getOrAddWithFactory(key, factory);
  24379. };
  24380. /**
  24381. * Remove an externaly attached data from the Engine instance
  24382. * @param key the unique key that identifies the data
  24383. * @return true if the data was successfully removed, false if it doesn't exist
  24384. */
  24385. Scene.prototype.removeExternalData = function (key) {
  24386. return this._externalData.remove(key);
  24387. };
  24388. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  24389. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  24390. if (mesh.showSubMeshesBoundingBox) {
  24391. var boundingInfo = subMesh.getBoundingInfo();
  24392. if (boundingInfo !== null && boundingInfo !== undefined) {
  24393. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24394. }
  24395. }
  24396. var material = subMesh.getMaterial();
  24397. if (material !== null && material !== undefined) {
  24398. // Render targets
  24399. if (material.getRenderTargetTextures !== undefined) {
  24400. if (this._processedMaterials.indexOf(material) === -1) {
  24401. this._processedMaterials.push(material);
  24402. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  24403. }
  24404. }
  24405. // Dispatch
  24406. this._activeIndices.addCount(subMesh.indexCount, false);
  24407. this._renderingManager.dispatch(subMesh, mesh, material);
  24408. }
  24409. }
  24410. };
  24411. /**
  24412. * Clear the processed materials smart array preventing retention point in material dispose.
  24413. */
  24414. Scene.prototype.freeProcessedMaterials = function () {
  24415. this._processedMaterials.dispose();
  24416. };
  24417. /**
  24418. * Clear the active meshes smart array preventing retention point in mesh dispose.
  24419. */
  24420. Scene.prototype.freeActiveMeshes = function () {
  24421. this._activeMeshes.dispose();
  24422. if (this.activeCamera && this.activeCamera._activeMeshes) {
  24423. this.activeCamera._activeMeshes.dispose();
  24424. }
  24425. if (this.activeCameras) {
  24426. for (var i = 0; i < this.activeCameras.length; i++) {
  24427. var activeCamera = this.activeCameras[i];
  24428. if (activeCamera && activeCamera._activeMeshes) {
  24429. activeCamera._activeMeshes.dispose();
  24430. }
  24431. }
  24432. }
  24433. };
  24434. /**
  24435. * Clear the info related to rendering groups preventing retention points during dispose.
  24436. */
  24437. Scene.prototype.freeRenderingGroups = function () {
  24438. if (this._renderingManager) {
  24439. this._renderingManager.freeRenderingGroups();
  24440. }
  24441. if (this.textures) {
  24442. for (var i = 0; i < this.textures.length; i++) {
  24443. var texture = this.textures[i];
  24444. if (texture && texture.renderList) {
  24445. texture.freeRenderingGroups();
  24446. }
  24447. }
  24448. }
  24449. };
  24450. Scene.prototype._isInIntermediateRendering = function () {
  24451. return this._intermediateRendering;
  24452. };
  24453. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  24454. this._activeMeshCandidateProvider = provider;
  24455. };
  24456. Scene.prototype.getActiveMeshCandidateProvider = function () {
  24457. return this._activeMeshCandidateProvider;
  24458. };
  24459. /**
  24460. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  24461. */
  24462. Scene.prototype.freezeActiveMeshes = function () {
  24463. if (!this.activeCamera) {
  24464. return this;
  24465. }
  24466. if (!this._frustumPlanes) {
  24467. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24468. }
  24469. this._evaluateActiveMeshes();
  24470. this._activeMeshesFrozen = true;
  24471. return this;
  24472. };
  24473. /**
  24474. * Use this function to restart evaluating active meshes on every frame
  24475. */
  24476. Scene.prototype.unfreezeActiveMeshes = function () {
  24477. this._activeMeshesFrozen = false;
  24478. return this;
  24479. };
  24480. Scene.prototype._evaluateActiveMeshes = function () {
  24481. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  24482. return;
  24483. }
  24484. if (!this.activeCamera) {
  24485. return;
  24486. }
  24487. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  24488. this.activeCamera._activeMeshes.reset();
  24489. this._activeMeshes.reset();
  24490. this._renderingManager.reset();
  24491. this._processedMaterials.reset();
  24492. this._activeParticleSystems.reset();
  24493. this._activeSkeletons.reset();
  24494. this._softwareSkinnedMeshes.reset();
  24495. if (this._boundingBoxRenderer) {
  24496. this._boundingBoxRenderer.reset();
  24497. }
  24498. // Meshes
  24499. var meshes;
  24500. var len;
  24501. var checkIsEnabled = true;
  24502. // Determine mesh candidates
  24503. if (this._activeMeshCandidateProvider !== undefined) {
  24504. // Use _activeMeshCandidateProvider
  24505. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  24506. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  24507. if (meshes !== undefined) {
  24508. len = meshes.length;
  24509. }
  24510. else {
  24511. len = 0;
  24512. }
  24513. }
  24514. else if (this._selectionOctree !== undefined) {
  24515. // Octree
  24516. var selection = this._selectionOctree.select(this._frustumPlanes);
  24517. meshes = selection.data;
  24518. len = selection.length;
  24519. }
  24520. else {
  24521. // Full scene traversal
  24522. len = this.meshes.length;
  24523. meshes = this.meshes;
  24524. }
  24525. // Check each mesh
  24526. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  24527. mesh = meshes[meshIndex];
  24528. if (mesh.isBlocked) {
  24529. continue;
  24530. }
  24531. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  24532. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  24533. continue;
  24534. }
  24535. mesh.computeWorldMatrix();
  24536. // Intersections
  24537. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  24538. this._meshesForIntersections.pushNoDuplicate(mesh);
  24539. }
  24540. // Switch to current LOD
  24541. meshLOD = mesh.getLOD(this.activeCamera);
  24542. if (meshLOD === undefined || meshLOD === null) {
  24543. continue;
  24544. }
  24545. mesh._preActivate();
  24546. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  24547. this._activeMeshes.push(mesh);
  24548. this.activeCamera._activeMeshes.push(mesh);
  24549. mesh._activate(this._renderId);
  24550. if (meshLOD !== mesh) {
  24551. meshLOD._activate(this._renderId);
  24552. }
  24553. this._activeMesh(mesh, meshLOD);
  24554. }
  24555. }
  24556. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  24557. // Particle systems
  24558. if (this.particlesEnabled) {
  24559. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  24560. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  24561. var particleSystem = this.particleSystems[particleIndex];
  24562. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  24563. continue;
  24564. }
  24565. var emitter = particleSystem.emitter;
  24566. if (!emitter.position || emitter.isEnabled()) {
  24567. this._activeParticleSystems.push(particleSystem);
  24568. particleSystem.animate();
  24569. this._renderingManager.dispatchParticles(particleSystem);
  24570. }
  24571. }
  24572. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  24573. }
  24574. };
  24575. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  24576. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  24577. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  24578. mesh.skeleton.prepare();
  24579. }
  24580. if (!mesh.computeBonesUsingShaders) {
  24581. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  24582. }
  24583. }
  24584. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  24585. var boundingInfo = sourceMesh.getBoundingInfo();
  24586. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24587. }
  24588. if (mesh !== undefined && mesh !== null
  24589. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  24590. // Submeshes Octrees
  24591. var len;
  24592. var subMeshes;
  24593. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  24594. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  24595. len = intersections.length;
  24596. subMeshes = intersections.data;
  24597. }
  24598. else {
  24599. subMeshes = mesh.subMeshes;
  24600. len = subMeshes.length;
  24601. }
  24602. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  24603. subMesh = subMeshes[subIndex];
  24604. this._evaluateSubMesh(subMesh, mesh);
  24605. }
  24606. }
  24607. };
  24608. Scene.prototype.updateTransformMatrix = function (force) {
  24609. if (!this.activeCamera) {
  24610. return;
  24611. }
  24612. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  24613. };
  24614. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  24615. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  24616. };
  24617. Scene.prototype._renderForCamera = function (camera, rigParent) {
  24618. if (camera && camera._skipRendering) {
  24619. return;
  24620. }
  24621. var engine = this._engine;
  24622. this.activeCamera = camera;
  24623. if (!this.activeCamera)
  24624. throw new Error("Active camera not set");
  24625. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24626. // Viewport
  24627. engine.setViewport(this.activeCamera.viewport);
  24628. // Camera
  24629. this.resetCachedMaterial();
  24630. this._renderId++;
  24631. this.updateTransformMatrix();
  24632. if (camera._alternateCamera) {
  24633. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24634. this._alternateRendering = true;
  24635. }
  24636. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24637. // Meshes
  24638. this._evaluateActiveMeshes();
  24639. // Software skinning
  24640. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24641. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24642. mesh.applySkeleton(mesh.skeleton);
  24643. }
  24644. // Render targets
  24645. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24646. var needsRestoreFrameBuffer = false;
  24647. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24648. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24649. }
  24650. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24651. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24652. }
  24653. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24654. this._intermediateRendering = true;
  24655. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24656. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24657. var renderTarget = this._renderTargets.data[renderIndex];
  24658. if (renderTarget._shouldRender()) {
  24659. this._renderId++;
  24660. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24661. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24662. }
  24663. }
  24664. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24665. this._intermediateRendering = false;
  24666. this._renderId++;
  24667. needsRestoreFrameBuffer = true; // Restore back buffer
  24668. }
  24669. // Render EffecttLayer Texture
  24670. var stencilState = this._engine.getStencilBuffer();
  24671. var renderEffects = false;
  24672. var needStencil = false;
  24673. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24674. this._intermediateRendering = true;
  24675. for (var i = 0; i < this.effectLayers.length; i++) {
  24676. var effectLayer = this.effectLayers[i];
  24677. if (effectLayer.shouldRender() &&
  24678. (!effectLayer.camera ||
  24679. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24680. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24681. renderEffects = true;
  24682. needStencil = needStencil || effectLayer.needStencil();
  24683. var renderTarget = effectLayer._mainTexture;
  24684. if (renderTarget._shouldRender()) {
  24685. this._renderId++;
  24686. renderTarget.render(false, false);
  24687. needsRestoreFrameBuffer = true;
  24688. }
  24689. }
  24690. }
  24691. this._intermediateRendering = false;
  24692. this._renderId++;
  24693. }
  24694. if (needsRestoreFrameBuffer) {
  24695. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24696. }
  24697. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24698. // Prepare Frame
  24699. this.postProcessManager._prepareFrame();
  24700. // Backgrounds
  24701. var layerIndex;
  24702. var layer;
  24703. if (this.layers.length) {
  24704. engine.setDepthBuffer(false);
  24705. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24706. layer = this.layers[layerIndex];
  24707. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24708. layer.render();
  24709. }
  24710. }
  24711. engine.setDepthBuffer(true);
  24712. }
  24713. // Activate effect Layer stencil
  24714. if (needStencil) {
  24715. this._engine.setStencilBuffer(true);
  24716. }
  24717. // Render
  24718. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24719. this._renderingManager.render(null, null, true, true);
  24720. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24721. // Restore effect Layer stencil
  24722. if (needStencil) {
  24723. this._engine.setStencilBuffer(stencilState);
  24724. }
  24725. // Bounding boxes
  24726. if (this._boundingBoxRenderer) {
  24727. this._boundingBoxRenderer.render();
  24728. }
  24729. // Lens flares
  24730. if (this.lensFlaresEnabled) {
  24731. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24732. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24733. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24734. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24735. lensFlareSystem.render();
  24736. }
  24737. }
  24738. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24739. }
  24740. // Foregrounds
  24741. if (this.layers.length) {
  24742. engine.setDepthBuffer(false);
  24743. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24744. layer = this.layers[layerIndex];
  24745. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24746. layer.render();
  24747. }
  24748. }
  24749. engine.setDepthBuffer(true);
  24750. }
  24751. // Effect Layer
  24752. if (renderEffects) {
  24753. engine.setDepthBuffer(false);
  24754. for (var i = 0; i < this.effectLayers.length; i++) {
  24755. if (this.effectLayers[i].shouldRender()) {
  24756. this.effectLayers[i].render();
  24757. }
  24758. }
  24759. engine.setDepthBuffer(true);
  24760. }
  24761. // Finalize frame
  24762. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24763. // Reset some special arrays
  24764. this._renderTargets.reset();
  24765. this._alternateRendering = false;
  24766. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24767. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24768. };
  24769. Scene.prototype._processSubCameras = function (camera) {
  24770. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24771. this._renderForCamera(camera);
  24772. return;
  24773. }
  24774. // rig cameras
  24775. for (var index = 0; index < camera._rigCameras.length; index++) {
  24776. this._renderForCamera(camera._rigCameras[index], camera);
  24777. }
  24778. this.activeCamera = camera;
  24779. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24780. };
  24781. Scene.prototype._checkIntersections = function () {
  24782. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24783. var sourceMesh = this._meshesForIntersections.data[index];
  24784. if (!sourceMesh.actionManager) {
  24785. continue;
  24786. }
  24787. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24788. var action = sourceMesh.actionManager.actions[actionIndex];
  24789. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24790. var parameters = action.getTriggerParameter();
  24791. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24792. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24793. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24794. if (areIntersecting && currentIntersectionInProgress === -1) {
  24795. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24796. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24797. sourceMesh._intersectionsInProgress.push(otherMesh);
  24798. }
  24799. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24800. sourceMesh._intersectionsInProgress.push(otherMesh);
  24801. }
  24802. }
  24803. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24804. //They intersected, and now they don't.
  24805. //is this trigger an exit trigger? execute an event.
  24806. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24807. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24808. }
  24809. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24810. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24811. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24812. }
  24813. }
  24814. }
  24815. }
  24816. }
  24817. };
  24818. Scene.prototype.render = function () {
  24819. if (this.isDisposed) {
  24820. return;
  24821. }
  24822. this._activeParticles.fetchNewFrame();
  24823. this._totalVertices.fetchNewFrame();
  24824. this._activeIndices.fetchNewFrame();
  24825. this._activeBones.fetchNewFrame();
  24826. this._meshesForIntersections.reset();
  24827. this.resetCachedMaterial();
  24828. this.onBeforeAnimationsObservable.notifyObservers(this);
  24829. // Actions
  24830. if (this.actionManager) {
  24831. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24832. }
  24833. //Simplification Queue
  24834. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24835. this.simplificationQueue.executeNext();
  24836. }
  24837. if (this._engine.isDeterministicLockStep()) {
  24838. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24839. var defaultFPS = (60.0 / 1000.0);
  24840. var defaultFrameTime = 1000 / 60; // frame time in MS
  24841. if (this._physicsEngine) {
  24842. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24843. }
  24844. var stepsTaken = 0;
  24845. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24846. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24847. internalSteps = Math.min(internalSteps, maxSubSteps);
  24848. do {
  24849. this.onBeforeStepObservable.notifyObservers(this);
  24850. // Animations
  24851. this._animationRatio = defaultFrameTime * defaultFPS;
  24852. this._animate();
  24853. this.onAfterAnimationsObservable.notifyObservers(this);
  24854. // Physics
  24855. if (this._physicsEngine) {
  24856. this.onBeforePhysicsObservable.notifyObservers(this);
  24857. this._physicsEngine._step(defaultFrameTime / 1000);
  24858. this.onAfterPhysicsObservable.notifyObservers(this);
  24859. }
  24860. this.onAfterStepObservable.notifyObservers(this);
  24861. this._currentStepId++;
  24862. stepsTaken++;
  24863. deltaTime -= defaultFrameTime;
  24864. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24865. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24866. }
  24867. else {
  24868. // Animations
  24869. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24870. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24871. this._animate();
  24872. this.onAfterAnimationsObservable.notifyObservers(this);
  24873. // Physics
  24874. if (this._physicsEngine) {
  24875. this.onBeforePhysicsObservable.notifyObservers(this);
  24876. this._physicsEngine._step(deltaTime / 1000.0);
  24877. this.onAfterPhysicsObservable.notifyObservers(this);
  24878. }
  24879. }
  24880. // update gamepad manager
  24881. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24882. this._gamepadManager._checkGamepadsStatus();
  24883. }
  24884. // Update Cameras
  24885. if (this.activeCameras.length > 0) {
  24886. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24887. var camera = this.activeCameras[cameraIndex];
  24888. camera.update();
  24889. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24890. // rig cameras
  24891. for (var index = 0; index < camera._rigCameras.length; index++) {
  24892. camera._rigCameras[index].update();
  24893. }
  24894. }
  24895. }
  24896. }
  24897. else if (this.activeCamera) {
  24898. this.activeCamera.update();
  24899. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24900. // rig cameras
  24901. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24902. this.activeCamera._rigCameras[index].update();
  24903. }
  24904. }
  24905. }
  24906. // Before render
  24907. this.onBeforeRenderObservable.notifyObservers(this);
  24908. // Customs render targets
  24909. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24910. var engine = this.getEngine();
  24911. var currentActiveCamera = this.activeCamera;
  24912. if (this.renderTargetsEnabled) {
  24913. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24914. this._intermediateRendering = true;
  24915. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24916. var renderTarget = this.customRenderTargets[customIndex];
  24917. if (renderTarget._shouldRender()) {
  24918. this._renderId++;
  24919. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24920. if (!this.activeCamera)
  24921. throw new Error("Active camera not set");
  24922. // Viewport
  24923. engine.setViewport(this.activeCamera.viewport);
  24924. // Camera
  24925. this.updateTransformMatrix();
  24926. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24927. }
  24928. }
  24929. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24930. this._intermediateRendering = false;
  24931. this._renderId++;
  24932. }
  24933. // Restore back buffer
  24934. if (this.customRenderTargets.length > 0) {
  24935. engine.restoreDefaultFramebuffer();
  24936. }
  24937. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24938. this.activeCamera = currentActiveCamera;
  24939. // Procedural textures
  24940. if (this.proceduralTexturesEnabled) {
  24941. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24942. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24943. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24944. if (proceduralTexture._shouldRender()) {
  24945. proceduralTexture.render();
  24946. }
  24947. }
  24948. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24949. }
  24950. // Clear
  24951. if (this.autoClearDepthAndStencil || this.autoClear) {
  24952. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24953. }
  24954. // Shadows
  24955. if (this.shadowsEnabled) {
  24956. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24957. var light = this.lights[lightIndex];
  24958. var shadowGenerator = light.getShadowGenerator();
  24959. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24960. var shadowMap = (shadowGenerator.getShadowMap());
  24961. if (this.textures.indexOf(shadowMap) !== -1) {
  24962. this._renderTargets.push(shadowMap);
  24963. }
  24964. }
  24965. }
  24966. }
  24967. // Depth renderer
  24968. for (var key in this._depthRenderer) {
  24969. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24970. }
  24971. // Geometry renderer
  24972. if (this._geometryBufferRenderer) {
  24973. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24974. }
  24975. // RenderPipeline
  24976. if (this._postProcessRenderPipelineManager) {
  24977. this._postProcessRenderPipelineManager.update();
  24978. }
  24979. // Multi-cameras?
  24980. if (this.activeCameras.length > 0) {
  24981. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24982. if (cameraIndex > 0) {
  24983. this._engine.clear(null, false, true, true);
  24984. }
  24985. this._processSubCameras(this.activeCameras[cameraIndex]);
  24986. }
  24987. }
  24988. else {
  24989. if (!this.activeCamera) {
  24990. throw new Error("No camera defined");
  24991. }
  24992. this._processSubCameras(this.activeCamera);
  24993. }
  24994. // Intersection checks
  24995. this._checkIntersections();
  24996. // Update the audio listener attached to the camera
  24997. if (BABYLON.AudioEngine) {
  24998. this._updateAudioParameters();
  24999. }
  25000. // After render
  25001. if (this.afterRender) {
  25002. this.afterRender();
  25003. }
  25004. this.onAfterRenderObservable.notifyObservers(this);
  25005. // Cleaning
  25006. for (var index = 0; index < this._toBeDisposed.length; index++) {
  25007. var data = this._toBeDisposed.data[index];
  25008. if (data) {
  25009. data.dispose();
  25010. }
  25011. this._toBeDisposed[index] = null;
  25012. }
  25013. this._toBeDisposed.reset();
  25014. if (this.dumpNextRenderTargets) {
  25015. this.dumpNextRenderTargets = false;
  25016. }
  25017. this._activeBones.addCount(0, true);
  25018. this._activeIndices.addCount(0, true);
  25019. this._activeParticles.addCount(0, true);
  25020. };
  25021. Scene.prototype._updateAudioParameters = function () {
  25022. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  25023. return;
  25024. }
  25025. var listeningCamera;
  25026. var audioEngine = BABYLON.Engine.audioEngine;
  25027. if (this.activeCameras.length > 0) {
  25028. listeningCamera = this.activeCameras[0];
  25029. }
  25030. else {
  25031. listeningCamera = this.activeCamera;
  25032. }
  25033. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  25034. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  25035. // for VR cameras
  25036. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  25037. listeningCamera = listeningCamera.rigCameras[0];
  25038. }
  25039. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  25040. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  25041. cameraDirection.normalize();
  25042. // To avoid some errors on GearVR
  25043. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  25044. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  25045. }
  25046. var i;
  25047. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25048. var sound = this.mainSoundTrack.soundCollection[i];
  25049. if (sound.useCustomAttenuation) {
  25050. sound.updateDistanceFromListener();
  25051. }
  25052. }
  25053. for (i = 0; i < this.soundTracks.length; i++) {
  25054. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25055. sound = this.soundTracks[i].soundCollection[j];
  25056. if (sound.useCustomAttenuation) {
  25057. sound.updateDistanceFromListener();
  25058. }
  25059. }
  25060. }
  25061. }
  25062. };
  25063. Object.defineProperty(Scene.prototype, "audioEnabled", {
  25064. // Audio
  25065. get: function () {
  25066. return this._audioEnabled;
  25067. },
  25068. set: function (value) {
  25069. this._audioEnabled = value;
  25070. if (BABYLON.AudioEngine) {
  25071. if (this._audioEnabled) {
  25072. this._enableAudio();
  25073. }
  25074. else {
  25075. this._disableAudio();
  25076. }
  25077. }
  25078. },
  25079. enumerable: true,
  25080. configurable: true
  25081. });
  25082. Scene.prototype._disableAudio = function () {
  25083. var i;
  25084. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25085. this.mainSoundTrack.soundCollection[i].pause();
  25086. }
  25087. for (i = 0; i < this.soundTracks.length; i++) {
  25088. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25089. this.soundTracks[i].soundCollection[j].pause();
  25090. }
  25091. }
  25092. };
  25093. Scene.prototype._enableAudio = function () {
  25094. var i;
  25095. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25096. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  25097. this.mainSoundTrack.soundCollection[i].play();
  25098. }
  25099. }
  25100. for (i = 0; i < this.soundTracks.length; i++) {
  25101. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25102. if (this.soundTracks[i].soundCollection[j].isPaused) {
  25103. this.soundTracks[i].soundCollection[j].play();
  25104. }
  25105. }
  25106. }
  25107. };
  25108. Object.defineProperty(Scene.prototype, "headphone", {
  25109. get: function () {
  25110. return this._headphone;
  25111. },
  25112. set: function (value) {
  25113. this._headphone = value;
  25114. if (BABYLON.AudioEngine) {
  25115. if (this._headphone) {
  25116. this._switchAudioModeForHeadphones();
  25117. }
  25118. else {
  25119. this._switchAudioModeForNormalSpeakers();
  25120. }
  25121. }
  25122. },
  25123. enumerable: true,
  25124. configurable: true
  25125. });
  25126. Scene.prototype._switchAudioModeForHeadphones = function () {
  25127. this.mainSoundTrack.switchPanningModelToHRTF();
  25128. for (var i = 0; i < this.soundTracks.length; i++) {
  25129. this.soundTracks[i].switchPanningModelToHRTF();
  25130. }
  25131. };
  25132. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  25133. this.mainSoundTrack.switchPanningModelToEqualPower();
  25134. for (var i = 0; i < this.soundTracks.length; i++) {
  25135. this.soundTracks[i].switchPanningModelToEqualPower();
  25136. }
  25137. };
  25138. /**
  25139. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  25140. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  25141. * @returns the created depth renderer
  25142. */
  25143. Scene.prototype.enableDepthRenderer = function (camera) {
  25144. camera = camera || this.activeCamera;
  25145. if (!camera) {
  25146. throw "No camera available to enable depth renderer";
  25147. }
  25148. if (!this._depthRenderer[camera.id]) {
  25149. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  25150. }
  25151. return this._depthRenderer[camera.id];
  25152. };
  25153. /**
  25154. * Disables a depth renderer for a given camera
  25155. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  25156. */
  25157. Scene.prototype.disableDepthRenderer = function (camera) {
  25158. camera = camera || this.activeCamera;
  25159. if (!camera || !this._depthRenderer[camera.id]) {
  25160. return;
  25161. }
  25162. this._depthRenderer[camera.id].dispose();
  25163. delete this._depthRenderer[camera.id];
  25164. };
  25165. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  25166. if (ratio === void 0) { ratio = 1; }
  25167. if (this._geometryBufferRenderer) {
  25168. return this._geometryBufferRenderer;
  25169. }
  25170. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  25171. if (!this._geometryBufferRenderer.isSupported) {
  25172. this._geometryBufferRenderer = null;
  25173. }
  25174. return this._geometryBufferRenderer;
  25175. };
  25176. Scene.prototype.disableGeometryBufferRenderer = function () {
  25177. if (!this._geometryBufferRenderer) {
  25178. return;
  25179. }
  25180. this._geometryBufferRenderer.dispose();
  25181. this._geometryBufferRenderer = null;
  25182. };
  25183. Scene.prototype.freezeMaterials = function () {
  25184. for (var i = 0; i < this.materials.length; i++) {
  25185. this.materials[i].freeze();
  25186. }
  25187. };
  25188. Scene.prototype.unfreezeMaterials = function () {
  25189. for (var i = 0; i < this.materials.length; i++) {
  25190. this.materials[i].unfreeze();
  25191. }
  25192. };
  25193. Scene.prototype.dispose = function () {
  25194. this.beforeRender = null;
  25195. this.afterRender = null;
  25196. this.skeletons = [];
  25197. this.morphTargetManagers = [];
  25198. this.importedMeshesFiles = new Array();
  25199. this.stopAllAnimations();
  25200. this.resetCachedMaterial();
  25201. for (var key in this._depthRenderer) {
  25202. this._depthRenderer[key].dispose();
  25203. }
  25204. if (this._gamepadManager) {
  25205. this._gamepadManager.dispose();
  25206. this._gamepadManager = null;
  25207. }
  25208. // Smart arrays
  25209. if (this.activeCamera) {
  25210. this.activeCamera._activeMeshes.dispose();
  25211. this.activeCamera = null;
  25212. }
  25213. this._activeMeshes.dispose();
  25214. this._renderingManager.dispose();
  25215. this._processedMaterials.dispose();
  25216. this._activeParticleSystems.dispose();
  25217. this._activeSkeletons.dispose();
  25218. this._softwareSkinnedMeshes.dispose();
  25219. this._renderTargets.dispose();
  25220. this._registeredForLateAnimationBindings.dispose();
  25221. if (this._boundingBoxRenderer) {
  25222. this._boundingBoxRenderer.dispose();
  25223. }
  25224. this._meshesForIntersections.dispose();
  25225. this._toBeDisposed.dispose();
  25226. // Abort active requests
  25227. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  25228. var request = _a[_i];
  25229. request.abort();
  25230. }
  25231. // Debug layer
  25232. if (this._debugLayer) {
  25233. this._debugLayer.hide();
  25234. }
  25235. // Events
  25236. this.onDisposeObservable.notifyObservers(this);
  25237. this.onDisposeObservable.clear();
  25238. this.onBeforeRenderObservable.clear();
  25239. this.onAfterRenderObservable.clear();
  25240. this.OnBeforeRenderTargetsRenderObservable.clear();
  25241. this.OnAfterRenderTargetsRenderObservable.clear();
  25242. this.onAfterStepObservable.clear();
  25243. this.onBeforeStepObservable.clear();
  25244. this.onBeforeActiveMeshesEvaluationObservable.clear();
  25245. this.onAfterActiveMeshesEvaluationObservable.clear();
  25246. this.onBeforeParticlesRenderingObservable.clear();
  25247. this.onAfterParticlesRenderingObservable.clear();
  25248. this.onBeforeSpritesRenderingObservable.clear();
  25249. this.onAfterSpritesRenderingObservable.clear();
  25250. this.onBeforeDrawPhaseObservable.clear();
  25251. this.onAfterDrawPhaseObservable.clear();
  25252. this.onBeforePhysicsObservable.clear();
  25253. this.onAfterPhysicsObservable.clear();
  25254. this.onBeforeAnimationsObservable.clear();
  25255. this.onAfterAnimationsObservable.clear();
  25256. this.onDataLoadedObservable.clear();
  25257. this.detachControl();
  25258. // Release sounds & sounds tracks
  25259. if (BABYLON.AudioEngine) {
  25260. this.disposeSounds();
  25261. }
  25262. // VR Helper
  25263. if (this.VRHelper) {
  25264. this.VRHelper.dispose();
  25265. }
  25266. // Detach cameras
  25267. var canvas = this._engine.getRenderingCanvas();
  25268. if (canvas) {
  25269. var index;
  25270. for (index = 0; index < this.cameras.length; index++) {
  25271. this.cameras[index].detachControl(canvas);
  25272. }
  25273. }
  25274. // Release animation groups
  25275. while (this.animationGroups.length) {
  25276. this.animationGroups[0].dispose();
  25277. }
  25278. // Release lights
  25279. while (this.lights.length) {
  25280. this.lights[0].dispose();
  25281. }
  25282. // Release meshes
  25283. while (this.meshes.length) {
  25284. this.meshes[0].dispose(true);
  25285. }
  25286. while (this.transformNodes.length) {
  25287. this.removeTransformNode(this.transformNodes[0]);
  25288. }
  25289. // Release cameras
  25290. while (this.cameras.length) {
  25291. this.cameras[0].dispose();
  25292. }
  25293. // Release materials
  25294. if (this.defaultMaterial) {
  25295. this.defaultMaterial.dispose();
  25296. }
  25297. while (this.multiMaterials.length) {
  25298. this.multiMaterials[0].dispose();
  25299. }
  25300. while (this.materials.length) {
  25301. this.materials[0].dispose();
  25302. }
  25303. // Release particles
  25304. while (this.particleSystems.length) {
  25305. this.particleSystems[0].dispose();
  25306. }
  25307. // Release sprites
  25308. while (this.spriteManagers.length) {
  25309. this.spriteManagers[0].dispose();
  25310. }
  25311. // Release postProcesses
  25312. while (this.postProcesses.length) {
  25313. this.postProcesses[0].dispose();
  25314. }
  25315. // Release layers
  25316. while (this.layers.length) {
  25317. this.layers[0].dispose();
  25318. }
  25319. while (this.effectLayers.length) {
  25320. this.effectLayers[0].dispose();
  25321. }
  25322. // Release textures
  25323. while (this.textures.length) {
  25324. this.textures[0].dispose();
  25325. }
  25326. // Release UBO
  25327. this._sceneUbo.dispose();
  25328. if (this._alternateSceneUbo) {
  25329. this._alternateSceneUbo.dispose();
  25330. }
  25331. // Post-processes
  25332. this.postProcessManager.dispose();
  25333. if (this._postProcessRenderPipelineManager) {
  25334. this._postProcessRenderPipelineManager.dispose();
  25335. }
  25336. // Physics
  25337. if (this._physicsEngine) {
  25338. this.disablePhysicsEngine();
  25339. }
  25340. // Remove from engine
  25341. index = this._engine.scenes.indexOf(this);
  25342. if (index > -1) {
  25343. this._engine.scenes.splice(index, 1);
  25344. }
  25345. this._engine.wipeCaches(true);
  25346. this._isDisposed = true;
  25347. };
  25348. Object.defineProperty(Scene.prototype, "isDisposed", {
  25349. get: function () {
  25350. return this._isDisposed;
  25351. },
  25352. enumerable: true,
  25353. configurable: true
  25354. });
  25355. // Release sounds & sounds tracks
  25356. Scene.prototype.disposeSounds = function () {
  25357. if (!this._mainSoundTrack) {
  25358. return;
  25359. }
  25360. this.mainSoundTrack.dispose();
  25361. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  25362. this.soundTracks[scIndex].dispose();
  25363. }
  25364. };
  25365. // Octrees
  25366. /**
  25367. * Get the world extend vectors with an optional filter
  25368. *
  25369. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  25370. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  25371. */
  25372. Scene.prototype.getWorldExtends = function (filterPredicate) {
  25373. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  25374. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  25375. filterPredicate = filterPredicate || (function () { return true; });
  25376. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  25377. mesh.computeWorldMatrix(true);
  25378. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  25379. return;
  25380. }
  25381. var boundingInfo = mesh.getBoundingInfo();
  25382. var minBox = boundingInfo.boundingBox.minimumWorld;
  25383. var maxBox = boundingInfo.boundingBox.maximumWorld;
  25384. BABYLON.Tools.CheckExtends(minBox, min, max);
  25385. BABYLON.Tools.CheckExtends(maxBox, min, max);
  25386. });
  25387. return {
  25388. min: min,
  25389. max: max
  25390. };
  25391. };
  25392. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  25393. if (maxCapacity === void 0) { maxCapacity = 64; }
  25394. if (maxDepth === void 0) { maxDepth = 2; }
  25395. if (!this._selectionOctree) {
  25396. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  25397. }
  25398. var worldExtends = this.getWorldExtends();
  25399. // Update octree
  25400. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  25401. return this._selectionOctree;
  25402. };
  25403. // Picking
  25404. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  25405. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25406. var result = BABYLON.Ray.Zero();
  25407. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  25408. return result;
  25409. };
  25410. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  25411. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25412. var engine = this._engine;
  25413. if (!camera) {
  25414. if (!this.activeCamera)
  25415. throw new Error("Active camera not set");
  25416. camera = this.activeCamera;
  25417. }
  25418. var cameraViewport = camera.viewport;
  25419. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25420. // Moving coordinates to local viewport world
  25421. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25422. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25423. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  25424. return this;
  25425. };
  25426. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  25427. var result = BABYLON.Ray.Zero();
  25428. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  25429. return result;
  25430. };
  25431. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  25432. if (!BABYLON.PickingInfo) {
  25433. return this;
  25434. }
  25435. var engine = this._engine;
  25436. if (!camera) {
  25437. if (!this.activeCamera)
  25438. throw new Error("Active camera not set");
  25439. camera = this.activeCamera;
  25440. }
  25441. var cameraViewport = camera.viewport;
  25442. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25443. var identity = BABYLON.Matrix.Identity();
  25444. // Moving coordinates to local viewport world
  25445. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25446. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25447. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  25448. return this;
  25449. };
  25450. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  25451. if (!BABYLON.PickingInfo) {
  25452. return null;
  25453. }
  25454. var pickingInfo = null;
  25455. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25456. var mesh = this.meshes[meshIndex];
  25457. if (predicate) {
  25458. if (!predicate(mesh)) {
  25459. continue;
  25460. }
  25461. }
  25462. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25463. continue;
  25464. }
  25465. var world = mesh.getWorldMatrix();
  25466. var ray = rayFunction(world);
  25467. var result = mesh.intersects(ray, fastCheck);
  25468. if (!result || !result.hit)
  25469. continue;
  25470. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25471. continue;
  25472. pickingInfo = result;
  25473. if (fastCheck) {
  25474. break;
  25475. }
  25476. }
  25477. return pickingInfo || new BABYLON.PickingInfo();
  25478. };
  25479. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  25480. if (!BABYLON.PickingInfo) {
  25481. return null;
  25482. }
  25483. var pickingInfos = new Array();
  25484. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25485. var mesh = this.meshes[meshIndex];
  25486. if (predicate) {
  25487. if (!predicate(mesh)) {
  25488. continue;
  25489. }
  25490. }
  25491. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25492. continue;
  25493. }
  25494. var world = mesh.getWorldMatrix();
  25495. var ray = rayFunction(world);
  25496. var result = mesh.intersects(ray, false);
  25497. if (!result || !result.hit)
  25498. continue;
  25499. pickingInfos.push(result);
  25500. }
  25501. return pickingInfos;
  25502. };
  25503. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  25504. if (!BABYLON.PickingInfo) {
  25505. return null;
  25506. }
  25507. var pickingInfo = null;
  25508. if (!camera) {
  25509. if (!this.activeCamera) {
  25510. return null;
  25511. }
  25512. camera = this.activeCamera;
  25513. }
  25514. if (this.spriteManagers.length > 0) {
  25515. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  25516. var spriteManager = this.spriteManagers[spriteIndex];
  25517. if (!spriteManager.isPickable) {
  25518. continue;
  25519. }
  25520. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  25521. if (!result || !result.hit)
  25522. continue;
  25523. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25524. continue;
  25525. pickingInfo = result;
  25526. if (fastCheck) {
  25527. break;
  25528. }
  25529. }
  25530. }
  25531. return pickingInfo || new BABYLON.PickingInfo();
  25532. };
  25533. /** Launch a ray to try to pick a mesh in the scene
  25534. * @param x position on screen
  25535. * @param y position on screen
  25536. * @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
  25537. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25538. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25539. */
  25540. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  25541. var _this = this;
  25542. if (!BABYLON.PickingInfo) {
  25543. return null;
  25544. }
  25545. return this._internalPick(function (world) {
  25546. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  25547. return _this._tempPickingRay;
  25548. }, predicate, fastCheck);
  25549. };
  25550. /** Launch a ray to try to pick a sprite in the scene
  25551. * @param x position on screen
  25552. * @param y position on screen
  25553. * @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
  25554. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25555. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25556. */
  25557. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  25558. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  25559. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  25560. };
  25561. /** Use the given ray to pick a mesh in the scene
  25562. * @param ray The ray to use to pick meshes
  25563. * @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
  25564. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25565. */
  25566. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  25567. var _this = this;
  25568. return this._internalPick(function (world) {
  25569. if (!_this._pickWithRayInverseMatrix) {
  25570. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25571. }
  25572. world.invertToRef(_this._pickWithRayInverseMatrix);
  25573. if (!_this._cachedRayForTransform) {
  25574. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25575. }
  25576. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25577. return _this._cachedRayForTransform;
  25578. }, predicate, fastCheck);
  25579. };
  25580. /**
  25581. * Launch a ray to try to pick a mesh in the scene
  25582. * @param x X position on screen
  25583. * @param y Y position on screen
  25584. * @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
  25585. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25586. */
  25587. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  25588. var _this = this;
  25589. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  25590. };
  25591. /**
  25592. * Launch a ray to try to pick a mesh in the scene
  25593. * @param ray Ray to use
  25594. * @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
  25595. */
  25596. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  25597. var _this = this;
  25598. return this._internalMultiPick(function (world) {
  25599. if (!_this._pickWithRayInverseMatrix) {
  25600. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25601. }
  25602. world.invertToRef(_this._pickWithRayInverseMatrix);
  25603. if (!_this._cachedRayForTransform) {
  25604. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25605. }
  25606. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25607. return _this._cachedRayForTransform;
  25608. }, predicate);
  25609. };
  25610. Scene.prototype.setPointerOverMesh = function (mesh) {
  25611. if (this._pointerOverMesh === mesh) {
  25612. return;
  25613. }
  25614. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25615. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25616. }
  25617. this._pointerOverMesh = mesh;
  25618. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25619. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25620. }
  25621. };
  25622. Scene.prototype.getPointerOverMesh = function () {
  25623. return this._pointerOverMesh;
  25624. };
  25625. Scene.prototype.setPointerOverSprite = function (sprite) {
  25626. if (this._pointerOverSprite === sprite) {
  25627. return;
  25628. }
  25629. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25630. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25631. }
  25632. this._pointerOverSprite = sprite;
  25633. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25634. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25635. }
  25636. };
  25637. Scene.prototype.getPointerOverSprite = function () {
  25638. return this._pointerOverSprite;
  25639. };
  25640. // Physics
  25641. Scene.prototype.getPhysicsEngine = function () {
  25642. return this._physicsEngine;
  25643. };
  25644. /**
  25645. * Enables physics to the current scene
  25646. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25647. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25648. * @return {boolean} was the physics engine initialized
  25649. */
  25650. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25651. if (gravity === void 0) { gravity = null; }
  25652. if (this._physicsEngine) {
  25653. return true;
  25654. }
  25655. try {
  25656. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25657. return true;
  25658. }
  25659. catch (e) {
  25660. BABYLON.Tools.Error(e.message);
  25661. return false;
  25662. }
  25663. };
  25664. Scene.prototype.disablePhysicsEngine = function () {
  25665. if (!this._physicsEngine) {
  25666. return;
  25667. }
  25668. this._physicsEngine.dispose();
  25669. this._physicsEngine = null;
  25670. };
  25671. Scene.prototype.isPhysicsEnabled = function () {
  25672. return this._physicsEngine !== undefined;
  25673. };
  25674. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25675. var mesh = compound.parts[0].mesh;
  25676. if (mesh.physicsImpostor) {
  25677. mesh.physicsImpostor.dispose();
  25678. mesh.physicsImpostor = null;
  25679. }
  25680. };
  25681. // Misc.
  25682. Scene.prototype._rebuildGeometries = function () {
  25683. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25684. var geometry = _a[_i];
  25685. geometry._rebuild();
  25686. }
  25687. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25688. var mesh = _c[_b];
  25689. mesh._rebuild();
  25690. }
  25691. if (this.postProcessManager) {
  25692. this.postProcessManager._rebuild();
  25693. }
  25694. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25695. var layer = _e[_d];
  25696. layer._rebuild();
  25697. }
  25698. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25699. var effectLayer = _g[_f];
  25700. effectLayer._rebuild();
  25701. }
  25702. if (this._boundingBoxRenderer) {
  25703. this._boundingBoxRenderer._rebuild();
  25704. }
  25705. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25706. var system = _j[_h];
  25707. system.rebuild();
  25708. }
  25709. if (this._postProcessRenderPipelineManager) {
  25710. this._postProcessRenderPipelineManager._rebuild();
  25711. }
  25712. };
  25713. Scene.prototype._rebuildTextures = function () {
  25714. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25715. var texture = _a[_i];
  25716. texture._rebuild();
  25717. }
  25718. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25719. };
  25720. /**
  25721. * Creates a default light for the scene.
  25722. * @param replace Whether to replace the existing lights in the scene.
  25723. */
  25724. Scene.prototype.createDefaultLight = function (replace) {
  25725. if (replace === void 0) { replace = false; }
  25726. // Dispose existing light in replace mode.
  25727. if (replace) {
  25728. if (this.lights) {
  25729. for (var i = 0; i < this.lights.length; i++) {
  25730. this.lights[i].dispose();
  25731. }
  25732. }
  25733. }
  25734. // Light
  25735. if (this.lights.length === 0) {
  25736. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25737. }
  25738. };
  25739. /**
  25740. * Creates a default camera for the scene.
  25741. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25742. * @param replace Whether to replace the existing active camera in the scene.
  25743. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25744. */
  25745. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25746. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25747. if (replace === void 0) { replace = false; }
  25748. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25749. // Dispose existing camera in replace mode.
  25750. if (replace) {
  25751. if (this.activeCamera) {
  25752. this.activeCamera.dispose();
  25753. this.activeCamera = null;
  25754. }
  25755. }
  25756. // Camera
  25757. if (!this.activeCamera) {
  25758. var worldExtends = this.getWorldExtends();
  25759. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25760. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25761. var camera;
  25762. var radius = worldSize.length() * 1.5;
  25763. // empty scene scenario!
  25764. if (!isFinite(radius)) {
  25765. radius = 1;
  25766. worldCenter.copyFromFloats(0, 0, 0);
  25767. }
  25768. if (createArcRotateCamera) {
  25769. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25770. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25771. arcRotateCamera.wheelPrecision = 100 / radius;
  25772. camera = arcRotateCamera;
  25773. }
  25774. else {
  25775. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25776. freeCamera.setTarget(worldCenter);
  25777. camera = freeCamera;
  25778. }
  25779. camera.minZ = radius * 0.01;
  25780. camera.maxZ = radius * 1000;
  25781. camera.speed = radius * 0.2;
  25782. this.activeCamera = camera;
  25783. var canvas = this.getEngine().getRenderingCanvas();
  25784. if (attachCameraControls && canvas) {
  25785. camera.attachControl(canvas);
  25786. }
  25787. }
  25788. };
  25789. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25790. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25791. if (replace === void 0) { replace = false; }
  25792. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25793. this.createDefaultLight(replace);
  25794. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25795. };
  25796. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25797. if (pbr === void 0) { pbr = false; }
  25798. if (scale === void 0) { scale = 1000; }
  25799. if (blur === void 0) { blur = 0; }
  25800. if (environmentTexture) {
  25801. this.environmentTexture = environmentTexture;
  25802. }
  25803. if (!this.environmentTexture) {
  25804. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25805. return null;
  25806. }
  25807. // Skybox
  25808. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25809. if (pbr) {
  25810. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25811. hdrSkyboxMaterial.backFaceCulling = false;
  25812. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25813. if (hdrSkyboxMaterial.reflectionTexture) {
  25814. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25815. }
  25816. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25817. hdrSkyboxMaterial.disableLighting = true;
  25818. hdrSkyboxMaterial.twoSidedLighting = true;
  25819. hdrSkybox.infiniteDistance = true;
  25820. hdrSkybox.material = hdrSkyboxMaterial;
  25821. }
  25822. else {
  25823. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25824. skyboxMaterial.backFaceCulling = false;
  25825. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25826. if (skyboxMaterial.reflectionTexture) {
  25827. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25828. }
  25829. skyboxMaterial.disableLighting = true;
  25830. hdrSkybox.infiniteDistance = true;
  25831. hdrSkybox.material = skyboxMaterial;
  25832. }
  25833. return hdrSkybox;
  25834. };
  25835. Scene.prototype.createDefaultEnvironment = function (options) {
  25836. if (BABYLON.EnvironmentHelper) {
  25837. return new BABYLON.EnvironmentHelper(options, this);
  25838. }
  25839. return null;
  25840. };
  25841. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25842. if (webVROptions === void 0) { webVROptions = {}; }
  25843. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25844. };
  25845. // Tags
  25846. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25847. if (tagsQuery === undefined) {
  25848. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25849. return list;
  25850. }
  25851. var listByTags = [];
  25852. forEach = forEach || (function (item) { return; });
  25853. for (var i in list) {
  25854. var item = list[i];
  25855. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25856. listByTags.push(item);
  25857. forEach(item);
  25858. }
  25859. }
  25860. return listByTags;
  25861. };
  25862. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25863. return this._getByTags(this.meshes, tagsQuery, forEach);
  25864. };
  25865. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25866. return this._getByTags(this.cameras, tagsQuery, forEach);
  25867. };
  25868. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25869. return this._getByTags(this.lights, tagsQuery, forEach);
  25870. };
  25871. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25872. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25873. };
  25874. /**
  25875. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25876. * This allowed control for front to back rendering or reversly depending of the special needs.
  25877. *
  25878. * @param renderingGroupId The rendering group id corresponding to its index
  25879. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25880. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25881. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25882. */
  25883. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25884. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25885. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25886. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25887. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25888. };
  25889. /**
  25890. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25891. *
  25892. * @param renderingGroupId The rendering group id corresponding to its index
  25893. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25894. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25895. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25896. */
  25897. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25898. if (depth === void 0) { depth = true; }
  25899. if (stencil === void 0) { stencil = true; }
  25900. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25901. };
  25902. /**
  25903. * Will flag all materials as dirty to trigger new shader compilation
  25904. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25905. */
  25906. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25907. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25908. var material = _a[_i];
  25909. if (predicate && !predicate(material)) {
  25910. continue;
  25911. }
  25912. material.markAsDirty(flag);
  25913. }
  25914. };
  25915. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25916. var _this = this;
  25917. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25918. this._activeRequests.push(request);
  25919. request.onCompleteObservable.add(function (request) {
  25920. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25921. });
  25922. return request;
  25923. };
  25924. /** @ignore */
  25925. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25926. var _this = this;
  25927. return new Promise(function (resolve, reject) {
  25928. _this._loadFile(url, function (data) {
  25929. resolve(data);
  25930. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25931. reject(exception);
  25932. });
  25933. });
  25934. };
  25935. // Statics
  25936. Scene._FOGMODE_NONE = 0;
  25937. Scene._FOGMODE_EXP = 1;
  25938. Scene._FOGMODE_EXP2 = 2;
  25939. Scene._FOGMODE_LINEAR = 3;
  25940. Scene._uniqueIdCounter = 0;
  25941. Scene.MinDeltaTime = 1.0;
  25942. Scene.MaxDeltaTime = 1000.0;
  25943. /** The distance in pixel that you have to move to prevent some events */
  25944. Scene.DragMovementThreshold = 10; // in pixels
  25945. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25946. Scene.LongPressDelay = 500; // in milliseconds
  25947. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25948. Scene.DoubleClickDelay = 300; // in milliseconds
  25949. /** If you need to check double click without raising a single click at first click, enable this flag */
  25950. Scene.ExclusiveDoubleClickMode = false;
  25951. return Scene;
  25952. }());
  25953. BABYLON.Scene = Scene;
  25954. })(BABYLON || (BABYLON = {}));
  25955. //# sourceMappingURL=babylon.scene.js.map
  25956. "use strict";
  25957. var BABYLON;
  25958. (function (BABYLON) {
  25959. /**
  25960. * Set of assets to keep when moving a scene into an asset container.
  25961. */
  25962. var KeepAssets = /** @class */ (function () {
  25963. function KeepAssets() {
  25964. /**
  25965. * Cameras to keep.
  25966. */
  25967. this.cameras = new Array();
  25968. /**
  25969. * Lights to keep.
  25970. */
  25971. this.lights = new Array();
  25972. /**
  25973. * Meshes to keep.
  25974. */
  25975. this.meshes = new Array();
  25976. /**
  25977. * Skeletons to keep.
  25978. */
  25979. this.skeletons = new Array();
  25980. /**
  25981. * ParticleSystems to keep.
  25982. */
  25983. this.particleSystems = new Array();
  25984. /**
  25985. * Animations to keep.
  25986. */
  25987. this.animations = new Array();
  25988. /**
  25989. * MultiMaterials to keep.
  25990. */
  25991. this.multiMaterials = new Array();
  25992. /**
  25993. * Materials to keep.
  25994. */
  25995. this.materials = new Array();
  25996. /**
  25997. * MorphTargetManagers to keep.
  25998. */
  25999. this.morphTargetManagers = new Array();
  26000. /**
  26001. * Geometries to keep.
  26002. */
  26003. this.geometries = new Array();
  26004. /**
  26005. * TransformNodes to keep.
  26006. */
  26007. this.transformNodes = new Array();
  26008. /**
  26009. * LensFlareSystems to keep.
  26010. */
  26011. this.lensFlareSystems = new Array();
  26012. /**
  26013. * ShadowGenerators to keep.
  26014. */
  26015. this.shadowGenerators = new Array();
  26016. /**
  26017. * ActionManagers to keep.
  26018. */
  26019. this.actionManagers = new Array();
  26020. /**
  26021. * Sounds to keep.
  26022. */
  26023. this.sounds = new Array();
  26024. }
  26025. return KeepAssets;
  26026. }());
  26027. BABYLON.KeepAssets = KeepAssets;
  26028. /**
  26029. * Container with a set of assets that can be added or removed from a scene.
  26030. */
  26031. var AssetContainer = /** @class */ (function () {
  26032. /**
  26033. * Instantiates an AssetContainer.
  26034. * @param scene The scene the AssetContainer belongs to.
  26035. */
  26036. function AssetContainer(scene) {
  26037. // Objects
  26038. /**
  26039. * Cameras populated in the container.
  26040. */
  26041. this.cameras = new Array();
  26042. /**
  26043. * Lights populated in the container.
  26044. */
  26045. this.lights = new Array();
  26046. /**
  26047. * Meshes populated in the container.
  26048. */
  26049. this.meshes = new Array();
  26050. /**
  26051. * Skeletons populated in the container.
  26052. */
  26053. this.skeletons = new Array();
  26054. /**
  26055. * ParticleSystems populated in the container.
  26056. */
  26057. this.particleSystems = new Array();
  26058. /**
  26059. * Animations populated in the container.
  26060. */
  26061. this.animations = new Array();
  26062. /**
  26063. * MultiMaterials populated in the container.
  26064. */
  26065. this.multiMaterials = new Array();
  26066. /**
  26067. * Materials populated in the container.
  26068. */
  26069. this.materials = new Array();
  26070. /**
  26071. * MorphTargetManagers populated in the container.
  26072. */
  26073. this.morphTargetManagers = new Array();
  26074. /**
  26075. * Geometries populated in the container.
  26076. */
  26077. this.geometries = new Array();
  26078. /**
  26079. * TransformNodes populated in the container.
  26080. */
  26081. this.transformNodes = new Array();
  26082. /**
  26083. * LensFlareSystems populated in the container.
  26084. */
  26085. this.lensFlareSystems = new Array();
  26086. /**
  26087. * ShadowGenerators populated in the container.
  26088. */
  26089. this.shadowGenerators = new Array();
  26090. /**
  26091. * ActionManagers populated in the container.
  26092. */
  26093. this.actionManagers = new Array();
  26094. /**
  26095. * Sounds populated in the container.
  26096. */
  26097. this.sounds = new Array();
  26098. this.scene = scene;
  26099. }
  26100. /**
  26101. * Adds all the assets from the container to the scene.
  26102. */
  26103. AssetContainer.prototype.addAllToScene = function () {
  26104. var _this = this;
  26105. this.cameras.forEach(function (o) {
  26106. _this.scene.addCamera(o);
  26107. });
  26108. this.lights.forEach(function (o) {
  26109. _this.scene.addLight(o);
  26110. });
  26111. this.meshes.forEach(function (o) {
  26112. _this.scene.addMesh(o);
  26113. });
  26114. this.skeletons.forEach(function (o) {
  26115. _this.scene.addSkeleton(o);
  26116. });
  26117. this.particleSystems.forEach(function (o) {
  26118. _this.scene.addParticleSystem(o);
  26119. });
  26120. this.animations.forEach(function (o) {
  26121. _this.scene.addAnimation(o);
  26122. });
  26123. this.multiMaterials.forEach(function (o) {
  26124. _this.scene.addMultiMaterial(o);
  26125. });
  26126. this.materials.forEach(function (o) {
  26127. _this.scene.addMaterial(o);
  26128. });
  26129. this.morphTargetManagers.forEach(function (o) {
  26130. _this.scene.addMorphTargetManager(o);
  26131. });
  26132. this.geometries.forEach(function (o) {
  26133. _this.scene.addGeometry(o);
  26134. });
  26135. this.transformNodes.forEach(function (o) {
  26136. _this.scene.addTransformNode(o);
  26137. });
  26138. this.lensFlareSystems.forEach(function (o) {
  26139. _this.scene.addLensFlareSystem(o);
  26140. });
  26141. this.actionManagers.forEach(function (o) {
  26142. _this.scene.addActionManager(o);
  26143. });
  26144. this.sounds.forEach(function (o) {
  26145. o.play();
  26146. o.autoplay = true;
  26147. _this.scene.mainSoundTrack.AddSound(o);
  26148. });
  26149. };
  26150. /**
  26151. * Removes all the assets in the container from the scene
  26152. */
  26153. AssetContainer.prototype.removeAllFromScene = function () {
  26154. var _this = this;
  26155. this.cameras.forEach(function (o) {
  26156. _this.scene.removeCamera(o);
  26157. });
  26158. this.lights.forEach(function (o) {
  26159. _this.scene.removeLight(o);
  26160. });
  26161. this.meshes.forEach(function (o) {
  26162. _this.scene.removeMesh(o);
  26163. });
  26164. this.skeletons.forEach(function (o) {
  26165. _this.scene.removeSkeleton(o);
  26166. });
  26167. this.particleSystems.forEach(function (o) {
  26168. _this.scene.removeParticleSystem(o);
  26169. });
  26170. this.animations.forEach(function (o) {
  26171. _this.scene.removeAnimation(o);
  26172. });
  26173. this.multiMaterials.forEach(function (o) {
  26174. _this.scene.removeMultiMaterial(o);
  26175. });
  26176. this.materials.forEach(function (o) {
  26177. _this.scene.removeMaterial(o);
  26178. });
  26179. this.morphTargetManagers.forEach(function (o) {
  26180. _this.scene.removeMorphTargetManager(o);
  26181. });
  26182. this.geometries.forEach(function (o) {
  26183. _this.scene.removeGeometry(o);
  26184. });
  26185. this.transformNodes.forEach(function (o) {
  26186. _this.scene.removeTransformNode(o);
  26187. });
  26188. this.lensFlareSystems.forEach(function (o) {
  26189. _this.scene.removeLensFlareSystem(o);
  26190. });
  26191. this.actionManagers.forEach(function (o) {
  26192. _this.scene.removeActionManager(o);
  26193. });
  26194. this.sounds.forEach(function (o) {
  26195. o.stop();
  26196. o.autoplay = false;
  26197. _this.scene.mainSoundTrack.RemoveSound(o);
  26198. });
  26199. };
  26200. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  26201. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  26202. var asset = sourceAssets_1[_i];
  26203. var move = true;
  26204. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  26205. var keepAsset = keepAssets_1[_a];
  26206. if (asset === keepAsset) {
  26207. move = false;
  26208. break;
  26209. }
  26210. }
  26211. if (move) {
  26212. targetAssets.push(asset);
  26213. }
  26214. }
  26215. };
  26216. /**
  26217. * Removes all the assets contained in the scene and adds them to the container.
  26218. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  26219. */
  26220. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  26221. if (keepAssets === undefined) {
  26222. keepAssets = new KeepAssets();
  26223. }
  26224. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  26225. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  26226. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  26227. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  26228. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  26229. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  26230. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  26231. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  26232. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  26233. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  26234. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  26235. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  26236. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  26237. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  26238. this.removeAllFromScene();
  26239. };
  26240. return AssetContainer;
  26241. }());
  26242. BABYLON.AssetContainer = AssetContainer;
  26243. })(BABYLON || (BABYLON = {}));
  26244. //# sourceMappingURL=babylon.assetContainer.js.map
  26245. "use strict";
  26246. var BABYLON;
  26247. (function (BABYLON) {
  26248. var Buffer = /** @class */ (function () {
  26249. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  26250. if (instanced === void 0) { instanced = false; }
  26251. if (engine instanceof BABYLON.Mesh) {
  26252. this._engine = engine.getScene().getEngine();
  26253. }
  26254. else {
  26255. this._engine = engine;
  26256. }
  26257. this._updatable = updatable;
  26258. this._instanced = instanced;
  26259. this._data = data;
  26260. this._strideSize = stride;
  26261. if (!postponeInternalCreation) {
  26262. this.create();
  26263. }
  26264. }
  26265. /**
  26266. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  26267. * @param kind defines the vertex buffer kind (position, normal, etc.)
  26268. * @param offset defines offset in the buffer (0 by default)
  26269. * @param size defines the size in floats of attributes (position is 3 for instance)
  26270. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  26271. * @param instanced defines if the vertex buffer contains indexed data
  26272. * @returns the new vertex buffer
  26273. */
  26274. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  26275. // a lot of these parameters are ignored as they are overriden by the buffer
  26276. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  26277. };
  26278. // Properties
  26279. Buffer.prototype.isUpdatable = function () {
  26280. return this._updatable;
  26281. };
  26282. Buffer.prototype.getData = function () {
  26283. return this._data;
  26284. };
  26285. Buffer.prototype.getBuffer = function () {
  26286. return this._buffer;
  26287. };
  26288. Buffer.prototype.getStrideSize = function () {
  26289. return this._strideSize;
  26290. };
  26291. // public getIsInstanced(): boolean {
  26292. // return this._instanced;
  26293. // }
  26294. // public get instanceDivisor(): number {
  26295. // return this._instanceDivisor;
  26296. // }
  26297. // public set instanceDivisor(value: number) {
  26298. // this._instanceDivisor = value;
  26299. // if (value == 0) {
  26300. // this._instanced = false;
  26301. // } else {
  26302. // this._instanced = true;
  26303. // }
  26304. // }
  26305. // Methods
  26306. Buffer.prototype.create = function (data) {
  26307. if (data === void 0) { data = null; }
  26308. if (!data && this._buffer) {
  26309. return; // nothing to do
  26310. }
  26311. data = data || this._data;
  26312. if (!data) {
  26313. return;
  26314. }
  26315. if (!this._buffer) {
  26316. if (this._updatable) {
  26317. this._buffer = this._engine.createDynamicVertexBuffer(data);
  26318. this._data = data;
  26319. }
  26320. else {
  26321. this._buffer = this._engine.createVertexBuffer(data);
  26322. }
  26323. }
  26324. else if (this._updatable) {
  26325. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  26326. this._data = data;
  26327. }
  26328. };
  26329. Buffer.prototype._rebuild = function () {
  26330. this._buffer = null;
  26331. this.create(this._data);
  26332. };
  26333. Buffer.prototype.update = function (data) {
  26334. this.create(data);
  26335. };
  26336. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  26337. if (!this._buffer) {
  26338. return;
  26339. }
  26340. if (this._updatable) {
  26341. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  26342. this._data = null;
  26343. }
  26344. };
  26345. Buffer.prototype.dispose = function () {
  26346. if (!this._buffer) {
  26347. return;
  26348. }
  26349. if (this._engine._releaseBuffer(this._buffer)) {
  26350. this._buffer = null;
  26351. }
  26352. };
  26353. return Buffer;
  26354. }());
  26355. BABYLON.Buffer = Buffer;
  26356. })(BABYLON || (BABYLON = {}));
  26357. //# sourceMappingURL=babylon.buffer.js.map
  26358. "use strict";
  26359. var BABYLON;
  26360. (function (BABYLON) {
  26361. var VertexBuffer = /** @class */ (function () {
  26362. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  26363. if (data instanceof BABYLON.Buffer) {
  26364. if (!stride) {
  26365. stride = data.getStrideSize();
  26366. }
  26367. this._buffer = data;
  26368. this._ownsBuffer = false;
  26369. }
  26370. else {
  26371. if (!stride) {
  26372. stride = VertexBuffer.DeduceStride(kind);
  26373. }
  26374. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  26375. this._ownsBuffer = true;
  26376. }
  26377. this._stride = stride;
  26378. this._instanced = instanced !== undefined ? instanced : false;
  26379. this._instanceDivisor = instanced ? 1 : 0;
  26380. this._offset = offset ? offset : 0;
  26381. this._size = size ? size : stride;
  26382. this._kind = kind;
  26383. }
  26384. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  26385. /**
  26386. * Gets or sets the instance divisor when in instanced mode
  26387. */
  26388. get: function () {
  26389. return this._instanceDivisor;
  26390. },
  26391. set: function (value) {
  26392. this._instanceDivisor = value;
  26393. if (value == 0) {
  26394. this._instanced = false;
  26395. }
  26396. else {
  26397. this._instanced = true;
  26398. }
  26399. },
  26400. enumerable: true,
  26401. configurable: true
  26402. });
  26403. VertexBuffer.prototype._rebuild = function () {
  26404. if (!this._buffer) {
  26405. return;
  26406. }
  26407. this._buffer._rebuild();
  26408. };
  26409. /**
  26410. * Returns the kind of the VertexBuffer (string).
  26411. */
  26412. VertexBuffer.prototype.getKind = function () {
  26413. return this._kind;
  26414. };
  26415. // Properties
  26416. /**
  26417. * Boolean : is the VertexBuffer updatable ?
  26418. */
  26419. VertexBuffer.prototype.isUpdatable = function () {
  26420. return this._buffer.isUpdatable();
  26421. };
  26422. /**
  26423. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  26424. */
  26425. VertexBuffer.prototype.getData = function () {
  26426. return this._buffer.getData();
  26427. };
  26428. /**
  26429. * Returns the WebGLBuffer associated to the VertexBuffer.
  26430. */
  26431. VertexBuffer.prototype.getBuffer = function () {
  26432. return this._buffer.getBuffer();
  26433. };
  26434. /**
  26435. * Returns the stride of the VertexBuffer (integer).
  26436. */
  26437. VertexBuffer.prototype.getStrideSize = function () {
  26438. return this._stride;
  26439. };
  26440. /**
  26441. * Returns the offset (integer).
  26442. */
  26443. VertexBuffer.prototype.getOffset = function () {
  26444. return this._offset;
  26445. };
  26446. /**
  26447. * Returns the VertexBuffer total size (integer).
  26448. */
  26449. VertexBuffer.prototype.getSize = function () {
  26450. return this._size;
  26451. };
  26452. /**
  26453. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  26454. */
  26455. VertexBuffer.prototype.getIsInstanced = function () {
  26456. return this._instanced;
  26457. };
  26458. /**
  26459. * Returns the instancing divisor, zero for non-instanced (integer).
  26460. */
  26461. VertexBuffer.prototype.getInstanceDivisor = function () {
  26462. return this._instanceDivisor;
  26463. };
  26464. // Methods
  26465. /**
  26466. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  26467. * Returns the created WebGLBuffer.
  26468. */
  26469. VertexBuffer.prototype.create = function (data) {
  26470. return this._buffer.create(data);
  26471. };
  26472. /**
  26473. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26474. * This function will create a new buffer if the current one is not updatable
  26475. * Returns the updated WebGLBuffer.
  26476. */
  26477. VertexBuffer.prototype.update = function (data) {
  26478. return this._buffer.update(data);
  26479. };
  26480. /**
  26481. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26482. * Returns the directly updated WebGLBuffer.
  26483. */
  26484. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  26485. return this._buffer.updateDirectly(data, offset);
  26486. };
  26487. /**
  26488. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  26489. */
  26490. VertexBuffer.prototype.dispose = function () {
  26491. if (this._ownsBuffer) {
  26492. this._buffer.dispose();
  26493. }
  26494. };
  26495. Object.defineProperty(VertexBuffer, "PositionKind", {
  26496. get: function () {
  26497. return VertexBuffer._PositionKind;
  26498. },
  26499. enumerable: true,
  26500. configurable: true
  26501. });
  26502. Object.defineProperty(VertexBuffer, "NormalKind", {
  26503. get: function () {
  26504. return VertexBuffer._NormalKind;
  26505. },
  26506. enumerable: true,
  26507. configurable: true
  26508. });
  26509. Object.defineProperty(VertexBuffer, "TangentKind", {
  26510. get: function () {
  26511. return VertexBuffer._TangentKind;
  26512. },
  26513. enumerable: true,
  26514. configurable: true
  26515. });
  26516. Object.defineProperty(VertexBuffer, "UVKind", {
  26517. get: function () {
  26518. return VertexBuffer._UVKind;
  26519. },
  26520. enumerable: true,
  26521. configurable: true
  26522. });
  26523. Object.defineProperty(VertexBuffer, "UV2Kind", {
  26524. get: function () {
  26525. return VertexBuffer._UV2Kind;
  26526. },
  26527. enumerable: true,
  26528. configurable: true
  26529. });
  26530. Object.defineProperty(VertexBuffer, "UV3Kind", {
  26531. get: function () {
  26532. return VertexBuffer._UV3Kind;
  26533. },
  26534. enumerable: true,
  26535. configurable: true
  26536. });
  26537. Object.defineProperty(VertexBuffer, "UV4Kind", {
  26538. get: function () {
  26539. return VertexBuffer._UV4Kind;
  26540. },
  26541. enumerable: true,
  26542. configurable: true
  26543. });
  26544. Object.defineProperty(VertexBuffer, "UV5Kind", {
  26545. get: function () {
  26546. return VertexBuffer._UV5Kind;
  26547. },
  26548. enumerable: true,
  26549. configurable: true
  26550. });
  26551. Object.defineProperty(VertexBuffer, "UV6Kind", {
  26552. get: function () {
  26553. return VertexBuffer._UV6Kind;
  26554. },
  26555. enumerable: true,
  26556. configurable: true
  26557. });
  26558. Object.defineProperty(VertexBuffer, "ColorKind", {
  26559. get: function () {
  26560. return VertexBuffer._ColorKind;
  26561. },
  26562. enumerable: true,
  26563. configurable: true
  26564. });
  26565. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  26566. get: function () {
  26567. return VertexBuffer._MatricesIndicesKind;
  26568. },
  26569. enumerable: true,
  26570. configurable: true
  26571. });
  26572. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  26573. get: function () {
  26574. return VertexBuffer._MatricesWeightsKind;
  26575. },
  26576. enumerable: true,
  26577. configurable: true
  26578. });
  26579. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  26580. get: function () {
  26581. return VertexBuffer._MatricesIndicesExtraKind;
  26582. },
  26583. enumerable: true,
  26584. configurable: true
  26585. });
  26586. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  26587. get: function () {
  26588. return VertexBuffer._MatricesWeightsExtraKind;
  26589. },
  26590. enumerable: true,
  26591. configurable: true
  26592. });
  26593. /**
  26594. * Deduces the stride given a kind.
  26595. * @param kind The kind string to deduce
  26596. * @returns The deduced stride
  26597. */
  26598. VertexBuffer.DeduceStride = function (kind) {
  26599. switch (kind) {
  26600. case VertexBuffer.UVKind:
  26601. case VertexBuffer.UV2Kind:
  26602. case VertexBuffer.UV3Kind:
  26603. case VertexBuffer.UV4Kind:
  26604. case VertexBuffer.UV5Kind:
  26605. case VertexBuffer.UV6Kind:
  26606. return 2;
  26607. case VertexBuffer.NormalKind:
  26608. case VertexBuffer.PositionKind:
  26609. return 3;
  26610. case VertexBuffer.ColorKind:
  26611. case VertexBuffer.MatricesIndicesKind:
  26612. case VertexBuffer.MatricesIndicesExtraKind:
  26613. case VertexBuffer.MatricesWeightsKind:
  26614. case VertexBuffer.MatricesWeightsExtraKind:
  26615. case VertexBuffer.TangentKind:
  26616. return 4;
  26617. default:
  26618. throw new Error("Invalid kind '" + kind + "'");
  26619. }
  26620. };
  26621. // Enums
  26622. VertexBuffer._PositionKind = "position";
  26623. VertexBuffer._NormalKind = "normal";
  26624. VertexBuffer._TangentKind = "tangent";
  26625. VertexBuffer._UVKind = "uv";
  26626. VertexBuffer._UV2Kind = "uv2";
  26627. VertexBuffer._UV3Kind = "uv3";
  26628. VertexBuffer._UV4Kind = "uv4";
  26629. VertexBuffer._UV5Kind = "uv5";
  26630. VertexBuffer._UV6Kind = "uv6";
  26631. VertexBuffer._ColorKind = "color";
  26632. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26633. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26634. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26635. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26636. return VertexBuffer;
  26637. }());
  26638. BABYLON.VertexBuffer = VertexBuffer;
  26639. })(BABYLON || (BABYLON = {}));
  26640. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26641. "use strict";
  26642. var BABYLON;
  26643. (function (BABYLON) {
  26644. /**
  26645. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26646. */
  26647. var DummyInternalTextureTracker = /** @class */ (function () {
  26648. function DummyInternalTextureTracker() {
  26649. /**
  26650. * Gets or set the previous tracker in the list
  26651. */
  26652. this.previous = null;
  26653. /**
  26654. * Gets or set the next tracker in the list
  26655. */
  26656. this.next = null;
  26657. }
  26658. return DummyInternalTextureTracker;
  26659. }());
  26660. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26661. })(BABYLON || (BABYLON = {}));
  26662. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26663. "use strict";
  26664. var BABYLON;
  26665. (function (BABYLON) {
  26666. /**
  26667. * Class used to store data associated with WebGL texture data for the engine
  26668. * This class should not be used directly
  26669. */
  26670. var InternalTexture = /** @class */ (function () {
  26671. /**
  26672. * Creates a new InternalTexture
  26673. * @param engine defines the engine to use
  26674. * @param dataSource defines the type of data that will be used
  26675. */
  26676. function InternalTexture(engine, dataSource) {
  26677. /**
  26678. * Observable called when the texture is loaded
  26679. */
  26680. this.onLoadedObservable = new BABYLON.Observable();
  26681. /**
  26682. * Gets or set the previous tracker in the list
  26683. */
  26684. this.previous = null;
  26685. /**
  26686. * Gets or set the next tracker in the list
  26687. */
  26688. this.next = null;
  26689. // Private
  26690. /** @ignore */
  26691. this._initialSlot = -1;
  26692. /** @ignore */
  26693. this._designatedSlot = -1;
  26694. /** @ignore */
  26695. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26696. /** @ignore */
  26697. this._comparisonFunction = 0;
  26698. /** @ignore */
  26699. this._references = 1;
  26700. this._engine = engine;
  26701. this._dataSource = dataSource;
  26702. this._webGLTexture = engine._createTexture();
  26703. }
  26704. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26705. /**
  26706. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26707. */
  26708. get: function () {
  26709. return this._dataSource;
  26710. },
  26711. enumerable: true,
  26712. configurable: true
  26713. });
  26714. /**
  26715. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26716. */
  26717. InternalTexture.prototype.incrementReferences = function () {
  26718. this._references++;
  26719. };
  26720. /**
  26721. * Change the size of the texture (not the size of the content)
  26722. * @param width defines the new width
  26723. * @param height defines the new height
  26724. * @param depth defines the new depth (1 by default)
  26725. */
  26726. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26727. if (depth === void 0) { depth = 1; }
  26728. this.width = width;
  26729. this.height = height;
  26730. this.depth = depth;
  26731. this.baseWidth = width;
  26732. this.baseHeight = height;
  26733. this.baseDepth = depth;
  26734. this._size = width * height * depth;
  26735. };
  26736. /** @ignore */
  26737. InternalTexture.prototype._rebuild = function () {
  26738. var _this = this;
  26739. var proxy;
  26740. this.isReady = false;
  26741. this._cachedCoordinatesMode = null;
  26742. this._cachedWrapU = null;
  26743. this._cachedWrapV = null;
  26744. this._cachedAnisotropicFilteringLevel = null;
  26745. switch (this._dataSource) {
  26746. case InternalTexture.DATASOURCE_TEMP:
  26747. return;
  26748. case InternalTexture.DATASOURCE_URL:
  26749. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26750. _this.isReady = true;
  26751. }, null, this._buffer, undefined, this.format);
  26752. proxy._swapAndDie(this);
  26753. return;
  26754. case InternalTexture.DATASOURCE_RAW:
  26755. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26756. proxy._swapAndDie(this);
  26757. this.isReady = true;
  26758. return;
  26759. case InternalTexture.DATASOURCE_RAW3D:
  26760. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26761. proxy._swapAndDie(this);
  26762. this.isReady = true;
  26763. return;
  26764. case InternalTexture.DATASOURCE_DYNAMIC:
  26765. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26766. proxy._swapAndDie(this);
  26767. // The engine will make sure to update content so no need to flag it as isReady = true
  26768. return;
  26769. case InternalTexture.DATASOURCE_RENDERTARGET:
  26770. var options = new BABYLON.RenderTargetCreationOptions();
  26771. options.generateDepthBuffer = this._generateDepthBuffer;
  26772. options.generateMipMaps = this.generateMipMaps;
  26773. options.generateStencilBuffer = this._generateStencilBuffer;
  26774. options.samplingMode = this.samplingMode;
  26775. options.type = this.type;
  26776. if (this.isCube) {
  26777. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26778. }
  26779. else {
  26780. var size = {
  26781. width: this.width,
  26782. height: this.height
  26783. };
  26784. proxy = this._engine.createRenderTargetTexture(size, options);
  26785. }
  26786. proxy._swapAndDie(this);
  26787. this.isReady = true;
  26788. return;
  26789. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26790. var depthTextureOptions = {
  26791. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26792. comparisonFunction: this._comparisonFunction,
  26793. generateStencil: this._generateStencilBuffer,
  26794. isCube: this.isCube
  26795. };
  26796. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26797. proxy._swapAndDie(this);
  26798. this.isReady = true;
  26799. return;
  26800. case InternalTexture.DATASOURCE_CUBE:
  26801. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26802. _this.isReady = true;
  26803. }, null, this.format, this._extension);
  26804. proxy._swapAndDie(this);
  26805. return;
  26806. case InternalTexture.DATASOURCE_CUBERAW:
  26807. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26808. proxy._swapAndDie(this);
  26809. this.isReady = true;
  26810. return;
  26811. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26812. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26813. if (proxy) {
  26814. proxy._swapAndDie(_this);
  26815. }
  26816. _this.isReady = true;
  26817. }, null, this.format, this._extension);
  26818. return;
  26819. }
  26820. };
  26821. InternalTexture.prototype._swapAndDie = function (target) {
  26822. target._webGLTexture = this._webGLTexture;
  26823. if (this._framebuffer) {
  26824. target._framebuffer = this._framebuffer;
  26825. }
  26826. if (this._depthStencilBuffer) {
  26827. target._depthStencilBuffer = this._depthStencilBuffer;
  26828. }
  26829. if (this._lodTextureHigh) {
  26830. if (target._lodTextureHigh) {
  26831. target._lodTextureHigh.dispose();
  26832. }
  26833. target._lodTextureHigh = this._lodTextureHigh;
  26834. }
  26835. if (this._lodTextureMid) {
  26836. if (target._lodTextureMid) {
  26837. target._lodTextureMid.dispose();
  26838. }
  26839. target._lodTextureMid = this._lodTextureMid;
  26840. }
  26841. if (this._lodTextureLow) {
  26842. if (target._lodTextureLow) {
  26843. target._lodTextureLow.dispose();
  26844. }
  26845. target._lodTextureLow = this._lodTextureLow;
  26846. }
  26847. var cache = this._engine.getLoadedTexturesCache();
  26848. var index = cache.indexOf(this);
  26849. if (index !== -1) {
  26850. cache.splice(index, 1);
  26851. }
  26852. };
  26853. /**
  26854. * Dispose the current allocated resources
  26855. */
  26856. InternalTexture.prototype.dispose = function () {
  26857. if (!this._webGLTexture) {
  26858. return;
  26859. }
  26860. this._references--;
  26861. if (this._references === 0) {
  26862. this._engine._releaseTexture(this);
  26863. this._webGLTexture = null;
  26864. this.previous = null;
  26865. this.next = null;
  26866. }
  26867. };
  26868. /**
  26869. * The source of the texture data is unknown
  26870. */
  26871. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26872. /**
  26873. * Texture data comes from an URL
  26874. */
  26875. InternalTexture.DATASOURCE_URL = 1;
  26876. /**
  26877. * Texture data is only used for temporary storage
  26878. */
  26879. InternalTexture.DATASOURCE_TEMP = 2;
  26880. /**
  26881. * Texture data comes from raw data (ArrayBuffer)
  26882. */
  26883. InternalTexture.DATASOURCE_RAW = 3;
  26884. /**
  26885. * Texture content is dynamic (video or dynamic texture)
  26886. */
  26887. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26888. /**
  26889. * Texture content is generated by rendering to it
  26890. */
  26891. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26892. /**
  26893. * Texture content is part of a multi render target process
  26894. */
  26895. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26896. /**
  26897. * Texture data comes from a cube data file
  26898. */
  26899. InternalTexture.DATASOURCE_CUBE = 7;
  26900. /**
  26901. * Texture data comes from a raw cube data
  26902. */
  26903. InternalTexture.DATASOURCE_CUBERAW = 8;
  26904. /**
  26905. * Texture data come from a prefiltered cube data file
  26906. */
  26907. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26908. /**
  26909. * Texture content is raw 3D data
  26910. */
  26911. InternalTexture.DATASOURCE_RAW3D = 10;
  26912. /**
  26913. * Texture content is a depth texture
  26914. */
  26915. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26916. return InternalTexture;
  26917. }());
  26918. BABYLON.InternalTexture = InternalTexture;
  26919. })(BABYLON || (BABYLON = {}));
  26920. //# sourceMappingURL=babylon.internalTexture.js.map
  26921. "use strict";
  26922. var BABYLON;
  26923. (function (BABYLON) {
  26924. var BaseTexture = /** @class */ (function () {
  26925. function BaseTexture(scene) {
  26926. this._hasAlpha = false;
  26927. this.getAlphaFromRGB = false;
  26928. this.level = 1;
  26929. this.coordinatesIndex = 0;
  26930. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26931. /**
  26932. * | Value | Type | Description |
  26933. * | ----- | ------------------ | ----------- |
  26934. * | 0 | CLAMP_ADDRESSMODE | |
  26935. * | 1 | WRAP_ADDRESSMODE | |
  26936. * | 2 | MIRROR_ADDRESSMODE | |
  26937. */
  26938. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26939. /**
  26940. * | Value | Type | Description |
  26941. * | ----- | ------------------ | ----------- |
  26942. * | 0 | CLAMP_ADDRESSMODE | |
  26943. * | 1 | WRAP_ADDRESSMODE | |
  26944. * | 2 | MIRROR_ADDRESSMODE | |
  26945. */
  26946. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26947. /**
  26948. * | Value | Type | Description |
  26949. * | ----- | ------------------ | ----------- |
  26950. * | 0 | CLAMP_ADDRESSMODE | |
  26951. * | 1 | WRAP_ADDRESSMODE | |
  26952. * | 2 | MIRROR_ADDRESSMODE | |
  26953. */
  26954. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26955. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26956. this.isCube = false;
  26957. this.is3D = false;
  26958. this.gammaSpace = true;
  26959. this.invertZ = false;
  26960. this.lodLevelInAlpha = false;
  26961. this.lodGenerationOffset = 0.0;
  26962. this.lodGenerationScale = 0.8;
  26963. this.isRenderTarget = false;
  26964. this.animations = new Array();
  26965. /**
  26966. * An event triggered when the texture is disposed.
  26967. * @type {BABYLON.Observable}
  26968. */
  26969. this.onDisposeObservable = new BABYLON.Observable();
  26970. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26971. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26972. if (this._scene) {
  26973. this._scene.textures.push(this);
  26974. }
  26975. this._uid = null;
  26976. }
  26977. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26978. get: function () {
  26979. return this._hasAlpha;
  26980. },
  26981. set: function (value) {
  26982. if (this._hasAlpha === value) {
  26983. return;
  26984. }
  26985. this._hasAlpha = value;
  26986. if (this._scene) {
  26987. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26988. }
  26989. },
  26990. enumerable: true,
  26991. configurable: true
  26992. });
  26993. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26994. get: function () {
  26995. return this._coordinatesMode;
  26996. },
  26997. /**
  26998. * How a texture is mapped.
  26999. *
  27000. * | Value | Type | Description |
  27001. * | ----- | ----------------------------------- | ----------- |
  27002. * | 0 | EXPLICIT_MODE | |
  27003. * | 1 | SPHERICAL_MODE | |
  27004. * | 2 | PLANAR_MODE | |
  27005. * | 3 | CUBIC_MODE | |
  27006. * | 4 | PROJECTION_MODE | |
  27007. * | 5 | SKYBOX_MODE | |
  27008. * | 6 | INVCUBIC_MODE | |
  27009. * | 7 | EQUIRECTANGULAR_MODE | |
  27010. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  27011. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  27012. */
  27013. set: function (value) {
  27014. if (this._coordinatesMode === value) {
  27015. return;
  27016. }
  27017. this._coordinatesMode = value;
  27018. if (this._scene) {
  27019. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27020. }
  27021. },
  27022. enumerable: true,
  27023. configurable: true
  27024. });
  27025. Object.defineProperty(BaseTexture.prototype, "uid", {
  27026. get: function () {
  27027. if (!this._uid) {
  27028. this._uid = BABYLON.Tools.RandomId();
  27029. }
  27030. return this._uid;
  27031. },
  27032. enumerable: true,
  27033. configurable: true
  27034. });
  27035. BaseTexture.prototype.toString = function () {
  27036. return this.name;
  27037. };
  27038. BaseTexture.prototype.getClassName = function () {
  27039. return "BaseTexture";
  27040. };
  27041. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  27042. set: function (callback) {
  27043. if (this._onDisposeObserver) {
  27044. this.onDisposeObservable.remove(this._onDisposeObserver);
  27045. }
  27046. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27047. },
  27048. enumerable: true,
  27049. configurable: true
  27050. });
  27051. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  27052. get: function () {
  27053. return true;
  27054. },
  27055. enumerable: true,
  27056. configurable: true
  27057. });
  27058. BaseTexture.prototype.getScene = function () {
  27059. return this._scene;
  27060. };
  27061. BaseTexture.prototype.getTextureMatrix = function () {
  27062. return BABYLON.Matrix.IdentityReadOnly;
  27063. };
  27064. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  27065. return BABYLON.Matrix.IdentityReadOnly;
  27066. };
  27067. BaseTexture.prototype.getInternalTexture = function () {
  27068. return this._texture;
  27069. };
  27070. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  27071. return !this.isBlocking || this.isReady();
  27072. };
  27073. BaseTexture.prototype.isReady = function () {
  27074. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27075. this.delayLoad();
  27076. return false;
  27077. }
  27078. if (this._texture) {
  27079. return this._texture.isReady;
  27080. }
  27081. return false;
  27082. };
  27083. BaseTexture.prototype.getSize = function () {
  27084. if (this._texture && this._texture.width) {
  27085. return new BABYLON.Size(this._texture.width, this._texture.height);
  27086. }
  27087. if (this._texture && this._texture._size) {
  27088. return new BABYLON.Size(this._texture._size, this._texture._size);
  27089. }
  27090. return BABYLON.Size.Zero();
  27091. };
  27092. BaseTexture.prototype.getBaseSize = function () {
  27093. if (!this.isReady() || !this._texture)
  27094. return BABYLON.Size.Zero();
  27095. if (this._texture._size) {
  27096. return new BABYLON.Size(this._texture._size, this._texture._size);
  27097. }
  27098. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  27099. };
  27100. BaseTexture.prototype.scale = function (ratio) {
  27101. };
  27102. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  27103. get: function () {
  27104. return false;
  27105. },
  27106. enumerable: true,
  27107. configurable: true
  27108. });
  27109. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  27110. if (!this._scene) {
  27111. return null;
  27112. }
  27113. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  27114. for (var index = 0; index < texturesCache.length; index++) {
  27115. var texturesCacheEntry = texturesCache[index];
  27116. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  27117. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  27118. texturesCacheEntry.incrementReferences();
  27119. return texturesCacheEntry;
  27120. }
  27121. }
  27122. }
  27123. return null;
  27124. };
  27125. BaseTexture.prototype._rebuild = function () {
  27126. };
  27127. BaseTexture.prototype.delayLoad = function () {
  27128. };
  27129. BaseTexture.prototype.clone = function () {
  27130. return null;
  27131. };
  27132. Object.defineProperty(BaseTexture.prototype, "textureType", {
  27133. get: function () {
  27134. if (!this._texture) {
  27135. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27136. }
  27137. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27138. },
  27139. enumerable: true,
  27140. configurable: true
  27141. });
  27142. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  27143. get: function () {
  27144. if (!this._texture) {
  27145. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27146. }
  27147. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27148. },
  27149. enumerable: true,
  27150. configurable: true
  27151. });
  27152. BaseTexture.prototype.readPixels = function (faceIndex) {
  27153. if (faceIndex === void 0) { faceIndex = 0; }
  27154. if (!this._texture) {
  27155. return null;
  27156. }
  27157. var size = this.getSize();
  27158. var scene = this.getScene();
  27159. if (!scene) {
  27160. return null;
  27161. }
  27162. var engine = scene.getEngine();
  27163. if (this._texture.isCube) {
  27164. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  27165. }
  27166. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  27167. };
  27168. BaseTexture.prototype.releaseInternalTexture = function () {
  27169. if (this._texture) {
  27170. this._texture.dispose();
  27171. this._texture = null;
  27172. }
  27173. };
  27174. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  27175. get: function () {
  27176. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  27177. return null;
  27178. }
  27179. if (!this._texture._sphericalPolynomial) {
  27180. this._texture._sphericalPolynomial =
  27181. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  27182. }
  27183. return this._texture._sphericalPolynomial;
  27184. },
  27185. set: function (value) {
  27186. if (this._texture) {
  27187. this._texture._sphericalPolynomial = value;
  27188. }
  27189. },
  27190. enumerable: true,
  27191. configurable: true
  27192. });
  27193. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  27194. get: function () {
  27195. if (this._texture) {
  27196. return this._texture._lodTextureHigh;
  27197. }
  27198. return null;
  27199. },
  27200. enumerable: true,
  27201. configurable: true
  27202. });
  27203. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  27204. get: function () {
  27205. if (this._texture) {
  27206. return this._texture._lodTextureMid;
  27207. }
  27208. return null;
  27209. },
  27210. enumerable: true,
  27211. configurable: true
  27212. });
  27213. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  27214. get: function () {
  27215. if (this._texture) {
  27216. return this._texture._lodTextureLow;
  27217. }
  27218. return null;
  27219. },
  27220. enumerable: true,
  27221. configurable: true
  27222. });
  27223. BaseTexture.prototype.dispose = function () {
  27224. if (!this._scene) {
  27225. return;
  27226. }
  27227. // Animations
  27228. this._scene.stopAnimation(this);
  27229. // Remove from scene
  27230. this._scene._removePendingData(this);
  27231. var index = this._scene.textures.indexOf(this);
  27232. if (index >= 0) {
  27233. this._scene.textures.splice(index, 1);
  27234. }
  27235. if (this._texture === undefined) {
  27236. return;
  27237. }
  27238. // Release
  27239. this.releaseInternalTexture();
  27240. // Callback
  27241. this.onDisposeObservable.notifyObservers(this);
  27242. this.onDisposeObservable.clear();
  27243. };
  27244. BaseTexture.prototype.serialize = function () {
  27245. if (!this.name) {
  27246. return null;
  27247. }
  27248. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  27249. // Animations
  27250. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27251. return serializationObject;
  27252. };
  27253. BaseTexture.WhenAllReady = function (textures, callback) {
  27254. var numRemaining = textures.length;
  27255. if (numRemaining === 0) {
  27256. callback();
  27257. return;
  27258. }
  27259. var _loop_1 = function () {
  27260. texture = textures[i];
  27261. if (texture.isReady()) {
  27262. if (--numRemaining === 0) {
  27263. callback();
  27264. }
  27265. }
  27266. else {
  27267. onLoadObservable = texture.onLoadObservable;
  27268. var onLoadCallback_1 = function () {
  27269. onLoadObservable.removeCallback(onLoadCallback_1);
  27270. if (--numRemaining === 0) {
  27271. callback();
  27272. }
  27273. };
  27274. onLoadObservable.add(onLoadCallback_1);
  27275. }
  27276. };
  27277. var texture, onLoadObservable;
  27278. for (var i = 0; i < textures.length; i++) {
  27279. _loop_1();
  27280. }
  27281. };
  27282. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  27283. __decorate([
  27284. BABYLON.serialize()
  27285. ], BaseTexture.prototype, "name", void 0);
  27286. __decorate([
  27287. BABYLON.serialize("hasAlpha")
  27288. ], BaseTexture.prototype, "_hasAlpha", void 0);
  27289. __decorate([
  27290. BABYLON.serialize()
  27291. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  27292. __decorate([
  27293. BABYLON.serialize()
  27294. ], BaseTexture.prototype, "level", void 0);
  27295. __decorate([
  27296. BABYLON.serialize()
  27297. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  27298. __decorate([
  27299. BABYLON.serialize("coordinatesMode")
  27300. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  27301. __decorate([
  27302. BABYLON.serialize()
  27303. ], BaseTexture.prototype, "wrapU", void 0);
  27304. __decorate([
  27305. BABYLON.serialize()
  27306. ], BaseTexture.prototype, "wrapV", void 0);
  27307. __decorate([
  27308. BABYLON.serialize()
  27309. ], BaseTexture.prototype, "wrapR", void 0);
  27310. __decorate([
  27311. BABYLON.serialize()
  27312. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  27313. __decorate([
  27314. BABYLON.serialize()
  27315. ], BaseTexture.prototype, "isCube", void 0);
  27316. __decorate([
  27317. BABYLON.serialize()
  27318. ], BaseTexture.prototype, "is3D", void 0);
  27319. __decorate([
  27320. BABYLON.serialize()
  27321. ], BaseTexture.prototype, "gammaSpace", void 0);
  27322. __decorate([
  27323. BABYLON.serialize()
  27324. ], BaseTexture.prototype, "invertZ", void 0);
  27325. __decorate([
  27326. BABYLON.serialize()
  27327. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  27328. __decorate([
  27329. BABYLON.serialize()
  27330. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  27331. __decorate([
  27332. BABYLON.serialize()
  27333. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  27334. __decorate([
  27335. BABYLON.serialize()
  27336. ], BaseTexture.prototype, "isRenderTarget", void 0);
  27337. return BaseTexture;
  27338. }());
  27339. BABYLON.BaseTexture = BaseTexture;
  27340. })(BABYLON || (BABYLON = {}));
  27341. //# sourceMappingURL=babylon.baseTexture.js.map
  27342. "use strict";
  27343. var BABYLON;
  27344. (function (BABYLON) {
  27345. var Texture = /** @class */ (function (_super) {
  27346. __extends(Texture, _super);
  27347. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  27348. if (noMipmap === void 0) { noMipmap = false; }
  27349. if (invertY === void 0) { invertY = true; }
  27350. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27351. if (onLoad === void 0) { onLoad = null; }
  27352. if (onError === void 0) { onError = null; }
  27353. if (buffer === void 0) { buffer = null; }
  27354. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27355. var _this = _super.call(this, scene) || this;
  27356. _this.uOffset = 0;
  27357. _this.vOffset = 0;
  27358. _this.uScale = 1.0;
  27359. _this.vScale = 1.0;
  27360. _this.uAng = 0;
  27361. _this.vAng = 0;
  27362. _this.wAng = 0;
  27363. _this._isBlocking = true;
  27364. _this.name = url || "";
  27365. _this.url = url;
  27366. _this._noMipmap = noMipmap;
  27367. _this._invertY = invertY;
  27368. _this._samplingMode = samplingMode;
  27369. _this._buffer = buffer;
  27370. _this._deleteBuffer = deleteBuffer;
  27371. if (format) {
  27372. _this._format = format;
  27373. }
  27374. scene = _this.getScene();
  27375. if (!scene) {
  27376. return _this;
  27377. }
  27378. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  27379. var load = function () {
  27380. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  27381. _this.onLoadObservable.notifyObservers(_this);
  27382. }
  27383. if (onLoad) {
  27384. onLoad();
  27385. }
  27386. if (!_this.isBlocking && scene) {
  27387. scene.resetCachedMaterial();
  27388. }
  27389. };
  27390. if (!_this.url) {
  27391. _this._delayedOnLoad = load;
  27392. _this._delayedOnError = onError;
  27393. return _this;
  27394. }
  27395. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  27396. if (!_this._texture) {
  27397. if (!scene.useDelayedTextureLoading) {
  27398. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  27399. if (deleteBuffer) {
  27400. delete _this._buffer;
  27401. }
  27402. }
  27403. else {
  27404. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27405. _this._delayedOnLoad = load;
  27406. _this._delayedOnError = onError;
  27407. }
  27408. }
  27409. else {
  27410. if (_this._texture.isReady) {
  27411. BABYLON.Tools.SetImmediate(function () { return load(); });
  27412. }
  27413. else {
  27414. _this._texture.onLoadedObservable.add(load);
  27415. }
  27416. }
  27417. return _this;
  27418. }
  27419. Object.defineProperty(Texture.prototype, "noMipmap", {
  27420. get: function () {
  27421. return this._noMipmap;
  27422. },
  27423. enumerable: true,
  27424. configurable: true
  27425. });
  27426. Object.defineProperty(Texture.prototype, "isBlocking", {
  27427. get: function () {
  27428. return this._isBlocking;
  27429. },
  27430. set: function (value) {
  27431. this._isBlocking = value;
  27432. },
  27433. enumerable: true,
  27434. configurable: true
  27435. });
  27436. Object.defineProperty(Texture.prototype, "samplingMode", {
  27437. get: function () {
  27438. return this._samplingMode;
  27439. },
  27440. enumerable: true,
  27441. configurable: true
  27442. });
  27443. Texture.prototype.updateURL = function (url) {
  27444. this.url = url;
  27445. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27446. this.delayLoad();
  27447. };
  27448. Texture.prototype.delayLoad = function () {
  27449. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27450. return;
  27451. }
  27452. var scene = this.getScene();
  27453. if (!scene) {
  27454. return;
  27455. }
  27456. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27457. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  27458. if (!this._texture) {
  27459. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  27460. if (this._deleteBuffer) {
  27461. delete this._buffer;
  27462. }
  27463. }
  27464. else {
  27465. if (this._delayedOnLoad) {
  27466. if (this._texture.isReady) {
  27467. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  27468. }
  27469. else {
  27470. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  27471. }
  27472. }
  27473. }
  27474. this._delayedOnLoad = null;
  27475. this._delayedOnError = null;
  27476. };
  27477. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27478. if (!this._texture) {
  27479. return;
  27480. }
  27481. var scene = this.getScene();
  27482. if (!scene) {
  27483. return;
  27484. }
  27485. this._samplingMode = samplingMode;
  27486. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27487. };
  27488. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27489. x *= this.uScale;
  27490. y *= this.vScale;
  27491. x -= 0.5 * this.uScale;
  27492. y -= 0.5 * this.vScale;
  27493. z -= 0.5;
  27494. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27495. t.x += 0.5 * this.uScale + this.uOffset;
  27496. t.y += 0.5 * this.vScale + this.vOffset;
  27497. t.z += 0.5;
  27498. };
  27499. Texture.prototype.getTextureMatrix = function () {
  27500. var _this = this;
  27501. if (this.uOffset === this._cachedUOffset &&
  27502. this.vOffset === this._cachedVOffset &&
  27503. this.uScale === this._cachedUScale &&
  27504. this.vScale === this._cachedVScale &&
  27505. this.uAng === this._cachedUAng &&
  27506. this.vAng === this._cachedVAng &&
  27507. this.wAng === this._cachedWAng) {
  27508. return this._cachedTextureMatrix;
  27509. }
  27510. this._cachedUOffset = this.uOffset;
  27511. this._cachedVOffset = this.vOffset;
  27512. this._cachedUScale = this.uScale;
  27513. this._cachedVScale = this.vScale;
  27514. this._cachedUAng = this.uAng;
  27515. this._cachedVAng = this.vAng;
  27516. this._cachedWAng = this.wAng;
  27517. if (!this._cachedTextureMatrix) {
  27518. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27519. this._rowGenerationMatrix = new BABYLON.Matrix();
  27520. this._t0 = BABYLON.Vector3.Zero();
  27521. this._t1 = BABYLON.Vector3.Zero();
  27522. this._t2 = BABYLON.Vector3.Zero();
  27523. }
  27524. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27525. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27526. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27527. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27528. this._t1.subtractInPlace(this._t0);
  27529. this._t2.subtractInPlace(this._t0);
  27530. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27531. this._cachedTextureMatrix.m[0] = this._t1.x;
  27532. this._cachedTextureMatrix.m[1] = this._t1.y;
  27533. this._cachedTextureMatrix.m[2] = this._t1.z;
  27534. this._cachedTextureMatrix.m[4] = this._t2.x;
  27535. this._cachedTextureMatrix.m[5] = this._t2.y;
  27536. this._cachedTextureMatrix.m[6] = this._t2.z;
  27537. this._cachedTextureMatrix.m[8] = this._t0.x;
  27538. this._cachedTextureMatrix.m[9] = this._t0.y;
  27539. this._cachedTextureMatrix.m[10] = this._t0.z;
  27540. var scene = this.getScene();
  27541. if (!scene) {
  27542. return this._cachedTextureMatrix;
  27543. }
  27544. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27545. return mat.hasTexture(_this);
  27546. });
  27547. return this._cachedTextureMatrix;
  27548. };
  27549. Texture.prototype.getReflectionTextureMatrix = function () {
  27550. var _this = this;
  27551. var scene = this.getScene();
  27552. if (!scene) {
  27553. return this._cachedTextureMatrix;
  27554. }
  27555. if (this.uOffset === this._cachedUOffset &&
  27556. this.vOffset === this._cachedVOffset &&
  27557. this.uScale === this._cachedUScale &&
  27558. this.vScale === this._cachedVScale &&
  27559. this.coordinatesMode === this._cachedCoordinatesMode) {
  27560. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  27561. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  27562. return this._cachedTextureMatrix;
  27563. }
  27564. }
  27565. else {
  27566. return this._cachedTextureMatrix;
  27567. }
  27568. }
  27569. if (!this._cachedTextureMatrix) {
  27570. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27571. }
  27572. if (!this._projectionModeMatrix) {
  27573. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27574. }
  27575. this._cachedUOffset = this.uOffset;
  27576. this._cachedVOffset = this.vOffset;
  27577. this._cachedUScale = this.uScale;
  27578. this._cachedVScale = this.vScale;
  27579. this._cachedCoordinatesMode = this.coordinatesMode;
  27580. switch (this.coordinatesMode) {
  27581. case Texture.PLANAR_MODE:
  27582. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27583. this._cachedTextureMatrix[0] = this.uScale;
  27584. this._cachedTextureMatrix[5] = this.vScale;
  27585. this._cachedTextureMatrix[12] = this.uOffset;
  27586. this._cachedTextureMatrix[13] = this.vOffset;
  27587. break;
  27588. case Texture.PROJECTION_MODE:
  27589. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27590. this._projectionModeMatrix.m[0] = 0.5;
  27591. this._projectionModeMatrix.m[5] = -0.5;
  27592. this._projectionModeMatrix.m[10] = 0.0;
  27593. this._projectionModeMatrix.m[12] = 0.5;
  27594. this._projectionModeMatrix.m[13] = 0.5;
  27595. this._projectionModeMatrix.m[14] = 1.0;
  27596. this._projectionModeMatrix.m[15] = 1.0;
  27597. var projectionMatrix = scene.getProjectionMatrix();
  27598. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  27599. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27600. break;
  27601. default:
  27602. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27603. break;
  27604. }
  27605. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27606. return (mat.getActiveTextures().indexOf(_this) !== -1);
  27607. });
  27608. return this._cachedTextureMatrix;
  27609. };
  27610. Texture.prototype.clone = function () {
  27611. var _this = this;
  27612. return BABYLON.SerializationHelper.Clone(function () {
  27613. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27614. }, this);
  27615. };
  27616. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27617. get: function () {
  27618. if (!this._onLoadObservable) {
  27619. this._onLoadObservable = new BABYLON.Observable();
  27620. }
  27621. return this._onLoadObservable;
  27622. },
  27623. enumerable: true,
  27624. configurable: true
  27625. });
  27626. Texture.prototype.serialize = function () {
  27627. var serializationObject = _super.prototype.serialize.call(this);
  27628. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27629. serializationObject.base64String = this._buffer;
  27630. serializationObject.name = serializationObject.name.replace("data:", "");
  27631. }
  27632. return serializationObject;
  27633. };
  27634. Texture.prototype.getClassName = function () {
  27635. return "Texture";
  27636. };
  27637. Texture.prototype.dispose = function () {
  27638. _super.prototype.dispose.call(this);
  27639. if (this.onLoadObservable) {
  27640. this.onLoadObservable.clear();
  27641. this._onLoadObservable = null;
  27642. }
  27643. this._delayedOnLoad = null;
  27644. this._delayedOnError = null;
  27645. };
  27646. // Statics
  27647. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27648. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27649. if (onLoad === void 0) { onLoad = null; }
  27650. if (onError === void 0) { onError = null; }
  27651. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27652. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27653. };
  27654. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27655. if (parsedTexture.customType) {
  27656. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27657. // Update Sampling Mode
  27658. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27659. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27660. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27661. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27662. }
  27663. }
  27664. return parsedCustomTexture;
  27665. }
  27666. if (parsedTexture.isCube) {
  27667. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27668. }
  27669. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27670. return null;
  27671. }
  27672. var texture = BABYLON.SerializationHelper.Parse(function () {
  27673. var generateMipMaps = true;
  27674. if (parsedTexture.noMipmap) {
  27675. generateMipMaps = false;
  27676. }
  27677. if (parsedTexture.mirrorPlane) {
  27678. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27679. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27680. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27681. return mirrorTexture;
  27682. }
  27683. else if (parsedTexture.isRenderTarget) {
  27684. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27685. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27686. return renderTargetTexture;
  27687. }
  27688. else {
  27689. var texture;
  27690. if (parsedTexture.base64String) {
  27691. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27692. }
  27693. else {
  27694. var url = rootUrl + parsedTexture.name;
  27695. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27696. url = parsedTexture.url;
  27697. }
  27698. texture = new Texture(url, scene, !generateMipMaps);
  27699. }
  27700. return texture;
  27701. }
  27702. }, parsedTexture, scene);
  27703. // Update Sampling Mode
  27704. if (parsedTexture.samplingMode) {
  27705. var sampling = parsedTexture.samplingMode;
  27706. if (texture._samplingMode !== sampling) {
  27707. texture.updateSamplingMode(sampling);
  27708. }
  27709. }
  27710. // Animations
  27711. if (parsedTexture.animations) {
  27712. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27713. var parsedAnimation = parsedTexture.animations[animationIndex];
  27714. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27715. }
  27716. }
  27717. return texture;
  27718. };
  27719. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27720. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27721. if (noMipmap === void 0) { noMipmap = false; }
  27722. if (invertY === void 0) { invertY = true; }
  27723. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27724. if (onLoad === void 0) { onLoad = null; }
  27725. if (onError === void 0) { onError = null; }
  27726. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27727. if (name.substr(0, 5) !== "data:") {
  27728. name = "data:" + name;
  27729. }
  27730. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27731. };
  27732. // Constants
  27733. Texture.NEAREST_SAMPLINGMODE = 1;
  27734. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27735. Texture.BILINEAR_SAMPLINGMODE = 2;
  27736. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27737. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27738. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27739. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27740. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27741. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27742. Texture.NEAREST_LINEAR = 7;
  27743. Texture.NEAREST_NEAREST = 8;
  27744. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27745. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27746. Texture.LINEAR_LINEAR = 11;
  27747. Texture.LINEAR_NEAREST = 12;
  27748. Texture.EXPLICIT_MODE = 0;
  27749. Texture.SPHERICAL_MODE = 1;
  27750. Texture.PLANAR_MODE = 2;
  27751. Texture.CUBIC_MODE = 3;
  27752. Texture.PROJECTION_MODE = 4;
  27753. Texture.SKYBOX_MODE = 5;
  27754. Texture.INVCUBIC_MODE = 6;
  27755. Texture.EQUIRECTANGULAR_MODE = 7;
  27756. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27757. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27758. Texture.CLAMP_ADDRESSMODE = 0;
  27759. Texture.WRAP_ADDRESSMODE = 1;
  27760. Texture.MIRROR_ADDRESSMODE = 2;
  27761. /**
  27762. * 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
  27763. */
  27764. Texture.UseSerializedUrlIfAny = false;
  27765. __decorate([
  27766. BABYLON.serialize()
  27767. ], Texture.prototype, "url", void 0);
  27768. __decorate([
  27769. BABYLON.serialize()
  27770. ], Texture.prototype, "uOffset", void 0);
  27771. __decorate([
  27772. BABYLON.serialize()
  27773. ], Texture.prototype, "vOffset", void 0);
  27774. __decorate([
  27775. BABYLON.serialize()
  27776. ], Texture.prototype, "uScale", void 0);
  27777. __decorate([
  27778. BABYLON.serialize()
  27779. ], Texture.prototype, "vScale", void 0);
  27780. __decorate([
  27781. BABYLON.serialize()
  27782. ], Texture.prototype, "uAng", void 0);
  27783. __decorate([
  27784. BABYLON.serialize()
  27785. ], Texture.prototype, "vAng", void 0);
  27786. __decorate([
  27787. BABYLON.serialize()
  27788. ], Texture.prototype, "wAng", void 0);
  27789. __decorate([
  27790. BABYLON.serialize()
  27791. ], Texture.prototype, "isBlocking", null);
  27792. return Texture;
  27793. }(BABYLON.BaseTexture));
  27794. BABYLON.Texture = Texture;
  27795. })(BABYLON || (BABYLON = {}));
  27796. //# sourceMappingURL=babylon.texture.js.map
  27797. "use strict";
  27798. var BABYLON;
  27799. (function (BABYLON) {
  27800. var _InstancesBatch = /** @class */ (function () {
  27801. function _InstancesBatch() {
  27802. this.mustReturn = false;
  27803. this.visibleInstances = new Array();
  27804. this.renderSelf = new Array();
  27805. }
  27806. return _InstancesBatch;
  27807. }());
  27808. BABYLON._InstancesBatch = _InstancesBatch;
  27809. var Mesh = /** @class */ (function (_super) {
  27810. __extends(Mesh, _super);
  27811. /**
  27812. * @constructor
  27813. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27814. * @param {Scene} scene The scene to add this mesh to.
  27815. * @param {Node} parent The parent of this mesh, if it has one
  27816. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27817. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27818. * When false, achieved by calling a clone(), also passing False.
  27819. * This will make creation of children, recursive.
  27820. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27821. */
  27822. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27823. if (scene === void 0) { scene = null; }
  27824. if (parent === void 0) { parent = null; }
  27825. if (source === void 0) { source = null; }
  27826. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27827. var _this = _super.call(this, name, scene) || this;
  27828. // Events
  27829. /**
  27830. * An event triggered before rendering the mesh
  27831. * @type {BABYLON.Observable}
  27832. */
  27833. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27834. /**
  27835. * An event triggered after rendering the mesh
  27836. * @type {BABYLON.Observable}
  27837. */
  27838. _this.onAfterRenderObservable = new BABYLON.Observable();
  27839. /**
  27840. * An event triggered before drawing the mesh
  27841. * @type {BABYLON.Observable}
  27842. */
  27843. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27844. // Members
  27845. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27846. _this.instances = new Array();
  27847. _this._LODLevels = new Array();
  27848. _this._visibleInstances = {};
  27849. _this._renderIdForInstances = new Array();
  27850. _this._batchCache = new _InstancesBatch();
  27851. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27852. // Use by builder only to know what orientation were the mesh build in.
  27853. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27854. _this.overrideMaterialSideOrientation = null;
  27855. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27856. // Will be used to save a source mesh reference, If any
  27857. _this._source = null;
  27858. scene = _this.getScene();
  27859. if (source) {
  27860. // Source mesh
  27861. _this._source = source;
  27862. // Geometry
  27863. if (source._geometry) {
  27864. source._geometry.applyToMesh(_this);
  27865. }
  27866. // Deep copy
  27867. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  27868. // Metadata
  27869. if (source.metadata && source.metadata.clone) {
  27870. _this.metadata = source.metadata.clone();
  27871. }
  27872. else {
  27873. _this.metadata = source.metadata;
  27874. }
  27875. // Tags
  27876. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27877. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27878. }
  27879. // Parent
  27880. _this.parent = source.parent;
  27881. // Pivot
  27882. _this.setPivotMatrix(source.getPivotMatrix());
  27883. _this.id = name + "." + source.id;
  27884. // Material
  27885. _this.material = source.material;
  27886. var index;
  27887. if (!doNotCloneChildren) {
  27888. // Children
  27889. var directDescendants = source.getDescendants(true);
  27890. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27891. var child = directDescendants[index_1];
  27892. if (child.clone) {
  27893. child.clone(name + "." + child.name, _this);
  27894. }
  27895. }
  27896. }
  27897. // Physics clone
  27898. var physicsEngine = _this.getScene().getPhysicsEngine();
  27899. if (clonePhysicsImpostor && physicsEngine) {
  27900. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27901. if (impostor) {
  27902. _this.physicsImpostor = impostor.clone(_this);
  27903. }
  27904. }
  27905. // Particles
  27906. for (index = 0; index < scene.particleSystems.length; index++) {
  27907. var system = scene.particleSystems[index];
  27908. if (system.emitter === source) {
  27909. system.clone(system.name, _this);
  27910. }
  27911. }
  27912. _this.computeWorldMatrix(true);
  27913. }
  27914. // Parent
  27915. if (parent !== null) {
  27916. _this.parent = parent;
  27917. }
  27918. return _this;
  27919. }
  27920. Object.defineProperty(Mesh, "FRONTSIDE", {
  27921. /**
  27922. * Mesh side orientation : usually the external or front surface
  27923. */
  27924. get: function () {
  27925. return Mesh._FRONTSIDE;
  27926. },
  27927. enumerable: true,
  27928. configurable: true
  27929. });
  27930. Object.defineProperty(Mesh, "BACKSIDE", {
  27931. /**
  27932. * Mesh side orientation : usually the internal or back surface
  27933. */
  27934. get: function () {
  27935. return Mesh._BACKSIDE;
  27936. },
  27937. enumerable: true,
  27938. configurable: true
  27939. });
  27940. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27941. /**
  27942. * Mesh side orientation : both internal and external or front and back surfaces
  27943. */
  27944. get: function () {
  27945. return Mesh._DOUBLESIDE;
  27946. },
  27947. enumerable: true,
  27948. configurable: true
  27949. });
  27950. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27951. /**
  27952. * Mesh side orientation : by default, `FRONTSIDE`
  27953. */
  27954. get: function () {
  27955. return Mesh._DEFAULTSIDE;
  27956. },
  27957. enumerable: true,
  27958. configurable: true
  27959. });
  27960. Object.defineProperty(Mesh, "NO_CAP", {
  27961. /**
  27962. * Mesh cap setting : no cap
  27963. */
  27964. get: function () {
  27965. return Mesh._NO_CAP;
  27966. },
  27967. enumerable: true,
  27968. configurable: true
  27969. });
  27970. Object.defineProperty(Mesh, "CAP_START", {
  27971. /**
  27972. * Mesh cap setting : one cap at the beginning of the mesh
  27973. */
  27974. get: function () {
  27975. return Mesh._CAP_START;
  27976. },
  27977. enumerable: true,
  27978. configurable: true
  27979. });
  27980. Object.defineProperty(Mesh, "CAP_END", {
  27981. /**
  27982. * Mesh cap setting : one cap at the end of the mesh
  27983. */
  27984. get: function () {
  27985. return Mesh._CAP_END;
  27986. },
  27987. enumerable: true,
  27988. configurable: true
  27989. });
  27990. Object.defineProperty(Mesh, "CAP_ALL", {
  27991. /**
  27992. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27993. */
  27994. get: function () {
  27995. return Mesh._CAP_ALL;
  27996. },
  27997. enumerable: true,
  27998. configurable: true
  27999. });
  28000. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  28001. set: function (callback) {
  28002. if (this._onBeforeDrawObserver) {
  28003. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  28004. }
  28005. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  28006. },
  28007. enumerable: true,
  28008. configurable: true
  28009. });
  28010. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  28011. get: function () {
  28012. return this._morphTargetManager;
  28013. },
  28014. set: function (value) {
  28015. if (this._morphTargetManager === value) {
  28016. return;
  28017. }
  28018. this._morphTargetManager = value;
  28019. this._syncGeometryWithMorphTargetManager();
  28020. },
  28021. enumerable: true,
  28022. configurable: true
  28023. });
  28024. Object.defineProperty(Mesh.prototype, "source", {
  28025. get: function () {
  28026. return this._source;
  28027. },
  28028. enumerable: true,
  28029. configurable: true
  28030. });
  28031. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  28032. get: function () {
  28033. return this._unIndexed;
  28034. },
  28035. set: function (value) {
  28036. if (this._unIndexed !== value) {
  28037. this._unIndexed = value;
  28038. this._markSubMeshesAsAttributesDirty();
  28039. }
  28040. },
  28041. enumerable: true,
  28042. configurable: true
  28043. });
  28044. // Methods
  28045. /**
  28046. * Returns the string "Mesh".
  28047. */
  28048. Mesh.prototype.getClassName = function () {
  28049. return "Mesh";
  28050. };
  28051. /**
  28052. * Returns a string.
  28053. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28054. */
  28055. Mesh.prototype.toString = function (fullDetails) {
  28056. var ret = _super.prototype.toString.call(this, fullDetails);
  28057. ret += ", n vertices: " + this.getTotalVertices();
  28058. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  28059. if (this.animations) {
  28060. for (var i = 0; i < this.animations.length; i++) {
  28061. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  28062. }
  28063. }
  28064. if (fullDetails) {
  28065. if (this._geometry) {
  28066. var ib = this.getIndices();
  28067. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28068. if (vb && ib) {
  28069. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  28070. }
  28071. }
  28072. else {
  28073. ret += ", flat shading: UNKNOWN";
  28074. }
  28075. }
  28076. return ret;
  28077. };
  28078. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  28079. /**
  28080. * True if the mesh has some Levels Of Details (LOD).
  28081. * Returns a boolean.
  28082. */
  28083. get: function () {
  28084. return this._LODLevels.length > 0;
  28085. },
  28086. enumerable: true,
  28087. configurable: true
  28088. });
  28089. /**
  28090. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  28091. * @returns an array of {BABYLON.MeshLODLevel}
  28092. */
  28093. Mesh.prototype.getLODLevels = function () {
  28094. return this._LODLevels;
  28095. };
  28096. Mesh.prototype._sortLODLevels = function () {
  28097. this._LODLevels.sort(function (a, b) {
  28098. if (a.distance < b.distance) {
  28099. return 1;
  28100. }
  28101. if (a.distance > b.distance) {
  28102. return -1;
  28103. }
  28104. return 0;
  28105. });
  28106. };
  28107. /**
  28108. * Add a mesh as LOD level triggered at the given distance.
  28109. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28110. * @param {number} distance The distance from the center of the object to show this level
  28111. * @param {Mesh} mesh The mesh to be added as LOD level
  28112. * @return {Mesh} This mesh (for chaining)
  28113. */
  28114. Mesh.prototype.addLODLevel = function (distance, mesh) {
  28115. if (mesh && mesh._masterMesh) {
  28116. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  28117. return this;
  28118. }
  28119. var level = new BABYLON.MeshLODLevel(distance, mesh);
  28120. this._LODLevels.push(level);
  28121. if (mesh) {
  28122. mesh._masterMesh = this;
  28123. }
  28124. this._sortLODLevels();
  28125. return this;
  28126. };
  28127. /**
  28128. * Returns the LOD level mesh at the passed distance or null if not found.
  28129. * It is related to the method `addLODLevel(distance, mesh)`.
  28130. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28131. * Returns an object Mesh or `null`.
  28132. */
  28133. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  28134. for (var index = 0; index < this._LODLevels.length; index++) {
  28135. var level = this._LODLevels[index];
  28136. if (level.distance === distance) {
  28137. return level.mesh;
  28138. }
  28139. }
  28140. return null;
  28141. };
  28142. /**
  28143. * Remove a mesh from the LOD array
  28144. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28145. * @param {Mesh} mesh The mesh to be removed.
  28146. * @return {Mesh} This mesh (for chaining)
  28147. */
  28148. Mesh.prototype.removeLODLevel = function (mesh) {
  28149. for (var index = 0; index < this._LODLevels.length; index++) {
  28150. if (this._LODLevels[index].mesh === mesh) {
  28151. this._LODLevels.splice(index, 1);
  28152. if (mesh) {
  28153. mesh._masterMesh = null;
  28154. }
  28155. }
  28156. }
  28157. this._sortLODLevels();
  28158. return this;
  28159. };
  28160. /**
  28161. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  28162. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28163. */
  28164. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  28165. if (!this._LODLevels || this._LODLevels.length === 0) {
  28166. return this;
  28167. }
  28168. var bSphere;
  28169. if (boundingSphere) {
  28170. bSphere = boundingSphere;
  28171. }
  28172. else {
  28173. var boundingInfo = this.getBoundingInfo();
  28174. bSphere = boundingInfo.boundingSphere;
  28175. }
  28176. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  28177. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  28178. if (this.onLODLevelSelection) {
  28179. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  28180. }
  28181. return this;
  28182. }
  28183. for (var index = 0; index < this._LODLevels.length; index++) {
  28184. var level = this._LODLevels[index];
  28185. if (level.distance < distanceToCamera) {
  28186. if (level.mesh) {
  28187. level.mesh._preActivate();
  28188. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  28189. }
  28190. if (this.onLODLevelSelection) {
  28191. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  28192. }
  28193. return level.mesh;
  28194. }
  28195. }
  28196. if (this.onLODLevelSelection) {
  28197. this.onLODLevelSelection(distanceToCamera, this, this);
  28198. }
  28199. return this;
  28200. };
  28201. Object.defineProperty(Mesh.prototype, "geometry", {
  28202. /**
  28203. * Returns the mesh internal Geometry object.
  28204. */
  28205. get: function () {
  28206. return this._geometry;
  28207. },
  28208. enumerable: true,
  28209. configurable: true
  28210. });
  28211. /**
  28212. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  28213. */
  28214. Mesh.prototype.getTotalVertices = function () {
  28215. if (this._geometry === null || this._geometry === undefined) {
  28216. return 0;
  28217. }
  28218. return this._geometry.getTotalVertices();
  28219. };
  28220. /**
  28221. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  28222. * 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.
  28223. * You can force the copy with forceCopy === true
  28224. * Returns null if the mesh has no geometry or no vertex buffer.
  28225. * Possible `kind` values :
  28226. * - BABYLON.VertexBuffer.PositionKind
  28227. * - BABYLON.VertexBuffer.UVKind
  28228. * - BABYLON.VertexBuffer.UV2Kind
  28229. * - BABYLON.VertexBuffer.UV3Kind
  28230. * - BABYLON.VertexBuffer.UV4Kind
  28231. * - BABYLON.VertexBuffer.UV5Kind
  28232. * - BABYLON.VertexBuffer.UV6Kind
  28233. * - BABYLON.VertexBuffer.ColorKind
  28234. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28235. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28236. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28237. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28238. */
  28239. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  28240. if (!this._geometry) {
  28241. return null;
  28242. }
  28243. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  28244. };
  28245. /**
  28246. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  28247. * Returns `null` if the mesh has no geometry.
  28248. * Possible `kind` values :
  28249. * - BABYLON.VertexBuffer.PositionKind
  28250. * - BABYLON.VertexBuffer.UVKind
  28251. * - BABYLON.VertexBuffer.UV2Kind
  28252. * - BABYLON.VertexBuffer.UV3Kind
  28253. * - BABYLON.VertexBuffer.UV4Kind
  28254. * - BABYLON.VertexBuffer.UV5Kind
  28255. * - BABYLON.VertexBuffer.UV6Kind
  28256. * - BABYLON.VertexBuffer.ColorKind
  28257. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28258. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28259. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28260. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28261. */
  28262. Mesh.prototype.getVertexBuffer = function (kind) {
  28263. if (!this._geometry) {
  28264. return null;
  28265. }
  28266. return this._geometry.getVertexBuffer(kind);
  28267. };
  28268. /**
  28269. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  28270. * Possible `kind` values :
  28271. * - BABYLON.VertexBuffer.PositionKind
  28272. * - BABYLON.VertexBuffer.UVKind
  28273. * - BABYLON.VertexBuffer.UV2Kind
  28274. * - BABYLON.VertexBuffer.UV3Kind
  28275. * - BABYLON.VertexBuffer.UV4Kind
  28276. * - BABYLON.VertexBuffer.UV5Kind
  28277. * - BABYLON.VertexBuffer.UV6Kind
  28278. * - BABYLON.VertexBuffer.ColorKind
  28279. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28280. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28281. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28282. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28283. */
  28284. Mesh.prototype.isVerticesDataPresent = function (kind) {
  28285. if (!this._geometry) {
  28286. if (this._delayInfo) {
  28287. return this._delayInfo.indexOf(kind) !== -1;
  28288. }
  28289. return false;
  28290. }
  28291. return this._geometry.isVerticesDataPresent(kind);
  28292. };
  28293. /**
  28294. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  28295. * Possible `kind` values :
  28296. * - BABYLON.VertexBuffer.PositionKind
  28297. * - BABYLON.VertexBuffer.UVKind
  28298. * - BABYLON.VertexBuffer.UV2Kind
  28299. * - BABYLON.VertexBuffer.UV3Kind
  28300. * - BABYLON.VertexBuffer.UV4Kind
  28301. * - BABYLON.VertexBuffer.UV5Kind
  28302. * - BABYLON.VertexBuffer.UV6Kind
  28303. * - BABYLON.VertexBuffer.ColorKind
  28304. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28305. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28306. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28307. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28308. */
  28309. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  28310. if (!this._geometry) {
  28311. if (this._delayInfo) {
  28312. return this._delayInfo.indexOf(kind) !== -1;
  28313. }
  28314. return false;
  28315. }
  28316. return this._geometry.isVertexBufferUpdatable(kind);
  28317. };
  28318. /**
  28319. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  28320. * Possible `kind` values :
  28321. * - BABYLON.VertexBuffer.PositionKind
  28322. * - BABYLON.VertexBuffer.UVKind
  28323. * - BABYLON.VertexBuffer.UV2Kind
  28324. * - BABYLON.VertexBuffer.UV3Kind
  28325. * - BABYLON.VertexBuffer.UV4Kind
  28326. * - BABYLON.VertexBuffer.UV5Kind
  28327. * - BABYLON.VertexBuffer.UV6Kind
  28328. * - BABYLON.VertexBuffer.ColorKind
  28329. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28330. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28331. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28332. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28333. */
  28334. Mesh.prototype.getVerticesDataKinds = function () {
  28335. if (!this._geometry) {
  28336. var result = new Array();
  28337. if (this._delayInfo) {
  28338. this._delayInfo.forEach(function (kind, index, array) {
  28339. result.push(kind);
  28340. });
  28341. }
  28342. return result;
  28343. }
  28344. return this._geometry.getVerticesDataKinds();
  28345. };
  28346. /**
  28347. * Returns a positive integer : the total number of indices in this mesh geometry.
  28348. * Returns zero if the mesh has no geometry.
  28349. */
  28350. Mesh.prototype.getTotalIndices = function () {
  28351. if (!this._geometry) {
  28352. return 0;
  28353. }
  28354. return this._geometry.getTotalIndices();
  28355. };
  28356. /**
  28357. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  28358. * 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.
  28359. * Returns an empty array if the mesh has no geometry.
  28360. */
  28361. Mesh.prototype.getIndices = function (copyWhenShared) {
  28362. if (!this._geometry) {
  28363. return [];
  28364. }
  28365. return this._geometry.getIndices(copyWhenShared);
  28366. };
  28367. Object.defineProperty(Mesh.prototype, "isBlocked", {
  28368. get: function () {
  28369. return this._masterMesh !== null && this._masterMesh !== undefined;
  28370. },
  28371. enumerable: true,
  28372. configurable: true
  28373. });
  28374. /**
  28375. * Determine if the current mesh is ready to be rendered
  28376. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  28377. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  28378. * @returns true if all associated assets are ready (material, textures, shaders)
  28379. */
  28380. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  28381. if (completeCheck === void 0) { completeCheck = false; }
  28382. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  28383. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28384. return false;
  28385. }
  28386. if (!_super.prototype.isReady.call(this, completeCheck)) {
  28387. return false;
  28388. }
  28389. if (!this.subMeshes || this.subMeshes.length === 0) {
  28390. return true;
  28391. }
  28392. if (!completeCheck) {
  28393. return true;
  28394. }
  28395. var engine = this.getEngine();
  28396. var scene = this.getScene();
  28397. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  28398. this.computeWorldMatrix();
  28399. var mat = this.material || scene.defaultMaterial;
  28400. if (mat) {
  28401. if (mat.storeEffectOnSubMeshes) {
  28402. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28403. var subMesh = _a[_i];
  28404. var effectiveMaterial = subMesh.getMaterial();
  28405. if (effectiveMaterial) {
  28406. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28407. return false;
  28408. }
  28409. }
  28410. }
  28411. }
  28412. else {
  28413. if (!mat.isReady(this, hardwareInstancedRendering)) {
  28414. return false;
  28415. }
  28416. }
  28417. }
  28418. // Shadows
  28419. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  28420. var light = _c[_b];
  28421. var generator = light.getShadowGenerator();
  28422. if (generator) {
  28423. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  28424. var subMesh = _e[_d];
  28425. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  28426. return false;
  28427. }
  28428. }
  28429. }
  28430. }
  28431. // LOD
  28432. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  28433. var lod = _g[_f];
  28434. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  28435. return false;
  28436. }
  28437. }
  28438. return true;
  28439. };
  28440. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  28441. /**
  28442. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  28443. * This property is pertinent only for updatable parametric shapes.
  28444. */
  28445. get: function () {
  28446. return this._areNormalsFrozen;
  28447. },
  28448. enumerable: true,
  28449. configurable: true
  28450. });
  28451. /**
  28452. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28453. * It has no effect at all on other shapes.
  28454. * It prevents the mesh normals from being recomputed on next `positions` array update.
  28455. * Returns the Mesh.
  28456. */
  28457. Mesh.prototype.freezeNormals = function () {
  28458. this._areNormalsFrozen = true;
  28459. return this;
  28460. };
  28461. /**
  28462. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28463. * It has no effect at all on other shapes.
  28464. * It reactivates the mesh normals computation if it was previously frozen.
  28465. * Returns the Mesh.
  28466. */
  28467. Mesh.prototype.unfreezeNormals = function () {
  28468. this._areNormalsFrozen = false;
  28469. return this;
  28470. };
  28471. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  28472. /**
  28473. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  28474. */
  28475. set: function (count) {
  28476. this._overridenInstanceCount = count;
  28477. },
  28478. enumerable: true,
  28479. configurable: true
  28480. });
  28481. // Methods
  28482. Mesh.prototype._preActivate = function () {
  28483. var sceneRenderId = this.getScene().getRenderId();
  28484. if (this._preActivateId === sceneRenderId) {
  28485. return this;
  28486. }
  28487. this._preActivateId = sceneRenderId;
  28488. this._visibleInstances = null;
  28489. return this;
  28490. };
  28491. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  28492. if (this._visibleInstances) {
  28493. this._visibleInstances.intermediateDefaultRenderId = renderId;
  28494. }
  28495. return this;
  28496. };
  28497. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  28498. if (!this._visibleInstances) {
  28499. this._visibleInstances = {};
  28500. this._visibleInstances.defaultRenderId = renderId;
  28501. this._visibleInstances.selfDefaultRenderId = this._renderId;
  28502. }
  28503. if (!this._visibleInstances[renderId]) {
  28504. this._visibleInstances[renderId] = new Array();
  28505. }
  28506. this._visibleInstances[renderId].push(instance);
  28507. return this;
  28508. };
  28509. /**
  28510. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  28511. * This means the mesh underlying bounding box and sphere are recomputed.
  28512. * Returns the Mesh.
  28513. */
  28514. Mesh.prototype.refreshBoundingInfo = function () {
  28515. return this._refreshBoundingInfo(false);
  28516. };
  28517. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  28518. if (this._boundingInfo && this._boundingInfo.isLocked) {
  28519. return this;
  28520. }
  28521. var data = this._getPositionData(applySkeleton);
  28522. if (data) {
  28523. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  28524. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28525. }
  28526. if (this.subMeshes) {
  28527. for (var index = 0; index < this.subMeshes.length; index++) {
  28528. this.subMeshes[index].refreshBoundingInfo();
  28529. }
  28530. }
  28531. this._updateBoundingInfo();
  28532. return this;
  28533. };
  28534. Mesh.prototype._getPositionData = function (applySkeleton) {
  28535. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28536. if (data && applySkeleton && this.skeleton) {
  28537. data = BABYLON.Tools.Slice(data);
  28538. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28539. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28540. if (matricesWeightsData && matricesIndicesData) {
  28541. var needExtras = this.numBoneInfluencers > 4;
  28542. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28543. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28544. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  28545. var tempVector = BABYLON.Tmp.Vector3[0];
  28546. var finalMatrix = BABYLON.Tmp.Matrix[0];
  28547. var tempMatrix = BABYLON.Tmp.Matrix[1];
  28548. var matWeightIdx = 0;
  28549. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  28550. finalMatrix.reset();
  28551. var inf;
  28552. var weight;
  28553. for (inf = 0; inf < 4; inf++) {
  28554. weight = matricesWeightsData[matWeightIdx + inf];
  28555. if (weight <= 0)
  28556. break;
  28557. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28558. finalMatrix.addToSelf(tempMatrix);
  28559. }
  28560. if (needExtras) {
  28561. for (inf = 0; inf < 4; inf++) {
  28562. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28563. if (weight <= 0)
  28564. break;
  28565. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28566. finalMatrix.addToSelf(tempMatrix);
  28567. }
  28568. }
  28569. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  28570. tempVector.toArray(data, index);
  28571. }
  28572. }
  28573. }
  28574. return data;
  28575. };
  28576. Mesh.prototype._createGlobalSubMesh = function (force) {
  28577. var totalVertices = this.getTotalVertices();
  28578. if (!totalVertices || !this.getIndices()) {
  28579. return null;
  28580. }
  28581. // Check if we need to recreate the submeshes
  28582. if (this.subMeshes && this.subMeshes.length > 0) {
  28583. var ib = this.getIndices();
  28584. if (!ib) {
  28585. return null;
  28586. }
  28587. var totalIndices = ib.length;
  28588. var needToRecreate = false;
  28589. if (force) {
  28590. needToRecreate = true;
  28591. }
  28592. else {
  28593. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28594. var submesh = _a[_i];
  28595. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  28596. needToRecreate = true;
  28597. break;
  28598. }
  28599. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  28600. needToRecreate = true;
  28601. break;
  28602. }
  28603. }
  28604. }
  28605. if (!needToRecreate) {
  28606. return this.subMeshes[0];
  28607. }
  28608. }
  28609. this.releaseSubMeshes();
  28610. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28611. };
  28612. Mesh.prototype.subdivide = function (count) {
  28613. if (count < 1) {
  28614. return;
  28615. }
  28616. var totalIndices = this.getTotalIndices();
  28617. var subdivisionSize = (totalIndices / count) | 0;
  28618. var offset = 0;
  28619. // Ensure that subdivisionSize is a multiple of 3
  28620. while (subdivisionSize % 3 !== 0) {
  28621. subdivisionSize++;
  28622. }
  28623. this.releaseSubMeshes();
  28624. for (var index = 0; index < count; index++) {
  28625. if (offset >= totalIndices) {
  28626. break;
  28627. }
  28628. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28629. offset += subdivisionSize;
  28630. }
  28631. this.synchronizeInstances();
  28632. };
  28633. /**
  28634. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28635. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28636. * The `data` are either a numeric array either a Float32Array.
  28637. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28638. * 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).
  28639. * Note that a new underlying VertexBuffer object is created each call.
  28640. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28641. *
  28642. * Possible `kind` values :
  28643. * - BABYLON.VertexBuffer.PositionKind
  28644. * - BABYLON.VertexBuffer.UVKind
  28645. * - BABYLON.VertexBuffer.UV2Kind
  28646. * - BABYLON.VertexBuffer.UV3Kind
  28647. * - BABYLON.VertexBuffer.UV4Kind
  28648. * - BABYLON.VertexBuffer.UV5Kind
  28649. * - BABYLON.VertexBuffer.UV6Kind
  28650. * - BABYLON.VertexBuffer.ColorKind
  28651. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28652. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28653. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28654. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28655. *
  28656. * Returns the Mesh.
  28657. */
  28658. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28659. if (updatable === void 0) { updatable = false; }
  28660. if (!this._geometry) {
  28661. var vertexData = new BABYLON.VertexData();
  28662. vertexData.set(data, kind);
  28663. var scene = this.getScene();
  28664. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28665. }
  28666. else {
  28667. this._geometry.setVerticesData(kind, data, updatable, stride);
  28668. }
  28669. return this;
  28670. };
  28671. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28672. if (updatable === void 0) { updatable = true; }
  28673. var vb = this.getVertexBuffer(kind);
  28674. if (!vb || vb.isUpdatable() === updatable) {
  28675. return;
  28676. }
  28677. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28678. };
  28679. /**
  28680. * Sets the mesh VertexBuffer.
  28681. * Returns the Mesh.
  28682. */
  28683. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28684. if (!this._geometry) {
  28685. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28686. }
  28687. this._geometry.setVerticesBuffer(buffer);
  28688. return this;
  28689. };
  28690. /**
  28691. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28692. * If the mesh has no geometry, it is simply returned as it is.
  28693. * The `data` are either a numeric array either a Float32Array.
  28694. * No new underlying VertexBuffer object is created.
  28695. * 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.
  28696. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28697. *
  28698. * Possible `kind` values :
  28699. * - BABYLON.VertexBuffer.PositionKind
  28700. * - BABYLON.VertexBuffer.UVKind
  28701. * - BABYLON.VertexBuffer.UV2Kind
  28702. * - BABYLON.VertexBuffer.UV3Kind
  28703. * - BABYLON.VertexBuffer.UV4Kind
  28704. * - BABYLON.VertexBuffer.UV5Kind
  28705. * - BABYLON.VertexBuffer.UV6Kind
  28706. * - BABYLON.VertexBuffer.ColorKind
  28707. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28708. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28709. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28710. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28711. *
  28712. * Returns the Mesh.
  28713. */
  28714. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28715. if (!this._geometry) {
  28716. return this;
  28717. }
  28718. if (!makeItUnique) {
  28719. this._geometry.updateVerticesData(kind, data, updateExtends);
  28720. }
  28721. else {
  28722. this.makeGeometryUnique();
  28723. this.updateVerticesData(kind, data, updateExtends, false);
  28724. }
  28725. return this;
  28726. };
  28727. /**
  28728. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28729. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28730. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28731. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28732. * Returns the Mesh.
  28733. */
  28734. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28735. if (computeNormals === void 0) { computeNormals = true; }
  28736. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28737. if (!positions) {
  28738. return this;
  28739. }
  28740. positionFunction(positions);
  28741. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28742. if (computeNormals) {
  28743. var indices = this.getIndices();
  28744. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28745. if (!normals) {
  28746. return this;
  28747. }
  28748. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28749. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28750. }
  28751. return this;
  28752. };
  28753. /**
  28754. * Creates a un-shared specific occurence of the geometry for the mesh.
  28755. * Returns the Mesh.
  28756. */
  28757. Mesh.prototype.makeGeometryUnique = function () {
  28758. if (!this._geometry) {
  28759. return this;
  28760. }
  28761. var oldGeometry = this._geometry;
  28762. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28763. oldGeometry.releaseForMesh(this, true);
  28764. geometry.applyToMesh(this);
  28765. return this;
  28766. };
  28767. /**
  28768. * Sets the mesh indices.
  28769. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28770. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28771. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28772. * This method creates a new index buffer each call.
  28773. * Returns the Mesh.
  28774. */
  28775. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28776. if (totalVertices === void 0) { totalVertices = null; }
  28777. if (updatable === void 0) { updatable = false; }
  28778. if (!this._geometry) {
  28779. var vertexData = new BABYLON.VertexData();
  28780. vertexData.indices = indices;
  28781. var scene = this.getScene();
  28782. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28783. }
  28784. else {
  28785. this._geometry.setIndices(indices, totalVertices, updatable);
  28786. }
  28787. return this;
  28788. };
  28789. /**
  28790. * Update the current index buffer
  28791. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28792. * Returns the Mesh.
  28793. */
  28794. Mesh.prototype.updateIndices = function (indices, offset) {
  28795. if (!this._geometry) {
  28796. return this;
  28797. }
  28798. this._geometry.updateIndices(indices, offset);
  28799. return this;
  28800. };
  28801. /**
  28802. * Invert the geometry to move from a right handed system to a left handed one.
  28803. * Returns the Mesh.
  28804. */
  28805. Mesh.prototype.toLeftHanded = function () {
  28806. if (!this._geometry) {
  28807. return this;
  28808. }
  28809. this._geometry.toLeftHanded();
  28810. return this;
  28811. };
  28812. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28813. if (!this._geometry) {
  28814. return this;
  28815. }
  28816. var engine = this.getScene().getEngine();
  28817. // Wireframe
  28818. var indexToBind;
  28819. if (this._unIndexed) {
  28820. indexToBind = null;
  28821. }
  28822. else {
  28823. switch (fillMode) {
  28824. case BABYLON.Material.PointFillMode:
  28825. indexToBind = null;
  28826. break;
  28827. case BABYLON.Material.WireFrameFillMode:
  28828. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28829. break;
  28830. default:
  28831. case BABYLON.Material.TriangleFillMode:
  28832. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28833. break;
  28834. }
  28835. }
  28836. // VBOs
  28837. this._geometry._bind(effect, indexToBind);
  28838. return this;
  28839. };
  28840. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28841. if (alternate === void 0) { alternate = false; }
  28842. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28843. return this;
  28844. }
  28845. this.onBeforeDrawObservable.notifyObservers(this);
  28846. var scene = this.getScene();
  28847. var engine = scene.getEngine();
  28848. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28849. // or triangles as points
  28850. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28851. }
  28852. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28853. // Triangles as wireframe
  28854. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28855. }
  28856. else {
  28857. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28858. }
  28859. if (scene._isAlternateRenderingEnabled && !alternate) {
  28860. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28861. if (!effect || !scene.activeCamera) {
  28862. return this;
  28863. }
  28864. scene._switchToAlternateCameraConfiguration(true);
  28865. this._effectiveMaterial.bindView(effect);
  28866. this._effectiveMaterial.bindViewProjection(effect);
  28867. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28868. this._draw(subMesh, fillMode, instancesCount, true);
  28869. engine.setViewport(scene.activeCamera.viewport);
  28870. scene._switchToAlternateCameraConfiguration(false);
  28871. this._effectiveMaterial.bindView(effect);
  28872. this._effectiveMaterial.bindViewProjection(effect);
  28873. }
  28874. return this;
  28875. };
  28876. /**
  28877. * Registers for this mesh a javascript function called just before the rendering process.
  28878. * This function is passed the current mesh.
  28879. * Return the Mesh.
  28880. */
  28881. Mesh.prototype.registerBeforeRender = function (func) {
  28882. this.onBeforeRenderObservable.add(func);
  28883. return this;
  28884. };
  28885. /**
  28886. * Disposes a previously registered javascript function called before the rendering.
  28887. * This function is passed the current mesh.
  28888. * Returns the Mesh.
  28889. */
  28890. Mesh.prototype.unregisterBeforeRender = function (func) {
  28891. this.onBeforeRenderObservable.removeCallback(func);
  28892. return this;
  28893. };
  28894. /**
  28895. * Registers for this mesh a javascript function called just after the rendering is complete.
  28896. * This function is passed the current mesh.
  28897. * Returns the Mesh.
  28898. */
  28899. Mesh.prototype.registerAfterRender = function (func) {
  28900. this.onAfterRenderObservable.add(func);
  28901. return this;
  28902. };
  28903. /**
  28904. * Disposes a previously registered javascript function called after the rendering.
  28905. * This function is passed the current mesh.
  28906. * Return the Mesh.
  28907. */
  28908. Mesh.prototype.unregisterAfterRender = function (func) {
  28909. this.onAfterRenderObservable.removeCallback(func);
  28910. return this;
  28911. };
  28912. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28913. var scene = this.getScene();
  28914. this._batchCache.mustReturn = false;
  28915. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28916. this._batchCache.visibleInstances[subMeshId] = null;
  28917. if (this._visibleInstances) {
  28918. var currentRenderId = scene.getRenderId();
  28919. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28920. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28921. var selfRenderId = this._renderId;
  28922. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28923. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28924. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28925. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28926. }
  28927. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28928. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28929. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28930. this._batchCache.mustReturn = true;
  28931. return this._batchCache;
  28932. }
  28933. if (currentRenderId !== selfRenderId) {
  28934. this._batchCache.renderSelf[subMeshId] = false;
  28935. }
  28936. }
  28937. this._renderIdForInstances[subMeshId] = currentRenderId;
  28938. }
  28939. return this._batchCache;
  28940. };
  28941. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28942. var visibleInstances = batch.visibleInstances[subMesh._id];
  28943. if (!visibleInstances) {
  28944. return this;
  28945. }
  28946. var matricesCount = visibleInstances.length + 1;
  28947. var bufferSize = matricesCount * 16 * 4;
  28948. var currentInstancesBufferSize = this._instancesBufferSize;
  28949. var instancesBuffer = this._instancesBuffer;
  28950. while (this._instancesBufferSize < bufferSize) {
  28951. this._instancesBufferSize *= 2;
  28952. }
  28953. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28954. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28955. }
  28956. var offset = 0;
  28957. var instancesCount = 0;
  28958. var world = this.getWorldMatrix();
  28959. if (batch.renderSelf[subMesh._id]) {
  28960. world.copyToArray(this._instancesData, offset);
  28961. offset += 16;
  28962. instancesCount++;
  28963. }
  28964. if (visibleInstances) {
  28965. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28966. var instance = visibleInstances[instanceIndex];
  28967. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28968. offset += 16;
  28969. instancesCount++;
  28970. }
  28971. }
  28972. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28973. if (instancesBuffer) {
  28974. instancesBuffer.dispose();
  28975. }
  28976. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28977. this._instancesBuffer = instancesBuffer;
  28978. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28979. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28980. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28981. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28982. }
  28983. else {
  28984. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28985. }
  28986. this._bind(subMesh, effect, fillMode);
  28987. this._draw(subMesh, fillMode, instancesCount);
  28988. engine.unbindInstanceAttributes();
  28989. return this;
  28990. };
  28991. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28992. var scene = this.getScene();
  28993. var engine = scene.getEngine();
  28994. if (hardwareInstancedRendering) {
  28995. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28996. }
  28997. else {
  28998. if (batch.renderSelf[subMesh._id]) {
  28999. // Draw
  29000. if (onBeforeDraw) {
  29001. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  29002. }
  29003. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  29004. }
  29005. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  29006. if (visibleInstancesForSubMesh) {
  29007. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  29008. var instance = visibleInstancesForSubMesh[instanceIndex];
  29009. // World
  29010. var world = instance.getWorldMatrix();
  29011. if (onBeforeDraw) {
  29012. onBeforeDraw(true, world, effectiveMaterial);
  29013. }
  29014. // Draw
  29015. this._draw(subMesh, fillMode);
  29016. }
  29017. }
  29018. }
  29019. return this;
  29020. };
  29021. /**
  29022. * Triggers the draw call for the mesh.
  29023. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  29024. * Returns the Mesh.
  29025. */
  29026. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  29027. this.checkOcclusionQuery();
  29028. if (this._isOccluded) {
  29029. return this;
  29030. }
  29031. var scene = this.getScene();
  29032. // Managing instances
  29033. var batch = this._getInstancesRenderList(subMesh._id);
  29034. if (batch.mustReturn) {
  29035. return this;
  29036. }
  29037. // Checking geometry state
  29038. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  29039. return this;
  29040. }
  29041. this.onBeforeRenderObservable.notifyObservers(this);
  29042. var engine = scene.getEngine();
  29043. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  29044. // Material
  29045. var material = subMesh.getMaterial();
  29046. if (!material) {
  29047. return this;
  29048. }
  29049. this._effectiveMaterial = material;
  29050. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29051. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  29052. return this;
  29053. }
  29054. }
  29055. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  29056. return this;
  29057. }
  29058. // Alpha mode
  29059. if (enableAlphaMode) {
  29060. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  29061. }
  29062. // Outline - step 1
  29063. var savedDepthWrite = engine.getDepthWrite();
  29064. if (this.renderOutline) {
  29065. engine.setDepthWrite(false);
  29066. scene.getOutlineRenderer().render(subMesh, batch);
  29067. engine.setDepthWrite(savedDepthWrite);
  29068. }
  29069. var effect;
  29070. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29071. effect = subMesh.effect;
  29072. }
  29073. else {
  29074. effect = this._effectiveMaterial.getEffect();
  29075. }
  29076. if (!effect) {
  29077. return this;
  29078. }
  29079. var sideOrientation = this.overrideMaterialSideOrientation;
  29080. if (sideOrientation == null) {
  29081. sideOrientation = this._effectiveMaterial.sideOrientation;
  29082. if (this._getWorldMatrixDeterminant() < 0) {
  29083. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  29084. }
  29085. }
  29086. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  29087. if (this._effectiveMaterial.forceDepthWrite) {
  29088. engine.setDepthWrite(true);
  29089. }
  29090. // Bind
  29091. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  29092. if (!hardwareInstancedRendering) {
  29093. this._bind(subMesh, effect, fillMode);
  29094. }
  29095. var world = this.getWorldMatrix();
  29096. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29097. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  29098. }
  29099. else {
  29100. this._effectiveMaterial.bind(world, this);
  29101. }
  29102. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  29103. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  29104. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29105. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  29106. }
  29107. // Draw
  29108. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29109. // Unbind
  29110. this._effectiveMaterial.unbind();
  29111. // Outline - step 2
  29112. if (this.renderOutline && savedDepthWrite) {
  29113. engine.setDepthWrite(true);
  29114. engine.setColorWrite(false);
  29115. scene.getOutlineRenderer().render(subMesh, batch);
  29116. engine.setColorWrite(true);
  29117. }
  29118. // Overlay
  29119. if (this.renderOverlay) {
  29120. var currentMode = engine.getAlphaMode();
  29121. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  29122. scene.getOutlineRenderer().render(subMesh, batch, true);
  29123. engine.setAlphaMode(currentMode);
  29124. }
  29125. this.onAfterRenderObservable.notifyObservers(this);
  29126. return this;
  29127. };
  29128. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  29129. if (isInstance && effectiveMaterial) {
  29130. effectiveMaterial.bindOnlyWorldMatrix(world);
  29131. }
  29132. };
  29133. /**
  29134. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  29135. */
  29136. Mesh.prototype.getEmittedParticleSystems = function () {
  29137. var results = new Array();
  29138. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29139. var particleSystem = this.getScene().particleSystems[index];
  29140. if (particleSystem.emitter === this) {
  29141. results.push(particleSystem);
  29142. }
  29143. }
  29144. return results;
  29145. };
  29146. /**
  29147. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  29148. */
  29149. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  29150. var results = new Array();
  29151. var descendants = this.getDescendants();
  29152. descendants.push(this);
  29153. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29154. var particleSystem = this.getScene().particleSystems[index];
  29155. var emitter = particleSystem.emitter;
  29156. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  29157. results.push(particleSystem);
  29158. }
  29159. }
  29160. return results;
  29161. };
  29162. Mesh.prototype._checkDelayState = function () {
  29163. var scene = this.getScene();
  29164. if (this._geometry) {
  29165. this._geometry.load(scene);
  29166. }
  29167. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29168. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29169. this._queueLoad(scene);
  29170. }
  29171. return this;
  29172. };
  29173. Mesh.prototype._queueLoad = function (scene) {
  29174. var _this = this;
  29175. scene._addPendingData(this);
  29176. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  29177. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29178. if (data instanceof ArrayBuffer) {
  29179. _this._delayLoadingFunction(data, _this);
  29180. }
  29181. else {
  29182. _this._delayLoadingFunction(JSON.parse(data), _this);
  29183. }
  29184. _this.instances.forEach(function (instance) {
  29185. instance._syncSubMeshes();
  29186. });
  29187. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29188. scene._removePendingData(_this);
  29189. }, function () { }, scene.database, getBinaryData);
  29190. return this;
  29191. };
  29192. /**
  29193. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  29194. */
  29195. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  29196. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29197. return false;
  29198. }
  29199. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  29200. return false;
  29201. }
  29202. this._checkDelayState();
  29203. return true;
  29204. };
  29205. /**
  29206. * Sets the mesh material by the material or multiMaterial `id` property.
  29207. * The material `id` is a string identifying the material or the multiMaterial.
  29208. * This method returns the Mesh.
  29209. */
  29210. Mesh.prototype.setMaterialByID = function (id) {
  29211. var materials = this.getScene().materials;
  29212. var index;
  29213. for (index = materials.length - 1; index > -1; index--) {
  29214. if (materials[index].id === id) {
  29215. this.material = materials[index];
  29216. return this;
  29217. }
  29218. }
  29219. // Multi
  29220. var multiMaterials = this.getScene().multiMaterials;
  29221. for (index = multiMaterials.length - 1; index > -1; index--) {
  29222. if (multiMaterials[index].id === id) {
  29223. this.material = multiMaterials[index];
  29224. return this;
  29225. }
  29226. }
  29227. return this;
  29228. };
  29229. /**
  29230. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  29231. */
  29232. Mesh.prototype.getAnimatables = function () {
  29233. var results = new Array();
  29234. if (this.material) {
  29235. results.push(this.material);
  29236. }
  29237. if (this.skeleton) {
  29238. results.push(this.skeleton);
  29239. }
  29240. return results;
  29241. };
  29242. /**
  29243. * Modifies the mesh geometry according to the passed transformation matrix.
  29244. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  29245. * The mesh normals are modified accordingly the same transformation.
  29246. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  29247. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29248. * Returns the Mesh.
  29249. */
  29250. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  29251. // Position
  29252. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29253. return this;
  29254. }
  29255. var submeshes = this.subMeshes.splice(0);
  29256. this._resetPointsArrayCache();
  29257. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29258. var temp = new Array();
  29259. var index;
  29260. for (index = 0; index < data.length; index += 3) {
  29261. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  29262. }
  29263. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  29264. // Normals
  29265. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29266. return this;
  29267. }
  29268. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29269. temp = [];
  29270. for (index = 0; index < data.length; index += 3) {
  29271. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  29272. }
  29273. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  29274. // flip faces?
  29275. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  29276. this.flipFaces();
  29277. }
  29278. // Restore submeshes
  29279. this.releaseSubMeshes();
  29280. this.subMeshes = submeshes;
  29281. return this;
  29282. };
  29283. /**
  29284. * Modifies the mesh geometry according to its own current World Matrix.
  29285. * The mesh World Matrix is then reset.
  29286. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  29287. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  29288. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29289. * Returns the Mesh.
  29290. */
  29291. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  29292. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  29293. this.scaling.copyFromFloats(1, 1, 1);
  29294. this.position.copyFromFloats(0, 0, 0);
  29295. this.rotation.copyFromFloats(0, 0, 0);
  29296. //only if quaternion is already set
  29297. if (this.rotationQuaternion) {
  29298. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  29299. }
  29300. this._worldMatrix = BABYLON.Matrix.Identity();
  29301. return this;
  29302. };
  29303. Object.defineProperty(Mesh.prototype, "_positions", {
  29304. // Cache
  29305. get: function () {
  29306. if (this._geometry) {
  29307. return this._geometry._positions;
  29308. }
  29309. return null;
  29310. },
  29311. enumerable: true,
  29312. configurable: true
  29313. });
  29314. Mesh.prototype._resetPointsArrayCache = function () {
  29315. if (this._geometry) {
  29316. this._geometry._resetPointsArrayCache();
  29317. }
  29318. return this;
  29319. };
  29320. Mesh.prototype._generatePointsArray = function () {
  29321. if (this._geometry) {
  29322. return this._geometry._generatePointsArray();
  29323. }
  29324. return false;
  29325. };
  29326. /**
  29327. * Returns a new Mesh object generated from the current mesh properties.
  29328. * This method must not get confused with createInstance().
  29329. * The parameter `name` is a string, the name given to the new mesh.
  29330. * The optional parameter `newParent` can be any Node object (default `null`).
  29331. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  29332. * 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.
  29333. */
  29334. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  29335. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  29336. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  29337. };
  29338. /**
  29339. * Releases resources associated with this mesh.
  29340. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  29341. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  29342. */
  29343. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  29344. var _this = this;
  29345. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  29346. this.morphTargetManager = null;
  29347. if (this._geometry) {
  29348. this._geometry.releaseForMesh(this, true);
  29349. }
  29350. // Sources
  29351. var meshes = this.getScene().meshes;
  29352. meshes.forEach(function (abstractMesh) {
  29353. var mesh = abstractMesh;
  29354. if (mesh._source && mesh._source === _this) {
  29355. mesh._source = null;
  29356. }
  29357. });
  29358. this._source = null;
  29359. // Instances
  29360. if (this._instancesBuffer) {
  29361. this._instancesBuffer.dispose();
  29362. this._instancesBuffer = null;
  29363. }
  29364. while (this.instances.length) {
  29365. this.instances[0].dispose();
  29366. }
  29367. // Effect layers.
  29368. var effectLayers = this.getScene().effectLayers;
  29369. for (var i = 0; i < effectLayers.length; i++) {
  29370. var effectLayer = effectLayers[i];
  29371. if (effectLayer) {
  29372. effectLayer._disposeMesh(this);
  29373. }
  29374. }
  29375. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  29376. };
  29377. /**
  29378. * Modifies the mesh geometry according to a displacement map.
  29379. * 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.
  29380. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29381. * This method returns nothing.
  29382. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  29383. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29384. * 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.
  29385. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29386. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29387. *
  29388. * Returns the Mesh.
  29389. */
  29390. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  29391. var _this = this;
  29392. var scene = this.getScene();
  29393. var onload = function (img) {
  29394. // Getting height map data
  29395. var canvas = document.createElement("canvas");
  29396. var context = canvas.getContext("2d");
  29397. var heightMapWidth = img.width;
  29398. var heightMapHeight = img.height;
  29399. canvas.width = heightMapWidth;
  29400. canvas.height = heightMapHeight;
  29401. context.drawImage(img, 0, 0);
  29402. // Create VertexData from map data
  29403. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  29404. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  29405. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  29406. //execute success callback, if set
  29407. if (onSuccess) {
  29408. onSuccess(_this);
  29409. }
  29410. };
  29411. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  29412. return this;
  29413. };
  29414. /**
  29415. * Modifies the mesh geometry according to a displacementMap buffer.
  29416. * 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.
  29417. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29418. * This method returns nothing.
  29419. * 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.
  29420. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  29421. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29422. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29423. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29424. *
  29425. * Returns the Mesh.
  29426. */
  29427. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  29428. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  29429. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  29430. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29431. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  29432. return this;
  29433. }
  29434. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29435. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29436. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29437. var position = BABYLON.Vector3.Zero();
  29438. var normal = BABYLON.Vector3.Zero();
  29439. var uv = BABYLON.Vector2.Zero();
  29440. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  29441. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  29442. for (var index = 0; index < positions.length; index += 3) {
  29443. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  29444. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  29445. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  29446. // Compute height
  29447. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  29448. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  29449. var pos = (u + v * heightMapWidth) * 4;
  29450. var r = buffer[pos] / 255.0;
  29451. var g = buffer[pos + 1] / 255.0;
  29452. var b = buffer[pos + 2] / 255.0;
  29453. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  29454. normal.normalize();
  29455. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  29456. position = position.add(normal);
  29457. position.toArray(positions, index);
  29458. }
  29459. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  29460. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  29461. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  29462. return this;
  29463. };
  29464. /**
  29465. * Modify the mesh to get a flat shading rendering.
  29466. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  29467. * This method returns the Mesh.
  29468. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  29469. */
  29470. Mesh.prototype.convertToFlatShadedMesh = function () {
  29471. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  29472. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29473. var kinds = this.getVerticesDataKinds();
  29474. var vbs = {};
  29475. var data = {};
  29476. var newdata = {};
  29477. var updatableNormals = false;
  29478. var kindIndex;
  29479. var kind;
  29480. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29481. kind = kinds[kindIndex];
  29482. var vertexBuffer = this.getVertexBuffer(kind);
  29483. if (kind === BABYLON.VertexBuffer.NormalKind) {
  29484. updatableNormals = vertexBuffer.isUpdatable();
  29485. kinds.splice(kindIndex, 1);
  29486. kindIndex--;
  29487. continue;
  29488. }
  29489. vbs[kind] = vertexBuffer;
  29490. data[kind] = vbs[kind].getData();
  29491. newdata[kind] = [];
  29492. }
  29493. // Save previous submeshes
  29494. var previousSubmeshes = this.subMeshes.slice(0);
  29495. var indices = this.getIndices();
  29496. var totalIndices = this.getTotalIndices();
  29497. // Generating unique vertices per face
  29498. var index;
  29499. for (index = 0; index < totalIndices; index++) {
  29500. var vertexIndex = indices[index];
  29501. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29502. kind = kinds[kindIndex];
  29503. var stride = vbs[kind].getStrideSize();
  29504. for (var offset = 0; offset < stride; offset++) {
  29505. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29506. }
  29507. }
  29508. }
  29509. // Updating faces & normal
  29510. var normals = [];
  29511. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  29512. for (index = 0; index < totalIndices; index += 3) {
  29513. indices[index] = index;
  29514. indices[index + 1] = index + 1;
  29515. indices[index + 2] = index + 2;
  29516. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  29517. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  29518. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  29519. var p1p2 = p1.subtract(p2);
  29520. var p3p2 = p3.subtract(p2);
  29521. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  29522. // Store same normals for every vertex
  29523. for (var localIndex = 0; localIndex < 3; localIndex++) {
  29524. normals.push(normal.x);
  29525. normals.push(normal.y);
  29526. normals.push(normal.z);
  29527. }
  29528. }
  29529. this.setIndices(indices);
  29530. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  29531. // Updating vertex buffers
  29532. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29533. kind = kinds[kindIndex];
  29534. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29535. }
  29536. // Updating submeshes
  29537. this.releaseSubMeshes();
  29538. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29539. var previousOne = previousSubmeshes[submeshIndex];
  29540. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29541. }
  29542. this.synchronizeInstances();
  29543. return this;
  29544. };
  29545. /**
  29546. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  29547. * In other words, more vertices, no more indices and a single bigger VBO.
  29548. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  29549. * Returns the Mesh.
  29550. */
  29551. Mesh.prototype.convertToUnIndexedMesh = function () {
  29552. /// <summary>Remove indices by unfolding faces into buffers</summary>
  29553. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29554. var kinds = this.getVerticesDataKinds();
  29555. var vbs = {};
  29556. var data = {};
  29557. var newdata = {};
  29558. var kindIndex;
  29559. var kind;
  29560. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29561. kind = kinds[kindIndex];
  29562. var vertexBuffer = this.getVertexBuffer(kind);
  29563. vbs[kind] = vertexBuffer;
  29564. data[kind] = vbs[kind].getData();
  29565. newdata[kind] = [];
  29566. }
  29567. // Save previous submeshes
  29568. var previousSubmeshes = this.subMeshes.slice(0);
  29569. var indices = this.getIndices();
  29570. var totalIndices = this.getTotalIndices();
  29571. // Generating unique vertices per face
  29572. var index;
  29573. for (index = 0; index < totalIndices; index++) {
  29574. var vertexIndex = indices[index];
  29575. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29576. kind = kinds[kindIndex];
  29577. var stride = vbs[kind].getStrideSize();
  29578. for (var offset = 0; offset < stride; offset++) {
  29579. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29580. }
  29581. }
  29582. }
  29583. // Updating indices
  29584. for (index = 0; index < totalIndices; index += 3) {
  29585. indices[index] = index;
  29586. indices[index + 1] = index + 1;
  29587. indices[index + 2] = index + 2;
  29588. }
  29589. this.setIndices(indices);
  29590. // Updating vertex buffers
  29591. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29592. kind = kinds[kindIndex];
  29593. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29594. }
  29595. // Updating submeshes
  29596. this.releaseSubMeshes();
  29597. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29598. var previousOne = previousSubmeshes[submeshIndex];
  29599. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29600. }
  29601. this._unIndexed = true;
  29602. this.synchronizeInstances();
  29603. return this;
  29604. };
  29605. /**
  29606. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  29607. * This method returns the Mesh.
  29608. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  29609. */
  29610. Mesh.prototype.flipFaces = function (flipNormals) {
  29611. if (flipNormals === void 0) { flipNormals = false; }
  29612. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29613. var i;
  29614. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29615. for (i = 0; i < vertex_data.normals.length; i++) {
  29616. vertex_data.normals[i] *= -1;
  29617. }
  29618. }
  29619. if (vertex_data.indices) {
  29620. var temp;
  29621. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29622. // reassign indices
  29623. temp = vertex_data.indices[i + 1];
  29624. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29625. vertex_data.indices[i + 2] = temp;
  29626. }
  29627. }
  29628. vertex_data.applyToMesh(this);
  29629. return this;
  29630. };
  29631. // Instances
  29632. /**
  29633. * Creates a new InstancedMesh object from the mesh model.
  29634. * An instance shares the same properties and the same material than its model.
  29635. * Only these properties of each instance can then be set individually :
  29636. * - position
  29637. * - rotation
  29638. * - rotationQuaternion
  29639. * - setPivotMatrix
  29640. * - scaling
  29641. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29642. * Warning : this method is not supported for Line mesh and LineSystem
  29643. */
  29644. Mesh.prototype.createInstance = function (name) {
  29645. return new BABYLON.InstancedMesh(name, this);
  29646. };
  29647. /**
  29648. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29649. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29650. * This method returns the Mesh.
  29651. */
  29652. Mesh.prototype.synchronizeInstances = function () {
  29653. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29654. var instance = this.instances[instanceIndex];
  29655. instance._syncSubMeshes();
  29656. }
  29657. return this;
  29658. };
  29659. /**
  29660. * Simplify the mesh according to the given array of settings.
  29661. * Function will return immediately and will simplify async. It returns the Mesh.
  29662. * @param settings a collection of simplification settings.
  29663. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29664. * @param type the type of simplification to run.
  29665. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29666. */
  29667. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29668. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29669. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29670. this.getScene().simplificationQueue.addTask({
  29671. settings: settings,
  29672. parallelProcessing: parallelProcessing,
  29673. mesh: this,
  29674. simplificationType: simplificationType,
  29675. successCallback: successCallback
  29676. });
  29677. return this;
  29678. };
  29679. /**
  29680. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29681. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29682. * This should be used together with the simplification to avoid disappearing triangles.
  29683. * Returns the Mesh.
  29684. * @param successCallback an optional success callback to be called after the optimization finished.
  29685. */
  29686. Mesh.prototype.optimizeIndices = function (successCallback) {
  29687. var _this = this;
  29688. var indices = this.getIndices();
  29689. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29690. if (!positions || !indices) {
  29691. return this;
  29692. }
  29693. var vectorPositions = new Array();
  29694. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29695. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29696. }
  29697. var dupes = new Array();
  29698. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29699. var realPos = vectorPositions.length - 1 - iteration;
  29700. var testedPosition = vectorPositions[realPos];
  29701. for (var j = 0; j < realPos; ++j) {
  29702. var againstPosition = vectorPositions[j];
  29703. if (testedPosition.equals(againstPosition)) {
  29704. dupes[realPos] = j;
  29705. break;
  29706. }
  29707. }
  29708. }, function () {
  29709. for (var i = 0; i < indices.length; ++i) {
  29710. indices[i] = dupes[indices[i]] || indices[i];
  29711. }
  29712. //indices are now reordered
  29713. var originalSubMeshes = _this.subMeshes.slice(0);
  29714. _this.setIndices(indices);
  29715. _this.subMeshes = originalSubMeshes;
  29716. if (successCallback) {
  29717. successCallback(_this);
  29718. }
  29719. });
  29720. return this;
  29721. };
  29722. Mesh.prototype.serialize = function (serializationObject) {
  29723. serializationObject.name = this.name;
  29724. serializationObject.id = this.id;
  29725. serializationObject.type = this.getClassName();
  29726. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29727. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29728. }
  29729. serializationObject.position = this.position.asArray();
  29730. if (this.rotationQuaternion) {
  29731. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29732. }
  29733. else if (this.rotation) {
  29734. serializationObject.rotation = this.rotation.asArray();
  29735. }
  29736. serializationObject.scaling = this.scaling.asArray();
  29737. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29738. serializationObject.isEnabled = this.isEnabled(false);
  29739. serializationObject.isVisible = this.isVisible;
  29740. serializationObject.infiniteDistance = this.infiniteDistance;
  29741. serializationObject.pickable = this.isPickable;
  29742. serializationObject.receiveShadows = this.receiveShadows;
  29743. serializationObject.billboardMode = this.billboardMode;
  29744. serializationObject.visibility = this.visibility;
  29745. serializationObject.checkCollisions = this.checkCollisions;
  29746. serializationObject.isBlocker = this.isBlocker;
  29747. // Parent
  29748. if (this.parent) {
  29749. serializationObject.parentId = this.parent.id;
  29750. }
  29751. // Geometry
  29752. serializationObject.isUnIndexed = this.isUnIndexed;
  29753. var geometry = this._geometry;
  29754. if (geometry) {
  29755. var geometryId = geometry.id;
  29756. serializationObject.geometryId = geometryId;
  29757. // SubMeshes
  29758. serializationObject.subMeshes = [];
  29759. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29760. var subMesh = this.subMeshes[subIndex];
  29761. serializationObject.subMeshes.push({
  29762. materialIndex: subMesh.materialIndex,
  29763. verticesStart: subMesh.verticesStart,
  29764. verticesCount: subMesh.verticesCount,
  29765. indexStart: subMesh.indexStart,
  29766. indexCount: subMesh.indexCount
  29767. });
  29768. }
  29769. }
  29770. // Material
  29771. if (this.material) {
  29772. serializationObject.materialId = this.material.id;
  29773. }
  29774. else {
  29775. this.material = null;
  29776. }
  29777. // Morph targets
  29778. if (this.morphTargetManager) {
  29779. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29780. }
  29781. // Skeleton
  29782. if (this.skeleton) {
  29783. serializationObject.skeletonId = this.skeleton.id;
  29784. }
  29785. // Physics
  29786. //TODO implement correct serialization for physics impostors.
  29787. var impostor = this.getPhysicsImpostor();
  29788. if (impostor) {
  29789. serializationObject.physicsMass = impostor.getParam("mass");
  29790. serializationObject.physicsFriction = impostor.getParam("friction");
  29791. serializationObject.physicsRestitution = impostor.getParam("mass");
  29792. serializationObject.physicsImpostor = impostor.type;
  29793. }
  29794. // Metadata
  29795. if (this.metadata) {
  29796. serializationObject.metadata = this.metadata;
  29797. }
  29798. // Instances
  29799. serializationObject.instances = [];
  29800. for (var index = 0; index < this.instances.length; index++) {
  29801. var instance = this.instances[index];
  29802. var serializationInstance = {
  29803. name: instance.name,
  29804. id: instance.id,
  29805. position: instance.position.asArray(),
  29806. scaling: instance.scaling.asArray()
  29807. };
  29808. if (instance.rotationQuaternion) {
  29809. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29810. }
  29811. else if (instance.rotation) {
  29812. serializationInstance.rotation = instance.rotation.asArray();
  29813. }
  29814. serializationObject.instances.push(serializationInstance);
  29815. // Animations
  29816. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29817. serializationInstance.ranges = instance.serializeAnimationRanges();
  29818. }
  29819. //
  29820. // Animations
  29821. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29822. serializationObject.ranges = this.serializeAnimationRanges();
  29823. // Layer mask
  29824. serializationObject.layerMask = this.layerMask;
  29825. // Alpha
  29826. serializationObject.alphaIndex = this.alphaIndex;
  29827. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29828. // Overlay
  29829. serializationObject.overlayAlpha = this.overlayAlpha;
  29830. serializationObject.overlayColor = this.overlayColor.asArray();
  29831. serializationObject.renderOverlay = this.renderOverlay;
  29832. // Fog
  29833. serializationObject.applyFog = this.applyFog;
  29834. // Action Manager
  29835. if (this.actionManager) {
  29836. serializationObject.actions = this.actionManager.serialize(this.name);
  29837. }
  29838. };
  29839. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29840. if (!this.geometry) {
  29841. return;
  29842. }
  29843. this._markSubMeshesAsAttributesDirty();
  29844. var morphTargetManager = this._morphTargetManager;
  29845. if (morphTargetManager && morphTargetManager.vertexCount) {
  29846. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29847. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29848. this.morphTargetManager = null;
  29849. return;
  29850. }
  29851. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29852. var morphTarget = morphTargetManager.getActiveTarget(index);
  29853. var positions = morphTarget.getPositions();
  29854. if (!positions) {
  29855. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29856. return;
  29857. }
  29858. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29859. var normals = morphTarget.getNormals();
  29860. if (normals) {
  29861. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29862. }
  29863. var tangents = morphTarget.getTangents();
  29864. if (tangents) {
  29865. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29866. }
  29867. }
  29868. }
  29869. else {
  29870. var index = 0;
  29871. // Positions
  29872. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29873. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29874. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29875. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29876. }
  29877. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29878. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29879. }
  29880. index++;
  29881. }
  29882. }
  29883. };
  29884. // Statics
  29885. /**
  29886. * Returns a new Mesh object parsed from the source provided.
  29887. * The parameter `parsedMesh` is the source.
  29888. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29889. */
  29890. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29891. var mesh;
  29892. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29893. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29894. }
  29895. else {
  29896. mesh = new Mesh(parsedMesh.name, scene);
  29897. }
  29898. mesh.id = parsedMesh.id;
  29899. if (BABYLON.Tags) {
  29900. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29901. }
  29902. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29903. if (parsedMesh.metadata !== undefined) {
  29904. mesh.metadata = parsedMesh.metadata;
  29905. }
  29906. if (parsedMesh.rotationQuaternion) {
  29907. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29908. }
  29909. else if (parsedMesh.rotation) {
  29910. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29911. }
  29912. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29913. if (parsedMesh.localMatrix) {
  29914. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29915. }
  29916. else if (parsedMesh.pivotMatrix) {
  29917. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29918. }
  29919. mesh.setEnabled(parsedMesh.isEnabled);
  29920. mesh.isVisible = parsedMesh.isVisible;
  29921. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29922. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29923. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29924. if (parsedMesh.applyFog !== undefined) {
  29925. mesh.applyFog = parsedMesh.applyFog;
  29926. }
  29927. if (parsedMesh.pickable !== undefined) {
  29928. mesh.isPickable = parsedMesh.pickable;
  29929. }
  29930. if (parsedMesh.alphaIndex !== undefined) {
  29931. mesh.alphaIndex = parsedMesh.alphaIndex;
  29932. }
  29933. mesh.receiveShadows = parsedMesh.receiveShadows;
  29934. mesh.billboardMode = parsedMesh.billboardMode;
  29935. if (parsedMesh.visibility !== undefined) {
  29936. mesh.visibility = parsedMesh.visibility;
  29937. }
  29938. mesh.checkCollisions = parsedMesh.checkCollisions;
  29939. if (parsedMesh.isBlocker !== undefined) {
  29940. mesh.isBlocker = parsedMesh.isBlocker;
  29941. }
  29942. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29943. // freezeWorldMatrix
  29944. if (parsedMesh.freezeWorldMatrix) {
  29945. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29946. }
  29947. // Parent
  29948. if (parsedMesh.parentId) {
  29949. mesh._waitingParentId = parsedMesh.parentId;
  29950. }
  29951. // Actions
  29952. if (parsedMesh.actions !== undefined) {
  29953. mesh._waitingActions = parsedMesh.actions;
  29954. }
  29955. // Overlay
  29956. if (parsedMesh.overlayAlpha !== undefined) {
  29957. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29958. }
  29959. if (parsedMesh.overlayColor !== undefined) {
  29960. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29961. }
  29962. if (parsedMesh.renderOverlay !== undefined) {
  29963. mesh.renderOverlay = parsedMesh.renderOverlay;
  29964. }
  29965. // Geometry
  29966. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29967. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29968. if (parsedMesh.delayLoadingFile) {
  29969. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29970. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29971. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29972. if (parsedMesh._binaryInfo) {
  29973. mesh._binaryInfo = parsedMesh._binaryInfo;
  29974. }
  29975. mesh._delayInfo = [];
  29976. if (parsedMesh.hasUVs) {
  29977. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29978. }
  29979. if (parsedMesh.hasUVs2) {
  29980. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29981. }
  29982. if (parsedMesh.hasUVs3) {
  29983. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29984. }
  29985. if (parsedMesh.hasUVs4) {
  29986. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29987. }
  29988. if (parsedMesh.hasUVs5) {
  29989. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29990. }
  29991. if (parsedMesh.hasUVs6) {
  29992. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29993. }
  29994. if (parsedMesh.hasColors) {
  29995. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29996. }
  29997. if (parsedMesh.hasMatricesIndices) {
  29998. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29999. }
  30000. if (parsedMesh.hasMatricesWeights) {
  30001. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  30002. }
  30003. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  30004. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  30005. mesh._checkDelayState();
  30006. }
  30007. }
  30008. else {
  30009. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  30010. }
  30011. // Material
  30012. if (parsedMesh.materialId) {
  30013. mesh.setMaterialByID(parsedMesh.materialId);
  30014. }
  30015. else {
  30016. mesh.material = null;
  30017. }
  30018. // Morph targets
  30019. if (parsedMesh.morphTargetManagerId > -1) {
  30020. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  30021. }
  30022. // Skeleton
  30023. if (parsedMesh.skeletonId > -1) {
  30024. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  30025. if (parsedMesh.numBoneInfluencers) {
  30026. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  30027. }
  30028. }
  30029. // Animations
  30030. if (parsedMesh.animations) {
  30031. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  30032. var parsedAnimation = parsedMesh.animations[animationIndex];
  30033. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30034. }
  30035. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  30036. }
  30037. if (parsedMesh.autoAnimate) {
  30038. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  30039. }
  30040. // Layer Mask
  30041. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  30042. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  30043. }
  30044. else {
  30045. mesh.layerMask = 0x0FFFFFFF;
  30046. }
  30047. // Physics
  30048. if (parsedMesh.physicsImpostor) {
  30049. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  30050. mass: parsedMesh.physicsMass,
  30051. friction: parsedMesh.physicsFriction,
  30052. restitution: parsedMesh.physicsRestitution
  30053. }, scene);
  30054. }
  30055. // Instances
  30056. if (parsedMesh.instances) {
  30057. for (var index = 0; index < parsedMesh.instances.length; index++) {
  30058. var parsedInstance = parsedMesh.instances[index];
  30059. var instance = mesh.createInstance(parsedInstance.name);
  30060. if (parsedInstance.id) {
  30061. instance.id = parsedInstance.id;
  30062. }
  30063. if (BABYLON.Tags) {
  30064. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  30065. }
  30066. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  30067. if (parsedInstance.parentId) {
  30068. instance._waitingParentId = parsedInstance.parentId;
  30069. }
  30070. if (parsedInstance.rotationQuaternion) {
  30071. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  30072. }
  30073. else if (parsedInstance.rotation) {
  30074. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  30075. }
  30076. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  30077. instance.checkCollisions = mesh.checkCollisions;
  30078. if (parsedMesh.animations) {
  30079. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  30080. parsedAnimation = parsedMesh.animations[animationIndex];
  30081. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30082. }
  30083. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  30084. }
  30085. }
  30086. }
  30087. return mesh;
  30088. };
  30089. /**
  30090. * Creates a ribbon mesh.
  30091. * Please consider using the same method from the MeshBuilder class instead.
  30092. * 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.
  30093. *
  30094. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  30095. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  30096. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  30097. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  30098. * 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.
  30099. * 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.
  30100. * 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
  30101. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30102. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30103. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30104. */
  30105. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  30106. if (closeArray === void 0) { closeArray = false; }
  30107. if (updatable === void 0) { updatable = false; }
  30108. return BABYLON.MeshBuilder.CreateRibbon(name, {
  30109. pathArray: pathArray,
  30110. closeArray: closeArray,
  30111. closePath: closePath,
  30112. offset: offset,
  30113. updatable: updatable,
  30114. sideOrientation: sideOrientation,
  30115. instance: instance
  30116. }, scene);
  30117. };
  30118. /**
  30119. * Creates a plane polygonal mesh. By default, this is a disc.
  30120. * Please consider using the same method from the MeshBuilder class instead.
  30121. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  30122. * 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.
  30123. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30124. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30125. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30126. */
  30127. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  30128. if (scene === void 0) { scene = null; }
  30129. var options = {
  30130. radius: radius,
  30131. tessellation: tessellation,
  30132. sideOrientation: sideOrientation,
  30133. updatable: updatable
  30134. };
  30135. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  30136. };
  30137. /**
  30138. * Creates a box mesh.
  30139. * Please consider using the same method from the MeshBuilder class instead.
  30140. * The parameter `size` sets the size (float) of each box side (default 1).
  30141. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30142. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30143. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30144. */
  30145. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  30146. if (scene === void 0) { scene = null; }
  30147. var options = {
  30148. size: size,
  30149. sideOrientation: sideOrientation,
  30150. updatable: updatable
  30151. };
  30152. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  30153. };
  30154. /**
  30155. * Creates a sphere mesh.
  30156. * Please consider using the same method from the MeshBuilder class instead.
  30157. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  30158. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  30159. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30160. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30161. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30162. */
  30163. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  30164. var options = {
  30165. segments: segments,
  30166. diameterX: diameter,
  30167. diameterY: diameter,
  30168. diameterZ: diameter,
  30169. sideOrientation: sideOrientation,
  30170. updatable: updatable
  30171. };
  30172. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  30173. };
  30174. /**
  30175. * Creates a cylinder or a cone mesh.
  30176. * Please consider using the same method from the MeshBuilder class instead.
  30177. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  30178. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  30179. * 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.
  30180. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  30181. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  30182. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30183. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30184. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30185. */
  30186. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  30187. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  30188. if (scene !== undefined) {
  30189. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  30190. updatable = scene;
  30191. }
  30192. scene = subdivisions;
  30193. subdivisions = 1;
  30194. }
  30195. var options = {
  30196. height: height,
  30197. diameterTop: diameterTop,
  30198. diameterBottom: diameterBottom,
  30199. tessellation: tessellation,
  30200. subdivisions: subdivisions,
  30201. sideOrientation: sideOrientation,
  30202. updatable: updatable
  30203. };
  30204. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  30205. };
  30206. // Torus (Code from SharpDX.org)
  30207. /**
  30208. * Creates a torus mesh.
  30209. * Please consider using the same method from the MeshBuilder class instead.
  30210. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  30211. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  30212. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  30213. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30214. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30215. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30216. */
  30217. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  30218. var options = {
  30219. diameter: diameter,
  30220. thickness: thickness,
  30221. tessellation: tessellation,
  30222. sideOrientation: sideOrientation,
  30223. updatable: updatable
  30224. };
  30225. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  30226. };
  30227. /**
  30228. * Creates a torus knot mesh.
  30229. * Please consider using the same method from the MeshBuilder class instead.
  30230. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  30231. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  30232. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  30233. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  30234. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30235. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30236. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30237. */
  30238. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  30239. var options = {
  30240. radius: radius,
  30241. tube: tube,
  30242. radialSegments: radialSegments,
  30243. tubularSegments: tubularSegments,
  30244. p: p,
  30245. q: q,
  30246. sideOrientation: sideOrientation,
  30247. updatable: updatable
  30248. };
  30249. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  30250. };
  30251. /**
  30252. * Creates a line mesh.
  30253. * Please consider using the same method from the MeshBuilder class instead.
  30254. * 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.
  30255. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30256. * The parameter `points` is an array successive Vector3.
  30257. * 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
  30258. * When updating an instance, remember that only point positions can change, not the number of points.
  30259. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30260. */
  30261. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  30262. if (scene === void 0) { scene = null; }
  30263. if (updatable === void 0) { updatable = false; }
  30264. if (instance === void 0) { instance = null; }
  30265. var options = {
  30266. points: points,
  30267. updatable: updatable,
  30268. instance: instance
  30269. };
  30270. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  30271. };
  30272. /**
  30273. * Creates a dashed line mesh.
  30274. * Please consider using the same method from the MeshBuilder class instead.
  30275. * 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.
  30276. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30277. * The parameter `points` is an array successive Vector3.
  30278. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  30279. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  30280. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  30281. * 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
  30282. * When updating an instance, remember that only point positions can change, not the number of points.
  30283. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30284. */
  30285. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  30286. if (scene === void 0) { scene = null; }
  30287. var options = {
  30288. points: points,
  30289. dashSize: dashSize,
  30290. gapSize: gapSize,
  30291. dashNb: dashNb,
  30292. updatable: updatable,
  30293. instance: instance
  30294. };
  30295. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  30296. };
  30297. /**
  30298. * Creates a polygon mesh.
  30299. * Please consider using the same method from the MeshBuilder class instead.
  30300. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  30301. * 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.
  30302. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30303. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30304. * Remember you can only change the shape positions, not their number when updating a polygon.
  30305. */
  30306. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  30307. var options = {
  30308. shape: shape,
  30309. holes: holes,
  30310. updatable: updatable,
  30311. sideOrientation: sideOrientation
  30312. };
  30313. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  30314. };
  30315. /**
  30316. * Creates an extruded polygon mesh, with depth in the Y direction.
  30317. * Please consider using the same method from the MeshBuilder class instead.
  30318. */
  30319. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  30320. var options = {
  30321. shape: shape,
  30322. holes: holes,
  30323. depth: depth,
  30324. updatable: updatable,
  30325. sideOrientation: sideOrientation
  30326. };
  30327. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  30328. };
  30329. /**
  30330. * Creates an extruded shape mesh.
  30331. * 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.
  30332. * Please consider using the same method from the MeshBuilder class instead.
  30333. *
  30334. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30335. * 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
  30336. * extruded along the Z axis.
  30337. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30338. * 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.
  30339. * The parameter `scale` (float, default 1) is the value to scale the shape.
  30340. * 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
  30341. * 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
  30342. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30343. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30344. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30345. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30346. */
  30347. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  30348. if (scene === void 0) { scene = null; }
  30349. var options = {
  30350. shape: shape,
  30351. path: path,
  30352. scale: scale,
  30353. rotation: rotation,
  30354. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30355. sideOrientation: sideOrientation,
  30356. instance: instance,
  30357. updatable: updatable
  30358. };
  30359. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  30360. };
  30361. /**
  30362. * Creates an custom extruded shape mesh.
  30363. * 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.
  30364. * Please consider using the same method from the MeshBuilder class instead.
  30365. *
  30366. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30367. * 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
  30368. * extruded along the Z axis.
  30369. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30370. * 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
  30371. * and the distance of this point from the begining of the path :
  30372. * ```javascript
  30373. * var rotationFunction = function(i, distance) {
  30374. * // do things
  30375. * return rotationValue; }
  30376. * ```
  30377. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  30378. * 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
  30379. * and the distance of this point from the begining of the path :
  30380. * ```javascript
  30381. * var scaleFunction = function(i, distance) {
  30382. * // do things
  30383. * return scaleValue;}
  30384. * ```
  30385. * It must returns a float value that will be the scale value applied to the shape on each path point.
  30386. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  30387. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  30388. * 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
  30389. * 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
  30390. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30391. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30392. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30393. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30394. */
  30395. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  30396. var options = {
  30397. shape: shape,
  30398. path: path,
  30399. scaleFunction: scaleFunction,
  30400. rotationFunction: rotationFunction,
  30401. ribbonCloseArray: ribbonCloseArray,
  30402. ribbonClosePath: ribbonClosePath,
  30403. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30404. sideOrientation: sideOrientation,
  30405. instance: instance,
  30406. updatable: updatable
  30407. };
  30408. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  30409. };
  30410. /**
  30411. * Creates lathe mesh.
  30412. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  30413. * Please consider using the same method from the MeshBuilder class instead.
  30414. * 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
  30415. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  30416. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  30417. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  30418. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30419. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30420. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30421. */
  30422. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  30423. var options = {
  30424. shape: shape,
  30425. radius: radius,
  30426. tessellation: tessellation,
  30427. sideOrientation: sideOrientation,
  30428. updatable: updatable
  30429. };
  30430. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  30431. };
  30432. /**
  30433. * Creates a plane mesh.
  30434. * Please consider using the same method from the MeshBuilder class instead.
  30435. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  30436. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30437. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30438. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30439. */
  30440. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  30441. var options = {
  30442. size: size,
  30443. width: size,
  30444. height: size,
  30445. sideOrientation: sideOrientation,
  30446. updatable: updatable
  30447. };
  30448. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  30449. };
  30450. /**
  30451. * Creates a ground mesh.
  30452. * Please consider using the same method from the MeshBuilder class instead.
  30453. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  30454. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  30455. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30456. */
  30457. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  30458. var options = {
  30459. width: width,
  30460. height: height,
  30461. subdivisions: subdivisions,
  30462. updatable: updatable
  30463. };
  30464. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  30465. };
  30466. /**
  30467. * Creates a tiled ground mesh.
  30468. * Please consider using the same method from the MeshBuilder class instead.
  30469. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  30470. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  30471. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  30472. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  30473. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  30474. * numbers of subdivisions on the ground width and height of each tile.
  30475. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30476. */
  30477. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  30478. var options = {
  30479. xmin: xmin,
  30480. zmin: zmin,
  30481. xmax: xmax,
  30482. zmax: zmax,
  30483. subdivisions: subdivisions,
  30484. precision: precision,
  30485. updatable: updatable
  30486. };
  30487. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  30488. };
  30489. /**
  30490. * Creates a ground mesh from a height map.
  30491. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  30492. * Please consider using the same method from the MeshBuilder class instead.
  30493. * The parameter `url` sets the URL of the height map image resource.
  30494. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  30495. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  30496. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  30497. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  30498. * 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).
  30499. * This function is passed the newly built mesh :
  30500. * ```javascript
  30501. * function(mesh) { // do things
  30502. * return; }
  30503. * ```
  30504. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30505. */
  30506. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  30507. var options = {
  30508. width: width,
  30509. height: height,
  30510. subdivisions: subdivisions,
  30511. minHeight: minHeight,
  30512. maxHeight: maxHeight,
  30513. updatable: updatable,
  30514. onReady: onReady
  30515. };
  30516. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  30517. };
  30518. /**
  30519. * Creates a tube mesh.
  30520. * 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.
  30521. * Please consider using the same method from the MeshBuilder class instead.
  30522. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  30523. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  30524. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  30525. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  30526. * 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.
  30527. * It must return a radius value (positive float) :
  30528. * ```javascript
  30529. * var radiusFunction = function(i, distance) {
  30530. * // do things
  30531. * return radius; }
  30532. * ```
  30533. * 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
  30534. * 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
  30535. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30536. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30537. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30538. */
  30539. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  30540. var options = {
  30541. path: path,
  30542. radius: radius,
  30543. tessellation: tessellation,
  30544. radiusFunction: radiusFunction,
  30545. arc: 1,
  30546. cap: cap,
  30547. updatable: updatable,
  30548. sideOrientation: sideOrientation,
  30549. instance: instance
  30550. };
  30551. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  30552. };
  30553. /**
  30554. * Creates a polyhedron mesh.
  30555. * Please consider using the same method from the MeshBuilder class instead.
  30556. * 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
  30557. * to choose the wanted type.
  30558. * The parameter `size` (positive float, default 1) sets the polygon size.
  30559. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  30560. * 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`.
  30561. * 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
  30562. * 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)`).
  30563. * 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
  30564. * 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.
  30565. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30566. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30567. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30568. */
  30569. Mesh.CreatePolyhedron = function (name, options, scene) {
  30570. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  30571. };
  30572. /**
  30573. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  30574. * Please consider using the same method from the MeshBuilder class instead.
  30575. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  30576. * 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`).
  30577. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  30578. * 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.
  30579. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30580. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30581. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30582. */
  30583. Mesh.CreateIcoSphere = function (name, options, scene) {
  30584. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  30585. };
  30586. /**
  30587. * Creates a decal mesh.
  30588. * Please consider using the same method from the MeshBuilder class instead.
  30589. * 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.
  30590. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  30591. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  30592. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  30593. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  30594. */
  30595. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  30596. var options = {
  30597. position: position,
  30598. normal: normal,
  30599. size: size,
  30600. angle: angle
  30601. };
  30602. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  30603. };
  30604. // Skeletons
  30605. /**
  30606. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30607. */
  30608. Mesh.prototype.setPositionsForCPUSkinning = function () {
  30609. if (!this._sourcePositions) {
  30610. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30611. if (!source) {
  30612. return this._sourcePositions;
  30613. }
  30614. this._sourcePositions = new Float32Array(source);
  30615. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30616. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30617. }
  30618. }
  30619. return this._sourcePositions;
  30620. };
  30621. /**
  30622. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30623. */
  30624. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30625. if (!this._sourceNormals) {
  30626. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30627. if (!source) {
  30628. return this._sourceNormals;
  30629. }
  30630. this._sourceNormals = new Float32Array(source);
  30631. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30632. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30633. }
  30634. }
  30635. return this._sourceNormals;
  30636. };
  30637. /**
  30638. * Updates the vertex buffer by applying transformation from the bones.
  30639. * Returns the Mesh.
  30640. *
  30641. * @param {skeleton} skeleton to apply
  30642. */
  30643. Mesh.prototype.applySkeleton = function (skeleton) {
  30644. if (!this.geometry) {
  30645. return this;
  30646. }
  30647. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30648. return this;
  30649. }
  30650. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30651. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30652. return this;
  30653. }
  30654. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30655. return this;
  30656. }
  30657. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30658. return this;
  30659. }
  30660. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30661. return this;
  30662. }
  30663. if (!this._sourcePositions) {
  30664. var submeshes = this.subMeshes.slice();
  30665. this.setPositionsForCPUSkinning();
  30666. this.subMeshes = submeshes;
  30667. }
  30668. if (!this._sourceNormals) {
  30669. this.setNormalsForCPUSkinning();
  30670. }
  30671. // positionsData checks for not being Float32Array will only pass at most once
  30672. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30673. if (!positionsData) {
  30674. return this;
  30675. }
  30676. if (!(positionsData instanceof Float32Array)) {
  30677. positionsData = new Float32Array(positionsData);
  30678. }
  30679. // normalsData checks for not being Float32Array will only pass at most once
  30680. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30681. if (!normalsData) {
  30682. return this;
  30683. }
  30684. if (!(normalsData instanceof Float32Array)) {
  30685. normalsData = new Float32Array(normalsData);
  30686. }
  30687. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30688. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30689. if (!matricesWeightsData || !matricesIndicesData) {
  30690. return this;
  30691. }
  30692. var needExtras = this.numBoneInfluencers > 4;
  30693. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30694. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30695. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30696. var tempVector3 = BABYLON.Vector3.Zero();
  30697. var finalMatrix = new BABYLON.Matrix();
  30698. var tempMatrix = new BABYLON.Matrix();
  30699. var matWeightIdx = 0;
  30700. var inf;
  30701. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30702. var weight;
  30703. for (inf = 0; inf < 4; inf++) {
  30704. weight = matricesWeightsData[matWeightIdx + inf];
  30705. if (weight > 0) {
  30706. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30707. finalMatrix.addToSelf(tempMatrix);
  30708. }
  30709. else
  30710. break;
  30711. }
  30712. if (needExtras) {
  30713. for (inf = 0; inf < 4; inf++) {
  30714. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30715. if (weight > 0) {
  30716. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30717. finalMatrix.addToSelf(tempMatrix);
  30718. }
  30719. else
  30720. break;
  30721. }
  30722. }
  30723. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30724. tempVector3.toArray(positionsData, index);
  30725. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30726. tempVector3.toArray(normalsData, index);
  30727. finalMatrix.reset();
  30728. }
  30729. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30730. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30731. return this;
  30732. };
  30733. // Tools
  30734. /**
  30735. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30736. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30737. */
  30738. Mesh.MinMax = function (meshes) {
  30739. var minVector = null;
  30740. var maxVector = null;
  30741. meshes.forEach(function (mesh, index, array) {
  30742. var boundingInfo = mesh.getBoundingInfo();
  30743. var boundingBox = boundingInfo.boundingBox;
  30744. if (!minVector || !maxVector) {
  30745. minVector = boundingBox.minimumWorld;
  30746. maxVector = boundingBox.maximumWorld;
  30747. }
  30748. else {
  30749. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30750. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30751. }
  30752. });
  30753. if (!minVector || !maxVector) {
  30754. return {
  30755. min: BABYLON.Vector3.Zero(),
  30756. max: BABYLON.Vector3.Zero()
  30757. };
  30758. }
  30759. return {
  30760. min: minVector,
  30761. max: maxVector
  30762. };
  30763. };
  30764. /**
  30765. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30766. */
  30767. Mesh.Center = function (meshesOrMinMaxVector) {
  30768. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30769. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30770. };
  30771. /**
  30772. * Merge the array of meshes into a single mesh for performance reasons.
  30773. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30774. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30775. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30776. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30777. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30778. */
  30779. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30780. if (disposeSource === void 0) { disposeSource = true; }
  30781. var index;
  30782. if (!allow32BitsIndices) {
  30783. var totalVertices = 0;
  30784. // Counting vertices
  30785. for (index = 0; index < meshes.length; index++) {
  30786. if (meshes[index]) {
  30787. totalVertices += meshes[index].getTotalVertices();
  30788. if (totalVertices > 65536) {
  30789. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30790. return null;
  30791. }
  30792. }
  30793. }
  30794. }
  30795. // Merge
  30796. var vertexData = null;
  30797. var otherVertexData;
  30798. var indiceArray = new Array();
  30799. var source = null;
  30800. for (index = 0; index < meshes.length; index++) {
  30801. if (meshes[index]) {
  30802. meshes[index].computeWorldMatrix(true);
  30803. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30804. otherVertexData.transform(meshes[index].getWorldMatrix());
  30805. if (vertexData) {
  30806. vertexData.merge(otherVertexData);
  30807. }
  30808. else {
  30809. vertexData = otherVertexData;
  30810. source = meshes[index];
  30811. }
  30812. if (subdivideWithSubMeshes) {
  30813. indiceArray.push(meshes[index].getTotalIndices());
  30814. }
  30815. }
  30816. }
  30817. source = source;
  30818. if (!meshSubclass) {
  30819. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30820. }
  30821. vertexData.applyToMesh(meshSubclass);
  30822. // Setting properties
  30823. meshSubclass.material = source.material;
  30824. meshSubclass.checkCollisions = source.checkCollisions;
  30825. // Cleaning
  30826. if (disposeSource) {
  30827. for (index = 0; index < meshes.length; index++) {
  30828. if (meshes[index]) {
  30829. meshes[index].dispose();
  30830. }
  30831. }
  30832. }
  30833. // Subdivide
  30834. if (subdivideWithSubMeshes) {
  30835. //-- Suppresions du submesh global
  30836. meshSubclass.releaseSubMeshes();
  30837. index = 0;
  30838. var offset = 0;
  30839. //-- aplique la subdivision en fonction du tableau d'indices
  30840. while (index < indiceArray.length) {
  30841. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30842. offset += indiceArray[index];
  30843. index++;
  30844. }
  30845. }
  30846. return meshSubclass;
  30847. };
  30848. // Consts
  30849. Mesh._FRONTSIDE = 0;
  30850. Mesh._BACKSIDE = 1;
  30851. Mesh._DOUBLESIDE = 2;
  30852. Mesh._DEFAULTSIDE = 0;
  30853. Mesh._NO_CAP = 0;
  30854. Mesh._CAP_START = 1;
  30855. Mesh._CAP_END = 2;
  30856. Mesh._CAP_ALL = 3;
  30857. return Mesh;
  30858. }(BABYLON.AbstractMesh));
  30859. BABYLON.Mesh = Mesh;
  30860. })(BABYLON || (BABYLON = {}));
  30861. //# sourceMappingURL=babylon.mesh.js.map
  30862. "use strict";
  30863. var BABYLON;
  30864. (function (BABYLON) {
  30865. var BaseSubMesh = /** @class */ (function () {
  30866. function BaseSubMesh() {
  30867. }
  30868. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30869. get: function () {
  30870. return this._materialEffect;
  30871. },
  30872. enumerable: true,
  30873. configurable: true
  30874. });
  30875. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30876. if (defines === void 0) { defines = null; }
  30877. if (this._materialEffect === effect) {
  30878. if (!effect) {
  30879. this._materialDefines = null;
  30880. }
  30881. return;
  30882. }
  30883. this._materialDefines = defines;
  30884. this._materialEffect = effect;
  30885. };
  30886. return BaseSubMesh;
  30887. }());
  30888. BABYLON.BaseSubMesh = BaseSubMesh;
  30889. var SubMesh = /** @class */ (function (_super) {
  30890. __extends(SubMesh, _super);
  30891. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30892. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30893. var _this = _super.call(this) || this;
  30894. _this.materialIndex = materialIndex;
  30895. _this.verticesStart = verticesStart;
  30896. _this.verticesCount = verticesCount;
  30897. _this.indexStart = indexStart;
  30898. _this.indexCount = indexCount;
  30899. _this._renderId = 0;
  30900. _this._mesh = mesh;
  30901. _this._renderingMesh = renderingMesh || mesh;
  30902. mesh.subMeshes.push(_this);
  30903. _this._trianglePlanes = [];
  30904. _this._id = mesh.subMeshes.length - 1;
  30905. if (createBoundingBox) {
  30906. _this.refreshBoundingInfo();
  30907. mesh.computeWorldMatrix(true);
  30908. }
  30909. return _this;
  30910. }
  30911. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30912. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30913. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30914. };
  30915. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30916. get: function () {
  30917. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30918. },
  30919. enumerable: true,
  30920. configurable: true
  30921. });
  30922. /**
  30923. * Returns the submesh BoudingInfo object.
  30924. */
  30925. SubMesh.prototype.getBoundingInfo = function () {
  30926. if (this.IsGlobal) {
  30927. return this._mesh.getBoundingInfo();
  30928. }
  30929. return this._boundingInfo;
  30930. };
  30931. /**
  30932. * Sets the submesh BoundingInfo.
  30933. * Return the SubMesh.
  30934. */
  30935. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30936. this._boundingInfo = boundingInfo;
  30937. return this;
  30938. };
  30939. /**
  30940. * Returns the mesh of the current submesh.
  30941. */
  30942. SubMesh.prototype.getMesh = function () {
  30943. return this._mesh;
  30944. };
  30945. /**
  30946. * Returns the rendering mesh of the submesh.
  30947. */
  30948. SubMesh.prototype.getRenderingMesh = function () {
  30949. return this._renderingMesh;
  30950. };
  30951. /**
  30952. * Returns the submesh material.
  30953. */
  30954. SubMesh.prototype.getMaterial = function () {
  30955. var rootMaterial = this._renderingMesh.material;
  30956. if (rootMaterial === null || rootMaterial === undefined) {
  30957. return this._mesh.getScene().defaultMaterial;
  30958. }
  30959. else if (rootMaterial.getSubMaterial) {
  30960. var multiMaterial = rootMaterial;
  30961. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30962. if (this._currentMaterial !== effectiveMaterial) {
  30963. this._currentMaterial = effectiveMaterial;
  30964. this._materialDefines = null;
  30965. }
  30966. return effectiveMaterial;
  30967. }
  30968. return rootMaterial;
  30969. };
  30970. // Methods
  30971. /**
  30972. * Sets a new updated BoundingInfo object to the submesh.
  30973. * Returns the SubMesh.
  30974. */
  30975. SubMesh.prototype.refreshBoundingInfo = function () {
  30976. this._lastColliderWorldVertices = null;
  30977. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30978. return this;
  30979. }
  30980. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30981. if (!data) {
  30982. this._boundingInfo = this._mesh.getBoundingInfo();
  30983. return this;
  30984. }
  30985. var indices = this._renderingMesh.getIndices();
  30986. var extend;
  30987. //is this the only submesh?
  30988. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30989. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30990. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30991. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30992. }
  30993. else {
  30994. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30995. }
  30996. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30997. return this;
  30998. };
  30999. SubMesh.prototype._checkCollision = function (collider) {
  31000. var boundingInfo = this._renderingMesh.getBoundingInfo();
  31001. return boundingInfo._checkCollision(collider);
  31002. };
  31003. /**
  31004. * Updates the submesh BoundingInfo.
  31005. * Returns the Submesh.
  31006. */
  31007. SubMesh.prototype.updateBoundingInfo = function (world) {
  31008. var boundingInfo = this.getBoundingInfo();
  31009. if (!boundingInfo) {
  31010. this.refreshBoundingInfo();
  31011. boundingInfo = this.getBoundingInfo();
  31012. }
  31013. boundingInfo.update(world);
  31014. return this;
  31015. };
  31016. /**
  31017. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  31018. * Boolean returned.
  31019. */
  31020. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  31021. var boundingInfo = this.getBoundingInfo();
  31022. if (!boundingInfo) {
  31023. return false;
  31024. }
  31025. return boundingInfo.isInFrustum(frustumPlanes);
  31026. };
  31027. /**
  31028. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  31029. * Boolean returned.
  31030. */
  31031. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  31032. var boundingInfo = this.getBoundingInfo();
  31033. if (!boundingInfo) {
  31034. return false;
  31035. }
  31036. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  31037. };
  31038. /**
  31039. * Renders the submesh.
  31040. * Returns it.
  31041. */
  31042. SubMesh.prototype.render = function (enableAlphaMode) {
  31043. this._renderingMesh.render(this, enableAlphaMode);
  31044. return this;
  31045. };
  31046. /**
  31047. * Returns a new Index Buffer.
  31048. * Type returned : WebGLBuffer.
  31049. */
  31050. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  31051. if (!this._linesIndexBuffer) {
  31052. var linesIndices = [];
  31053. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  31054. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  31055. }
  31056. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  31057. this.linesIndexCount = linesIndices.length;
  31058. }
  31059. return this._linesIndexBuffer;
  31060. };
  31061. /**
  31062. * True is the passed Ray intersects the submesh bounding box.
  31063. * Boolean returned.
  31064. */
  31065. SubMesh.prototype.canIntersects = function (ray) {
  31066. var boundingInfo = this.getBoundingInfo();
  31067. if (!boundingInfo) {
  31068. return false;
  31069. }
  31070. return ray.intersectsBox(boundingInfo.boundingBox);
  31071. };
  31072. /**
  31073. * Returns an object IntersectionInfo.
  31074. */
  31075. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  31076. var intersectInfo = null;
  31077. var material = this.getMaterial();
  31078. if (!material) {
  31079. return null;
  31080. }
  31081. switch (material.fillMode) {
  31082. case BABYLON.Material.PointListDrawMode:
  31083. case BABYLON.Material.LineListDrawMode:
  31084. case BABYLON.Material.LineLoopDrawMode:
  31085. case BABYLON.Material.LineStripDrawMode:
  31086. case BABYLON.Material.TriangleFanDrawMode:
  31087. case BABYLON.Material.TriangleStripDrawMode:
  31088. return null;
  31089. }
  31090. // LineMesh first as it's also a Mesh...
  31091. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  31092. var lineMesh = this._mesh;
  31093. // Line test
  31094. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  31095. var p0 = positions[indices[index]];
  31096. var p1 = positions[indices[index + 1]];
  31097. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  31098. if (length < 0) {
  31099. continue;
  31100. }
  31101. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  31102. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  31103. if (fastCheck) {
  31104. break;
  31105. }
  31106. }
  31107. }
  31108. }
  31109. else {
  31110. // Triangles test
  31111. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  31112. var p0 = positions[indices[index]];
  31113. var p1 = positions[indices[index + 1]];
  31114. var p2 = positions[indices[index + 2]];
  31115. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  31116. if (currentIntersectInfo) {
  31117. if (currentIntersectInfo.distance < 0) {
  31118. continue;
  31119. }
  31120. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  31121. intersectInfo = currentIntersectInfo;
  31122. intersectInfo.faceId = index / 3;
  31123. if (fastCheck) {
  31124. break;
  31125. }
  31126. }
  31127. }
  31128. }
  31129. }
  31130. return intersectInfo;
  31131. };
  31132. SubMesh.prototype._rebuild = function () {
  31133. if (this._linesIndexBuffer) {
  31134. this._linesIndexBuffer = null;
  31135. }
  31136. };
  31137. // Clone
  31138. /**
  31139. * Creates a new Submesh from the passed Mesh.
  31140. */
  31141. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  31142. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  31143. if (!this.IsGlobal) {
  31144. var boundingInfo = this.getBoundingInfo();
  31145. if (!boundingInfo) {
  31146. return result;
  31147. }
  31148. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  31149. }
  31150. return result;
  31151. };
  31152. // Dispose
  31153. /**
  31154. * Disposes the Submesh.
  31155. * Returns nothing.
  31156. */
  31157. SubMesh.prototype.dispose = function () {
  31158. if (this._linesIndexBuffer) {
  31159. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  31160. this._linesIndexBuffer = null;
  31161. }
  31162. // Remove from mesh
  31163. var index = this._mesh.subMeshes.indexOf(this);
  31164. this._mesh.subMeshes.splice(index, 1);
  31165. };
  31166. // Statics
  31167. /**
  31168. * Creates a new Submesh from the passed parameters :
  31169. * - materialIndex (integer) : the index of the main mesh material.
  31170. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  31171. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  31172. * - mesh (Mesh) : the main mesh to create the submesh from.
  31173. * - renderingMesh (optional Mesh) : rendering mesh.
  31174. */
  31175. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  31176. var minVertexIndex = Number.MAX_VALUE;
  31177. var maxVertexIndex = -Number.MAX_VALUE;
  31178. renderingMesh = (renderingMesh || mesh);
  31179. var indices = renderingMesh.getIndices();
  31180. for (var index = startIndex; index < startIndex + indexCount; index++) {
  31181. var vertexIndex = indices[index];
  31182. if (vertexIndex < minVertexIndex)
  31183. minVertexIndex = vertexIndex;
  31184. if (vertexIndex > maxVertexIndex)
  31185. maxVertexIndex = vertexIndex;
  31186. }
  31187. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  31188. };
  31189. return SubMesh;
  31190. }(BaseSubMesh));
  31191. BABYLON.SubMesh = SubMesh;
  31192. })(BABYLON || (BABYLON = {}));
  31193. //# sourceMappingURL=babylon.subMesh.js.map
  31194. "use strict";
  31195. var __assign = (this && this.__assign) || Object.assign || function(t) {
  31196. for (var s, i = 1, n = arguments.length; i < n; i++) {
  31197. s = arguments[i];
  31198. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  31199. t[p] = s[p];
  31200. }
  31201. return t;
  31202. };
  31203. var BABYLON;
  31204. (function (BABYLON) {
  31205. /**
  31206. * Manages the defines for the Material.
  31207. */
  31208. var MaterialDefines = /** @class */ (function () {
  31209. function MaterialDefines() {
  31210. this._isDirty = true;
  31211. this._areLightsDirty = true;
  31212. this._areAttributesDirty = true;
  31213. this._areTexturesDirty = true;
  31214. this._areFresnelDirty = true;
  31215. this._areMiscDirty = true;
  31216. this._areImageProcessingDirty = true;
  31217. this._normals = false;
  31218. this._uvs = false;
  31219. this._needNormals = false;
  31220. this._needUVs = false;
  31221. }
  31222. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  31223. /**
  31224. * Specifies if the material needs to be re-calculated.
  31225. */
  31226. get: function () {
  31227. return this._isDirty;
  31228. },
  31229. enumerable: true,
  31230. configurable: true
  31231. });
  31232. /**
  31233. * Marks the material to indicate that it has been re-calculated.
  31234. */
  31235. MaterialDefines.prototype.markAsProcessed = function () {
  31236. this._isDirty = false;
  31237. this._areAttributesDirty = false;
  31238. this._areTexturesDirty = false;
  31239. this._areFresnelDirty = false;
  31240. this._areLightsDirty = false;
  31241. this._areMiscDirty = false;
  31242. this._areImageProcessingDirty = false;
  31243. };
  31244. /**
  31245. * Marks the material to indicate that it needs to be re-calculated.
  31246. */
  31247. MaterialDefines.prototype.markAsUnprocessed = function () {
  31248. this._isDirty = true;
  31249. };
  31250. /**
  31251. * Marks the material to indicate all of its defines need to be re-calculated.
  31252. */
  31253. MaterialDefines.prototype.markAllAsDirty = function () {
  31254. this._areTexturesDirty = true;
  31255. this._areAttributesDirty = true;
  31256. this._areLightsDirty = true;
  31257. this._areFresnelDirty = true;
  31258. this._areMiscDirty = true;
  31259. this._areImageProcessingDirty = true;
  31260. this._isDirty = true;
  31261. };
  31262. /**
  31263. * Marks the material to indicate that image processing needs to be re-calculated.
  31264. */
  31265. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  31266. this._areImageProcessingDirty = true;
  31267. this._isDirty = true;
  31268. };
  31269. /**
  31270. * Marks the material to indicate the lights need to be re-calculated.
  31271. */
  31272. MaterialDefines.prototype.markAsLightDirty = function () {
  31273. this._areLightsDirty = true;
  31274. this._isDirty = true;
  31275. };
  31276. /**
  31277. * Marks the attribute state as changed.
  31278. */
  31279. MaterialDefines.prototype.markAsAttributesDirty = function () {
  31280. this._areAttributesDirty = true;
  31281. this._isDirty = true;
  31282. };
  31283. /**
  31284. * Marks the texture state as changed.
  31285. */
  31286. MaterialDefines.prototype.markAsTexturesDirty = function () {
  31287. this._areTexturesDirty = true;
  31288. this._isDirty = true;
  31289. };
  31290. /**
  31291. * Marks the fresnel state as changed.
  31292. */
  31293. MaterialDefines.prototype.markAsFresnelDirty = function () {
  31294. this._areFresnelDirty = true;
  31295. this._isDirty = true;
  31296. };
  31297. /**
  31298. * Marks the misc state as changed.
  31299. */
  31300. MaterialDefines.prototype.markAsMiscDirty = function () {
  31301. this._areMiscDirty = true;
  31302. this._isDirty = true;
  31303. };
  31304. /**
  31305. * Rebuilds the material defines.
  31306. */
  31307. MaterialDefines.prototype.rebuild = function () {
  31308. if (this._keys) {
  31309. delete this._keys;
  31310. }
  31311. this._keys = [];
  31312. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  31313. var key = _a[_i];
  31314. if (key[0] === "_") {
  31315. continue;
  31316. }
  31317. this._keys.push(key);
  31318. }
  31319. };
  31320. /**
  31321. * Specifies if two material defines are equal.
  31322. * @param other - A material define instance to compare to.
  31323. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  31324. */
  31325. MaterialDefines.prototype.isEqual = function (other) {
  31326. if (this._keys.length !== other._keys.length) {
  31327. return false;
  31328. }
  31329. for (var index = 0; index < this._keys.length; index++) {
  31330. var prop = this._keys[index];
  31331. if (this[prop] !== other[prop]) {
  31332. return false;
  31333. }
  31334. }
  31335. return true;
  31336. };
  31337. /**
  31338. * Clones this instance's defines to another instance.
  31339. * @param other - material defines to clone values to.
  31340. */
  31341. MaterialDefines.prototype.cloneTo = function (other) {
  31342. if (this._keys.length !== other._keys.length) {
  31343. other._keys = this._keys.slice(0);
  31344. }
  31345. for (var index = 0; index < this._keys.length; index++) {
  31346. var prop = this._keys[index];
  31347. other[prop] = this[prop];
  31348. }
  31349. };
  31350. /**
  31351. * Resets the material define values.
  31352. */
  31353. MaterialDefines.prototype.reset = function () {
  31354. for (var index = 0; index < this._keys.length; index++) {
  31355. var prop = this._keys[index];
  31356. var type = typeof this[prop];
  31357. switch (type) {
  31358. case "number":
  31359. this[prop] = 0;
  31360. break;
  31361. case "string":
  31362. this[prop] = "";
  31363. break;
  31364. default:
  31365. this[prop] = false;
  31366. break;
  31367. }
  31368. }
  31369. };
  31370. /**
  31371. * Converts the material define values to a string.
  31372. * @returns - String of material define information.
  31373. */
  31374. MaterialDefines.prototype.toString = function () {
  31375. var result = "";
  31376. for (var index = 0; index < this._keys.length; index++) {
  31377. var prop = this._keys[index];
  31378. var value = this[prop];
  31379. var type = typeof value;
  31380. switch (type) {
  31381. case "number":
  31382. case "string":
  31383. result += "#define " + prop + " " + value + "\n";
  31384. break;
  31385. default:
  31386. if (value) {
  31387. result += "#define " + prop + "\n";
  31388. }
  31389. break;
  31390. }
  31391. }
  31392. return result;
  31393. };
  31394. return MaterialDefines;
  31395. }());
  31396. BABYLON.MaterialDefines = MaterialDefines;
  31397. /**
  31398. * This offers the main features of a material in BJS.
  31399. */
  31400. var Material = /** @class */ (function () {
  31401. /**
  31402. * Creates a material instance.
  31403. * @param name - The name of the material.
  31404. * @param scene - The BJS scene to reference.
  31405. * @param doNotAdd - Specifies if the material should be added to the scene.
  31406. */
  31407. function Material(name, scene, doNotAdd) {
  31408. /**
  31409. * Specifies if the ready state should be checked on each call.
  31410. */
  31411. this.checkReadyOnEveryCall = false;
  31412. /**
  31413. * Specifies if the ready state should be checked once.
  31414. */
  31415. this.checkReadyOnlyOnce = false;
  31416. /**
  31417. * The state of the material.
  31418. */
  31419. this.state = "";
  31420. /**
  31421. * The alpha value of the material.
  31422. */
  31423. this._alpha = 1.0;
  31424. /**
  31425. * Specifies if back face culling is enabled.
  31426. */
  31427. this._backFaceCulling = true;
  31428. /**
  31429. * Specifies if the material should be serialized.
  31430. */
  31431. this.doNotSerialize = false;
  31432. /**
  31433. * Specifies if the effect should be stored on sub meshes.
  31434. */
  31435. this.storeEffectOnSubMeshes = false;
  31436. /**
  31437. * An event triggered when the material is disposed.
  31438. * @type {BABYLON.Observable}
  31439. */
  31440. this.onDisposeObservable = new BABYLON.Observable();
  31441. /**
  31442. * An event triggered when the material is bound.
  31443. * @type {BABYLON.Observable}
  31444. */
  31445. this.onBindObservable = new BABYLON.Observable();
  31446. /**
  31447. * An event triggered when the material is unbound.
  31448. * @type {BABYLON.Observable}
  31449. */
  31450. this.onUnBindObservable = new BABYLON.Observable();
  31451. /**
  31452. * Stores the value of the alpha mode.
  31453. */
  31454. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  31455. /**
  31456. * Stores the state of the need depth pre-pass value.
  31457. */
  31458. this._needDepthPrePass = false;
  31459. /**
  31460. * Specifies if depth writing should be disabled.
  31461. */
  31462. this.disableDepthWrite = false;
  31463. /**
  31464. * Specifies if depth writing should be forced.
  31465. */
  31466. this.forceDepthWrite = false;
  31467. /**
  31468. * Specifies if there should be a separate pass for culling.
  31469. */
  31470. this.separateCullingPass = false;
  31471. /**
  31472. * Stores the state specifing if fog should be enabled.
  31473. */
  31474. this._fogEnabled = true;
  31475. /**
  31476. * Stores the size of points.
  31477. */
  31478. this.pointSize = 1.0;
  31479. /**
  31480. * Stores the z offset value.
  31481. */
  31482. this.zOffset = 0;
  31483. /**
  31484. * Specifies if the material was previously ready.
  31485. */
  31486. this._wasPreviouslyReady = false;
  31487. /**
  31488. * Stores the fill mode state.
  31489. */
  31490. this._fillMode = Material.TriangleFillMode;
  31491. this.name = name;
  31492. this.id = name || BABYLON.Tools.RandomId();
  31493. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31494. if (this._scene.useRightHandedSystem) {
  31495. this.sideOrientation = Material.ClockWiseSideOrientation;
  31496. }
  31497. else {
  31498. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  31499. }
  31500. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  31501. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  31502. if (!doNotAdd) {
  31503. this._scene.materials.push(this);
  31504. }
  31505. }
  31506. Object.defineProperty(Material, "TriangleFillMode", {
  31507. /**
  31508. * Returns the triangle fill mode.
  31509. */
  31510. get: function () {
  31511. return Material._TriangleFillMode;
  31512. },
  31513. enumerable: true,
  31514. configurable: true
  31515. });
  31516. Object.defineProperty(Material, "WireFrameFillMode", {
  31517. /**
  31518. * Returns the wireframe mode.
  31519. */
  31520. get: function () {
  31521. return Material._WireFrameFillMode;
  31522. },
  31523. enumerable: true,
  31524. configurable: true
  31525. });
  31526. Object.defineProperty(Material, "PointFillMode", {
  31527. /**
  31528. * Returns the point fill mode.
  31529. */
  31530. get: function () {
  31531. return Material._PointFillMode;
  31532. },
  31533. enumerable: true,
  31534. configurable: true
  31535. });
  31536. Object.defineProperty(Material, "PointListDrawMode", {
  31537. /**
  31538. * Returns the point list draw mode.
  31539. */
  31540. get: function () {
  31541. return Material._PointListDrawMode;
  31542. },
  31543. enumerable: true,
  31544. configurable: true
  31545. });
  31546. Object.defineProperty(Material, "LineListDrawMode", {
  31547. /**
  31548. * Returns the line list draw mode.
  31549. */
  31550. get: function () {
  31551. return Material._LineListDrawMode;
  31552. },
  31553. enumerable: true,
  31554. configurable: true
  31555. });
  31556. Object.defineProperty(Material, "LineLoopDrawMode", {
  31557. /**
  31558. * Returns the line loop draw mode.
  31559. */
  31560. get: function () {
  31561. return Material._LineLoopDrawMode;
  31562. },
  31563. enumerable: true,
  31564. configurable: true
  31565. });
  31566. Object.defineProperty(Material, "LineStripDrawMode", {
  31567. /**
  31568. * Returns the line strip draw mode.
  31569. */
  31570. get: function () {
  31571. return Material._LineStripDrawMode;
  31572. },
  31573. enumerable: true,
  31574. configurable: true
  31575. });
  31576. Object.defineProperty(Material, "TriangleStripDrawMode", {
  31577. /**
  31578. * Returns the triangle strip draw mode.
  31579. */
  31580. get: function () {
  31581. return Material._TriangleStripDrawMode;
  31582. },
  31583. enumerable: true,
  31584. configurable: true
  31585. });
  31586. Object.defineProperty(Material, "TriangleFanDrawMode", {
  31587. /**
  31588. * Returns the triangle fan draw mode.
  31589. */
  31590. get: function () {
  31591. return Material._TriangleFanDrawMode;
  31592. },
  31593. enumerable: true,
  31594. configurable: true
  31595. });
  31596. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  31597. /**
  31598. * Returns the clock-wise side orientation.
  31599. */
  31600. get: function () {
  31601. return Material._ClockWiseSideOrientation;
  31602. },
  31603. enumerable: true,
  31604. configurable: true
  31605. });
  31606. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  31607. /**
  31608. * Returns the counter clock-wise side orientation.
  31609. */
  31610. get: function () {
  31611. return Material._CounterClockWiseSideOrientation;
  31612. },
  31613. enumerable: true,
  31614. configurable: true
  31615. });
  31616. Object.defineProperty(Material, "TextureDirtyFlag", {
  31617. /**
  31618. * Returns the dirty texture flag value.
  31619. */
  31620. get: function () {
  31621. return Material._TextureDirtyFlag;
  31622. },
  31623. enumerable: true,
  31624. configurable: true
  31625. });
  31626. Object.defineProperty(Material, "LightDirtyFlag", {
  31627. /**
  31628. * Returns the dirty light flag value.
  31629. */
  31630. get: function () {
  31631. return Material._LightDirtyFlag;
  31632. },
  31633. enumerable: true,
  31634. configurable: true
  31635. });
  31636. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31637. /**
  31638. * Returns the dirty fresnel flag value.
  31639. */
  31640. get: function () {
  31641. return Material._FresnelDirtyFlag;
  31642. },
  31643. enumerable: true,
  31644. configurable: true
  31645. });
  31646. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31647. /**
  31648. * Returns the dirty attributes flag value.
  31649. */
  31650. get: function () {
  31651. return Material._AttributesDirtyFlag;
  31652. },
  31653. enumerable: true,
  31654. configurable: true
  31655. });
  31656. Object.defineProperty(Material, "MiscDirtyFlag", {
  31657. /**
  31658. * Returns the dirty misc flag value.
  31659. */
  31660. get: function () {
  31661. return Material._MiscDirtyFlag;
  31662. },
  31663. enumerable: true,
  31664. configurable: true
  31665. });
  31666. Object.defineProperty(Material.prototype, "alpha", {
  31667. /**
  31668. * Gets the alpha value of the material.
  31669. */
  31670. get: function () {
  31671. return this._alpha;
  31672. },
  31673. /**
  31674. * Sets the alpha value of the material.
  31675. */
  31676. set: function (value) {
  31677. if (this._alpha === value) {
  31678. return;
  31679. }
  31680. this._alpha = value;
  31681. this.markAsDirty(Material.MiscDirtyFlag);
  31682. },
  31683. enumerable: true,
  31684. configurable: true
  31685. });
  31686. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31687. /**
  31688. * Gets the back-face culling state.
  31689. */
  31690. get: function () {
  31691. return this._backFaceCulling;
  31692. },
  31693. /**
  31694. * Sets the back-face culling state.
  31695. */
  31696. set: function (value) {
  31697. if (this._backFaceCulling === value) {
  31698. return;
  31699. }
  31700. this._backFaceCulling = value;
  31701. this.markAsDirty(Material.TextureDirtyFlag);
  31702. },
  31703. enumerable: true,
  31704. configurable: true
  31705. });
  31706. Object.defineProperty(Material.prototype, "onDispose", {
  31707. /**
  31708. * Called during a dispose event.
  31709. */
  31710. set: function (callback) {
  31711. if (this._onDisposeObserver) {
  31712. this.onDisposeObservable.remove(this._onDisposeObserver);
  31713. }
  31714. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31715. },
  31716. enumerable: true,
  31717. configurable: true
  31718. });
  31719. Object.defineProperty(Material.prototype, "onBind", {
  31720. /**
  31721. * Called during a bind event.
  31722. */
  31723. set: function (callback) {
  31724. if (this._onBindObserver) {
  31725. this.onBindObservable.remove(this._onBindObserver);
  31726. }
  31727. this._onBindObserver = this.onBindObservable.add(callback);
  31728. },
  31729. enumerable: true,
  31730. configurable: true
  31731. });
  31732. Object.defineProperty(Material.prototype, "alphaMode", {
  31733. /**
  31734. * Gets the value of the alpha mode.
  31735. */
  31736. get: function () {
  31737. return this._alphaMode;
  31738. },
  31739. /**
  31740. * Sets the value of the alpha mode.
  31741. */
  31742. set: function (value) {
  31743. if (this._alphaMode === value) {
  31744. return;
  31745. }
  31746. this._alphaMode = value;
  31747. this.markAsDirty(Material.TextureDirtyFlag);
  31748. },
  31749. enumerable: true,
  31750. configurable: true
  31751. });
  31752. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31753. /**
  31754. * Gets the depth pre-pass value.
  31755. */
  31756. get: function () {
  31757. return this._needDepthPrePass;
  31758. },
  31759. /**
  31760. * Sets the need depth pre-pass value.
  31761. */
  31762. set: function (value) {
  31763. if (this._needDepthPrePass === value) {
  31764. return;
  31765. }
  31766. this._needDepthPrePass = value;
  31767. if (this._needDepthPrePass) {
  31768. this.checkReadyOnEveryCall = true;
  31769. }
  31770. },
  31771. enumerable: true,
  31772. configurable: true
  31773. });
  31774. Object.defineProperty(Material.prototype, "fogEnabled", {
  31775. /**
  31776. * Gets the value of the fog enabled state.
  31777. */
  31778. get: function () {
  31779. return this._fogEnabled;
  31780. },
  31781. /**
  31782. * Sets the state for enabling fog.
  31783. */
  31784. set: function (value) {
  31785. if (this._fogEnabled === value) {
  31786. return;
  31787. }
  31788. this._fogEnabled = value;
  31789. this.markAsDirty(Material.MiscDirtyFlag);
  31790. },
  31791. enumerable: true,
  31792. configurable: true
  31793. });
  31794. Object.defineProperty(Material.prototype, "wireframe", {
  31795. /**
  31796. * Gets a value specifying if wireframe mode is enabled.
  31797. */
  31798. get: function () {
  31799. switch (this._fillMode) {
  31800. case Material.WireFrameFillMode:
  31801. case Material.LineListDrawMode:
  31802. case Material.LineLoopDrawMode:
  31803. case Material.LineStripDrawMode:
  31804. return true;
  31805. }
  31806. return this._scene.forceWireframe;
  31807. },
  31808. /**
  31809. * Sets the state of wireframe mode.
  31810. */
  31811. set: function (value) {
  31812. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31813. },
  31814. enumerable: true,
  31815. configurable: true
  31816. });
  31817. Object.defineProperty(Material.prototype, "pointsCloud", {
  31818. /**
  31819. * Gets the value specifying if point clouds are enabled.
  31820. */
  31821. get: function () {
  31822. switch (this._fillMode) {
  31823. case Material.PointFillMode:
  31824. case Material.PointListDrawMode:
  31825. return true;
  31826. }
  31827. return this._scene.forcePointsCloud;
  31828. },
  31829. /**
  31830. * Sets the state of point cloud mode.
  31831. */
  31832. set: function (value) {
  31833. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31834. },
  31835. enumerable: true,
  31836. configurable: true
  31837. });
  31838. Object.defineProperty(Material.prototype, "fillMode", {
  31839. /**
  31840. * Gets the material fill mode.
  31841. */
  31842. get: function () {
  31843. return this._fillMode;
  31844. },
  31845. /**
  31846. * Sets the material fill mode.
  31847. */
  31848. set: function (value) {
  31849. if (this._fillMode === value) {
  31850. return;
  31851. }
  31852. this._fillMode = value;
  31853. this.markAsDirty(Material.MiscDirtyFlag);
  31854. },
  31855. enumerable: true,
  31856. configurable: true
  31857. });
  31858. /**
  31859. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31860. * subclasses should override adding information pertainent to themselves.
  31861. * @returns - String with material information.
  31862. */
  31863. Material.prototype.toString = function (fullDetails) {
  31864. var ret = "Name: " + this.name;
  31865. if (fullDetails) {
  31866. }
  31867. return ret;
  31868. };
  31869. /**
  31870. * Gets the class name of the material.
  31871. * @returns - String with the class name of the material.
  31872. */
  31873. Material.prototype.getClassName = function () {
  31874. return "Material";
  31875. };
  31876. Object.defineProperty(Material.prototype, "isFrozen", {
  31877. /**
  31878. * Specifies if updates for the material been locked.
  31879. */
  31880. get: function () {
  31881. return this.checkReadyOnlyOnce;
  31882. },
  31883. enumerable: true,
  31884. configurable: true
  31885. });
  31886. /**
  31887. * Locks updates for the material.
  31888. */
  31889. Material.prototype.freeze = function () {
  31890. this.checkReadyOnlyOnce = true;
  31891. };
  31892. /**
  31893. * Unlocks updates for the material.
  31894. */
  31895. Material.prototype.unfreeze = function () {
  31896. this.checkReadyOnlyOnce = false;
  31897. };
  31898. /**
  31899. * Specifies if the material is ready to be used.
  31900. * @param mesh - BJS mesh.
  31901. * @param useInstances - Specifies if instances should be used.
  31902. * @returns - Boolean indicating if the material is ready to be used.
  31903. */
  31904. Material.prototype.isReady = function (mesh, useInstances) {
  31905. return true;
  31906. };
  31907. /**
  31908. * Specifies that the submesh is ready to be used.
  31909. * @param mesh - BJS mesh.
  31910. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31911. * @param useInstances - Specifies that instances should be used.
  31912. * @returns - boolean indicating that the submesh is ready or not.
  31913. */
  31914. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31915. return false;
  31916. };
  31917. /**
  31918. * Returns the material effect.
  31919. * @returns - Nullable material effect.
  31920. */
  31921. Material.prototype.getEffect = function () {
  31922. return this._effect;
  31923. };
  31924. /**
  31925. * Returns the BJS scene.
  31926. * @returns - BJS Scene.
  31927. */
  31928. Material.prototype.getScene = function () {
  31929. return this._scene;
  31930. };
  31931. /**
  31932. * Specifies if the material will require alpha blending
  31933. * @returns - Boolean specifying if alpha blending is needed.
  31934. */
  31935. Material.prototype.needAlphaBlending = function () {
  31936. return (this.alpha < 1.0);
  31937. };
  31938. /**
  31939. * Specifies if the mesh will require alpha blending.
  31940. * @param mesh - BJS mesh.
  31941. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31942. */
  31943. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31944. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31945. };
  31946. /**
  31947. * Specifies if this material should be rendered in alpha test mode.
  31948. * @returns - Boolean specifying if an alpha test is needed.
  31949. */
  31950. Material.prototype.needAlphaTesting = function () {
  31951. return false;
  31952. };
  31953. /**
  31954. * Gets the texture used for the alpha test.
  31955. * @returns - Nullable alpha test texture.
  31956. */
  31957. Material.prototype.getAlphaTestTexture = function () {
  31958. return null;
  31959. };
  31960. /**
  31961. * Marks the material to indicate that it needs to be re-calculated.
  31962. */
  31963. Material.prototype.markDirty = function () {
  31964. this._wasPreviouslyReady = false;
  31965. };
  31966. Material.prototype._preBind = function (effect, overrideOrientation) {
  31967. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31968. var engine = this._scene.getEngine();
  31969. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31970. var reverse = orientation === Material.ClockWiseSideOrientation;
  31971. engine.enableEffect(effect ? effect : this._effect);
  31972. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31973. return reverse;
  31974. };
  31975. /**
  31976. * Binds the material to the mesh.
  31977. * @param world - World transformation matrix.
  31978. * @param mesh - Mesh to bind the material to.
  31979. */
  31980. Material.prototype.bind = function (world, mesh) {
  31981. };
  31982. /**
  31983. * Binds the submesh to the material.
  31984. * @param world - World transformation matrix.
  31985. * @param mesh - Mesh containing the submesh.
  31986. * @param subMesh - Submesh to bind the material to.
  31987. */
  31988. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31989. };
  31990. /**
  31991. * Binds the world matrix to the material.
  31992. * @param world - World transformation matrix.
  31993. */
  31994. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31995. };
  31996. /**
  31997. * Binds the scene's uniform buffer to the effect.
  31998. * @param effect - Effect to bind to the scene uniform buffer.
  31999. * @param sceneUbo - Scene uniform buffer.
  32000. */
  32001. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  32002. sceneUbo.bindToEffect(effect, "Scene");
  32003. };
  32004. /**
  32005. * Binds the view matrix to the effect.
  32006. * @param effect - Effect to bind the view matrix to.
  32007. */
  32008. Material.prototype.bindView = function (effect) {
  32009. if (!this._useUBO) {
  32010. effect.setMatrix("view", this.getScene().getViewMatrix());
  32011. }
  32012. else {
  32013. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  32014. }
  32015. };
  32016. /**
  32017. * Binds the view projection matrix to the effect.
  32018. * @param effect - Effect to bind the view projection matrix to.
  32019. */
  32020. Material.prototype.bindViewProjection = function (effect) {
  32021. if (!this._useUBO) {
  32022. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  32023. }
  32024. else {
  32025. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  32026. }
  32027. };
  32028. /**
  32029. * Specifies if material alpha testing should be turned on for the mesh.
  32030. * @param mesh - BJS mesh.
  32031. */
  32032. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  32033. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  32034. };
  32035. /**
  32036. * Processes to execute after binding the material to a mesh.
  32037. * @param mesh - BJS mesh.
  32038. */
  32039. Material.prototype._afterBind = function (mesh) {
  32040. this._scene._cachedMaterial = this;
  32041. if (mesh) {
  32042. this._scene._cachedVisibility = mesh.visibility;
  32043. }
  32044. else {
  32045. this._scene._cachedVisibility = 1;
  32046. }
  32047. if (mesh) {
  32048. this.onBindObservable.notifyObservers(mesh);
  32049. }
  32050. if (this.disableDepthWrite) {
  32051. var engine = this._scene.getEngine();
  32052. this._cachedDepthWriteState = engine.getDepthWrite();
  32053. engine.setDepthWrite(false);
  32054. }
  32055. };
  32056. /**
  32057. * Unbinds the material from the mesh.
  32058. */
  32059. Material.prototype.unbind = function () {
  32060. this.onUnBindObservable.notifyObservers(this);
  32061. if (this.disableDepthWrite) {
  32062. var engine = this._scene.getEngine();
  32063. engine.setDepthWrite(this._cachedDepthWriteState);
  32064. }
  32065. };
  32066. /**
  32067. * Gets the active textures from the material.
  32068. * @returns - Array of textures.
  32069. */
  32070. Material.prototype.getActiveTextures = function () {
  32071. return [];
  32072. };
  32073. /**
  32074. * Specifies if the material uses a texture.
  32075. * @param texture - Texture to check against the material.
  32076. * @returns - Boolean specifying if the material uses the texture.
  32077. */
  32078. Material.prototype.hasTexture = function (texture) {
  32079. return false;
  32080. };
  32081. /**
  32082. * Makes a duplicate of the material, and gives it a new name.
  32083. * @param name - Name to call the duplicated material.
  32084. * @returns - Nullable cloned material
  32085. */
  32086. Material.prototype.clone = function (name) {
  32087. return null;
  32088. };
  32089. /**
  32090. * Gets the meshes bound to the material.
  32091. * @returns - Array of meshes bound to the material.
  32092. */
  32093. Material.prototype.getBindedMeshes = function () {
  32094. var result = new Array();
  32095. for (var index = 0; index < this._scene.meshes.length; index++) {
  32096. var mesh = this._scene.meshes[index];
  32097. if (mesh.material === this) {
  32098. result.push(mesh);
  32099. }
  32100. }
  32101. return result;
  32102. };
  32103. /**
  32104. * Force shader compilation
  32105. * @param mesh - BJS mesh.
  32106. * @param onCompiled - function to execute once the material is compiled.
  32107. * @param options - options to pass to this function.
  32108. */
  32109. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  32110. var _this = this;
  32111. var localOptions = __assign({ clipPlane: false }, options);
  32112. var subMesh = new BABYLON.BaseSubMesh();
  32113. var scene = this.getScene();
  32114. var checkReady = function () {
  32115. if (!_this._scene || !_this._scene.getEngine()) {
  32116. return;
  32117. }
  32118. if (subMesh._materialDefines) {
  32119. subMesh._materialDefines._renderId = -1;
  32120. }
  32121. var clipPlaneState = scene.clipPlane;
  32122. if (localOptions.clipPlane) {
  32123. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  32124. }
  32125. if (_this.storeEffectOnSubMeshes) {
  32126. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  32127. if (onCompiled) {
  32128. onCompiled(_this);
  32129. }
  32130. }
  32131. else {
  32132. setTimeout(checkReady, 16);
  32133. }
  32134. }
  32135. else {
  32136. if (_this.isReady(mesh)) {
  32137. if (onCompiled) {
  32138. onCompiled(_this);
  32139. }
  32140. }
  32141. else {
  32142. setTimeout(checkReady, 16);
  32143. }
  32144. }
  32145. if (localOptions.clipPlane) {
  32146. scene.clipPlane = clipPlaneState;
  32147. }
  32148. };
  32149. checkReady();
  32150. };
  32151. /**
  32152. * Force shader compilation.
  32153. * @param mesh The mesh that will use this material
  32154. * @param options Additional options for compiling the shaders
  32155. * @returns A promise that resolves when the compilation completes
  32156. */
  32157. Material.prototype.forceCompilationAsync = function (mesh, options) {
  32158. var _this = this;
  32159. return new Promise(function (resolve) {
  32160. _this.forceCompilation(mesh, function () {
  32161. resolve();
  32162. }, options);
  32163. });
  32164. };
  32165. /**
  32166. * Marks a define in the material to indicate that it needs to be re-computed.
  32167. * @param flag - Material define flag.
  32168. */
  32169. Material.prototype.markAsDirty = function (flag) {
  32170. if (flag & Material.TextureDirtyFlag) {
  32171. this._markAllSubMeshesAsTexturesDirty();
  32172. }
  32173. if (flag & Material.LightDirtyFlag) {
  32174. this._markAllSubMeshesAsLightsDirty();
  32175. }
  32176. if (flag & Material.FresnelDirtyFlag) {
  32177. this._markAllSubMeshesAsFresnelDirty();
  32178. }
  32179. if (flag & Material.AttributesDirtyFlag) {
  32180. this._markAllSubMeshesAsAttributesDirty();
  32181. }
  32182. if (flag & Material.MiscDirtyFlag) {
  32183. this._markAllSubMeshesAsMiscDirty();
  32184. }
  32185. this.getScene().resetCachedMaterial();
  32186. };
  32187. /**
  32188. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  32189. * @param func - function which checks material defines against the submeshes.
  32190. */
  32191. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  32192. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  32193. var mesh = _a[_i];
  32194. if (!mesh.subMeshes) {
  32195. continue;
  32196. }
  32197. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  32198. var subMesh = _c[_b];
  32199. if (subMesh.getMaterial() !== this) {
  32200. continue;
  32201. }
  32202. if (!subMesh._materialDefines) {
  32203. continue;
  32204. }
  32205. func(subMesh._materialDefines);
  32206. }
  32207. }
  32208. };
  32209. /**
  32210. * Indicates that image processing needs to be re-calculated for all submeshes.
  32211. */
  32212. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  32213. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  32214. };
  32215. /**
  32216. * Indicates that textures need to be re-calculated for all submeshes.
  32217. */
  32218. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  32219. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  32220. };
  32221. /**
  32222. * Indicates that fresnel needs to be re-calculated for all submeshes.
  32223. */
  32224. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  32225. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  32226. };
  32227. /**
  32228. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  32229. */
  32230. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  32231. this._markAllSubMeshesAsDirty(function (defines) {
  32232. defines.markAsFresnelDirty();
  32233. defines.markAsMiscDirty();
  32234. });
  32235. };
  32236. /**
  32237. * Indicates that lights need to be re-calculated for all submeshes.
  32238. */
  32239. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  32240. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  32241. };
  32242. /**
  32243. * Indicates that attributes need to be re-calculated for all submeshes.
  32244. */
  32245. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  32246. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  32247. };
  32248. /**
  32249. * Indicates that misc needs to be re-calculated for all submeshes.
  32250. */
  32251. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  32252. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  32253. };
  32254. /**
  32255. * Indicates that textures and misc need to be re-calculated for all submeshes.
  32256. */
  32257. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  32258. this._markAllSubMeshesAsDirty(function (defines) {
  32259. defines.markAsTexturesDirty();
  32260. defines.markAsMiscDirty();
  32261. });
  32262. };
  32263. /**
  32264. * Disposes the material.
  32265. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  32266. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  32267. */
  32268. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  32269. // Animations
  32270. this.getScene().stopAnimation(this);
  32271. this.getScene().freeProcessedMaterials();
  32272. // Remove from scene
  32273. var index = this._scene.materials.indexOf(this);
  32274. if (index >= 0) {
  32275. this._scene.materials.splice(index, 1);
  32276. }
  32277. // Remove from meshes
  32278. for (index = 0; index < this._scene.meshes.length; index++) {
  32279. var mesh = this._scene.meshes[index];
  32280. if (mesh.material === this) {
  32281. mesh.material = null;
  32282. if (mesh.geometry) {
  32283. var geometry = (mesh.geometry);
  32284. if (this.storeEffectOnSubMeshes) {
  32285. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  32286. var subMesh = _a[_i];
  32287. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  32288. if (forceDisposeEffect && subMesh._materialEffect) {
  32289. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  32290. }
  32291. }
  32292. }
  32293. else {
  32294. geometry._releaseVertexArrayObject(this._effect);
  32295. }
  32296. }
  32297. }
  32298. }
  32299. this._uniformBuffer.dispose();
  32300. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  32301. if (forceDisposeEffect && this._effect) {
  32302. if (!this.storeEffectOnSubMeshes) {
  32303. this._scene.getEngine()._releaseEffect(this._effect);
  32304. }
  32305. this._effect = null;
  32306. }
  32307. // Callback
  32308. this.onDisposeObservable.notifyObservers(this);
  32309. this.onDisposeObservable.clear();
  32310. this.onBindObservable.clear();
  32311. this.onUnBindObservable.clear();
  32312. };
  32313. /**
  32314. * Serializes this material.
  32315. * @returns - serialized material object.
  32316. */
  32317. Material.prototype.serialize = function () {
  32318. return BABYLON.SerializationHelper.Serialize(this);
  32319. };
  32320. /**
  32321. * Creates a MultiMaterial from parse MultiMaterial data.
  32322. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  32323. * @param scene - BJS scene.
  32324. * @returns - MultiMaterial.
  32325. */
  32326. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  32327. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  32328. multiMaterial.id = parsedMultiMaterial.id;
  32329. if (BABYLON.Tags) {
  32330. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  32331. }
  32332. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  32333. var subMatId = parsedMultiMaterial.materials[matIndex];
  32334. if (subMatId) {
  32335. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  32336. }
  32337. else {
  32338. multiMaterial.subMaterials.push(null);
  32339. }
  32340. }
  32341. return multiMaterial;
  32342. };
  32343. /**
  32344. * Creates a material from parsed material data.
  32345. * @param parsedMaterial - Parsed material data.
  32346. * @param scene - BJS scene.
  32347. * @param rootUrl - Root URL containing the material information.
  32348. * @returns - Parsed material.
  32349. */
  32350. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  32351. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  32352. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  32353. }
  32354. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  32355. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  32356. if (!BABYLON.LegacyPBRMaterial) {
  32357. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  32358. return;
  32359. }
  32360. }
  32361. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  32362. return materialType.Parse(parsedMaterial, scene, rootUrl);
  32363. ;
  32364. };
  32365. // Triangle views
  32366. Material._TriangleFillMode = 0;
  32367. Material._WireFrameFillMode = 1;
  32368. Material._PointFillMode = 2;
  32369. // Draw modes
  32370. Material._PointListDrawMode = 3;
  32371. Material._LineListDrawMode = 4;
  32372. Material._LineLoopDrawMode = 5;
  32373. Material._LineStripDrawMode = 6;
  32374. Material._TriangleStripDrawMode = 7;
  32375. Material._TriangleFanDrawMode = 8;
  32376. /**
  32377. * Stores the clock-wise side orientation.
  32378. */
  32379. Material._ClockWiseSideOrientation = 0;
  32380. /**
  32381. * Stores the counter clock-wise side orientation.
  32382. */
  32383. Material._CounterClockWiseSideOrientation = 1;
  32384. /**
  32385. * The dirty texture flag value.
  32386. */
  32387. Material._TextureDirtyFlag = 1;
  32388. /**
  32389. * The dirty light flag value.
  32390. */
  32391. Material._LightDirtyFlag = 2;
  32392. /**
  32393. * The dirty fresnel flag value.
  32394. */
  32395. Material._FresnelDirtyFlag = 4;
  32396. /**
  32397. * The dirty attribute flag value.
  32398. */
  32399. Material._AttributesDirtyFlag = 8;
  32400. /**
  32401. * The dirty misc flag value.
  32402. */
  32403. Material._MiscDirtyFlag = 16;
  32404. __decorate([
  32405. BABYLON.serialize()
  32406. ], Material.prototype, "id", void 0);
  32407. __decorate([
  32408. BABYLON.serialize()
  32409. ], Material.prototype, "name", void 0);
  32410. __decorate([
  32411. BABYLON.serialize()
  32412. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  32413. __decorate([
  32414. BABYLON.serialize()
  32415. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  32416. __decorate([
  32417. BABYLON.serialize()
  32418. ], Material.prototype, "state", void 0);
  32419. __decorate([
  32420. BABYLON.serialize("alpha")
  32421. ], Material.prototype, "_alpha", void 0);
  32422. __decorate([
  32423. BABYLON.serialize("backFaceCulling")
  32424. ], Material.prototype, "_backFaceCulling", void 0);
  32425. __decorate([
  32426. BABYLON.serialize()
  32427. ], Material.prototype, "sideOrientation", void 0);
  32428. __decorate([
  32429. BABYLON.serialize("alphaMode")
  32430. ], Material.prototype, "_alphaMode", void 0);
  32431. __decorate([
  32432. BABYLON.serialize()
  32433. ], Material.prototype, "_needDepthPrePass", void 0);
  32434. __decorate([
  32435. BABYLON.serialize()
  32436. ], Material.prototype, "disableDepthWrite", void 0);
  32437. __decorate([
  32438. BABYLON.serialize()
  32439. ], Material.prototype, "forceDepthWrite", void 0);
  32440. __decorate([
  32441. BABYLON.serialize()
  32442. ], Material.prototype, "separateCullingPass", void 0);
  32443. __decorate([
  32444. BABYLON.serialize("fogEnabled")
  32445. ], Material.prototype, "_fogEnabled", void 0);
  32446. __decorate([
  32447. BABYLON.serialize()
  32448. ], Material.prototype, "pointSize", void 0);
  32449. __decorate([
  32450. BABYLON.serialize()
  32451. ], Material.prototype, "zOffset", void 0);
  32452. __decorate([
  32453. BABYLON.serialize()
  32454. ], Material.prototype, "wireframe", null);
  32455. __decorate([
  32456. BABYLON.serialize()
  32457. ], Material.prototype, "pointsCloud", null);
  32458. __decorate([
  32459. BABYLON.serialize()
  32460. ], Material.prototype, "fillMode", null);
  32461. return Material;
  32462. }());
  32463. BABYLON.Material = Material;
  32464. })(BABYLON || (BABYLON = {}));
  32465. //# sourceMappingURL=babylon.material.js.map
  32466. "use strict";
  32467. var BABYLON;
  32468. (function (BABYLON) {
  32469. var UniformBuffer = /** @class */ (function () {
  32470. /**
  32471. * Uniform buffer objects.
  32472. *
  32473. * Handles blocks of uniform on the GPU.
  32474. *
  32475. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  32476. *
  32477. * For more information, please refer to :
  32478. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  32479. */
  32480. function UniformBuffer(engine, data, dynamic) {
  32481. this._engine = engine;
  32482. this._noUBO = !engine.supportsUniformBuffers;
  32483. this._dynamic = dynamic;
  32484. this._data = data || [];
  32485. this._uniformLocations = {};
  32486. this._uniformSizes = {};
  32487. this._uniformLocationPointer = 0;
  32488. this._needSync = false;
  32489. if (this._noUBO) {
  32490. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  32491. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  32492. this.updateFloat = this._updateFloatForEffect;
  32493. this.updateFloat2 = this._updateFloat2ForEffect;
  32494. this.updateFloat3 = this._updateFloat3ForEffect;
  32495. this.updateFloat4 = this._updateFloat4ForEffect;
  32496. this.updateMatrix = this._updateMatrixForEffect;
  32497. this.updateVector3 = this._updateVector3ForEffect;
  32498. this.updateVector4 = this._updateVector4ForEffect;
  32499. this.updateColor3 = this._updateColor3ForEffect;
  32500. this.updateColor4 = this._updateColor4ForEffect;
  32501. }
  32502. else {
  32503. this._engine._uniformBuffers.push(this);
  32504. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  32505. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  32506. this.updateFloat = this._updateFloatForUniform;
  32507. this.updateFloat2 = this._updateFloat2ForUniform;
  32508. this.updateFloat3 = this._updateFloat3ForUniform;
  32509. this.updateFloat4 = this._updateFloat4ForUniform;
  32510. this.updateMatrix = this._updateMatrixForUniform;
  32511. this.updateVector3 = this._updateVector3ForUniform;
  32512. this.updateVector4 = this._updateVector4ForUniform;
  32513. this.updateColor3 = this._updateColor3ForUniform;
  32514. this.updateColor4 = this._updateColor4ForUniform;
  32515. }
  32516. }
  32517. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  32518. // Properties
  32519. /**
  32520. * Indicates if the buffer is using the WebGL2 UBO implementation,
  32521. * or just falling back on setUniformXXX calls.
  32522. */
  32523. get: function () {
  32524. return !this._noUBO;
  32525. },
  32526. enumerable: true,
  32527. configurable: true
  32528. });
  32529. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  32530. /**
  32531. * Indicates if the WebGL underlying uniform buffer is in sync
  32532. * with the javascript cache data.
  32533. */
  32534. get: function () {
  32535. return !this._needSync;
  32536. },
  32537. enumerable: true,
  32538. configurable: true
  32539. });
  32540. /**
  32541. * Indicates if the WebGL underlying uniform buffer is dynamic.
  32542. * Also, a dynamic UniformBuffer will disable cache verification and always
  32543. * update the underlying WebGL uniform buffer to the GPU.
  32544. */
  32545. UniformBuffer.prototype.isDynamic = function () {
  32546. return this._dynamic !== undefined;
  32547. };
  32548. /**
  32549. * The data cache on JS side.
  32550. */
  32551. UniformBuffer.prototype.getData = function () {
  32552. return this._bufferData;
  32553. };
  32554. /**
  32555. * The underlying WebGL Uniform buffer.
  32556. */
  32557. UniformBuffer.prototype.getBuffer = function () {
  32558. return this._buffer;
  32559. };
  32560. /**
  32561. * std140 layout specifies how to align data within an UBO structure.
  32562. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  32563. * for specs.
  32564. */
  32565. UniformBuffer.prototype._fillAlignment = function (size) {
  32566. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  32567. // and 4x4 matrices
  32568. // TODO : change if other types are used
  32569. var alignment;
  32570. if (size <= 2) {
  32571. alignment = size;
  32572. }
  32573. else {
  32574. alignment = 4;
  32575. }
  32576. if ((this._uniformLocationPointer % alignment) !== 0) {
  32577. var oldPointer = this._uniformLocationPointer;
  32578. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  32579. var diff = this._uniformLocationPointer - oldPointer;
  32580. for (var i = 0; i < diff; i++) {
  32581. this._data.push(0);
  32582. }
  32583. }
  32584. };
  32585. /**
  32586. * Adds an uniform in the buffer.
  32587. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  32588. * for the layout to be correct !
  32589. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32590. * @param {number|number[]} size Data size, or data directly.
  32591. */
  32592. UniformBuffer.prototype.addUniform = function (name, size) {
  32593. if (this._noUBO) {
  32594. return;
  32595. }
  32596. if (this._uniformLocations[name] !== undefined) {
  32597. // Already existing uniform
  32598. return;
  32599. }
  32600. // This function must be called in the order of the shader layout !
  32601. // size can be the size of the uniform, or data directly
  32602. var data;
  32603. if (size instanceof Array) {
  32604. data = size;
  32605. size = data.length;
  32606. }
  32607. else {
  32608. size = size;
  32609. data = [];
  32610. // Fill with zeros
  32611. for (var i = 0; i < size; i++) {
  32612. data.push(0);
  32613. }
  32614. }
  32615. this._fillAlignment(size);
  32616. this._uniformSizes[name] = size;
  32617. this._uniformLocations[name] = this._uniformLocationPointer;
  32618. this._uniformLocationPointer += size;
  32619. for (var i = 0; i < size; i++) {
  32620. this._data.push(data[i]);
  32621. }
  32622. this._needSync = true;
  32623. };
  32624. /**
  32625. * Wrapper for addUniform.
  32626. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32627. * @param {Matrix} mat A 4x4 matrix.
  32628. */
  32629. UniformBuffer.prototype.addMatrix = function (name, mat) {
  32630. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  32631. };
  32632. /**
  32633. * Wrapper for addUniform.
  32634. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32635. * @param {number} x
  32636. * @param {number} y
  32637. */
  32638. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  32639. var temp = [x, y];
  32640. this.addUniform(name, temp);
  32641. };
  32642. /**
  32643. * Wrapper for addUniform.
  32644. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32645. * @param {number} x
  32646. * @param {number} y
  32647. * @param {number} z
  32648. */
  32649. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  32650. var temp = [x, y, z];
  32651. this.addUniform(name, temp);
  32652. };
  32653. /**
  32654. * Wrapper for addUniform.
  32655. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32656. * @param {Color3} color
  32657. */
  32658. UniformBuffer.prototype.addColor3 = function (name, color) {
  32659. var temp = new Array();
  32660. color.toArray(temp);
  32661. this.addUniform(name, temp);
  32662. };
  32663. /**
  32664. * Wrapper for addUniform.
  32665. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32666. * @param {Color3} color
  32667. * @param {number} alpha
  32668. */
  32669. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32670. var temp = new Array();
  32671. color.toArray(temp);
  32672. temp.push(alpha);
  32673. this.addUniform(name, temp);
  32674. };
  32675. /**
  32676. * Wrapper for addUniform.
  32677. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32678. * @param {Vector3} vector
  32679. */
  32680. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32681. var temp = new Array();
  32682. vector.toArray(temp);
  32683. this.addUniform(name, temp);
  32684. };
  32685. /**
  32686. * Wrapper for addUniform.
  32687. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32688. */
  32689. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32690. this.addUniform(name, 12);
  32691. };
  32692. /**
  32693. * Wrapper for addUniform.
  32694. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32695. */
  32696. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32697. this.addUniform(name, 8);
  32698. };
  32699. /**
  32700. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32701. */
  32702. UniformBuffer.prototype.create = function () {
  32703. if (this._noUBO) {
  32704. return;
  32705. }
  32706. if (this._buffer) {
  32707. return; // nothing to do
  32708. }
  32709. // See spec, alignment must be filled as a vec4
  32710. this._fillAlignment(4);
  32711. this._bufferData = new Float32Array(this._data);
  32712. this._rebuild();
  32713. this._needSync = true;
  32714. };
  32715. UniformBuffer.prototype._rebuild = function () {
  32716. if (this._noUBO) {
  32717. return;
  32718. }
  32719. if (this._dynamic) {
  32720. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32721. }
  32722. else {
  32723. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32724. }
  32725. };
  32726. /**
  32727. * Updates the WebGL Uniform Buffer on the GPU.
  32728. * If the `dynamic` flag is set to true, no cache comparison is done.
  32729. * Otherwise, the buffer will be updated only if the cache differs.
  32730. */
  32731. UniformBuffer.prototype.update = function () {
  32732. if (!this._buffer) {
  32733. this.create();
  32734. return;
  32735. }
  32736. if (!this._dynamic && !this._needSync) {
  32737. return;
  32738. }
  32739. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32740. this._needSync = false;
  32741. };
  32742. /**
  32743. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32744. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32745. * @param {number[]|Float32Array} data Flattened data
  32746. * @param {number} size Size of the data.
  32747. */
  32748. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32749. var location = this._uniformLocations[uniformName];
  32750. if (location === undefined) {
  32751. if (this._buffer) {
  32752. // Cannot add an uniform if the buffer is already created
  32753. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32754. return;
  32755. }
  32756. this.addUniform(uniformName, size);
  32757. location = this._uniformLocations[uniformName];
  32758. }
  32759. if (!this._buffer) {
  32760. this.create();
  32761. }
  32762. if (!this._dynamic) {
  32763. // Cache for static uniform buffers
  32764. var changed = false;
  32765. for (var i = 0; i < size; i++) {
  32766. if (this._bufferData[location + i] !== data[i]) {
  32767. changed = true;
  32768. this._bufferData[location + i] = data[i];
  32769. }
  32770. }
  32771. this._needSync = this._needSync || changed;
  32772. }
  32773. else {
  32774. // No cache for dynamic
  32775. for (var i = 0; i < size; i++) {
  32776. this._bufferData[location + i] = data[i];
  32777. }
  32778. }
  32779. };
  32780. // Update methods
  32781. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32782. // To match std140, matrix must be realigned
  32783. for (var i = 0; i < 3; i++) {
  32784. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32785. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32786. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32787. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32788. }
  32789. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32790. };
  32791. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32792. this._currentEffect.setMatrix3x3(name, matrix);
  32793. };
  32794. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32795. this._currentEffect.setMatrix2x2(name, matrix);
  32796. };
  32797. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32798. // To match std140, matrix must be realigned
  32799. for (var i = 0; i < 2; i++) {
  32800. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32801. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32802. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32803. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32804. }
  32805. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32806. };
  32807. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32808. this._currentEffect.setFloat(name, x);
  32809. };
  32810. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32811. UniformBuffer._tempBuffer[0] = x;
  32812. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32813. };
  32814. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32815. if (suffix === void 0) { suffix = ""; }
  32816. this._currentEffect.setFloat2(name + suffix, x, y);
  32817. };
  32818. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32819. if (suffix === void 0) { suffix = ""; }
  32820. UniformBuffer._tempBuffer[0] = x;
  32821. UniformBuffer._tempBuffer[1] = y;
  32822. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32823. };
  32824. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32825. if (suffix === void 0) { suffix = ""; }
  32826. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32827. };
  32828. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32829. if (suffix === void 0) { suffix = ""; }
  32830. UniformBuffer._tempBuffer[0] = x;
  32831. UniformBuffer._tempBuffer[1] = y;
  32832. UniformBuffer._tempBuffer[2] = z;
  32833. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32834. };
  32835. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32836. if (suffix === void 0) { suffix = ""; }
  32837. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32838. };
  32839. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32840. if (suffix === void 0) { suffix = ""; }
  32841. UniformBuffer._tempBuffer[0] = x;
  32842. UniformBuffer._tempBuffer[1] = y;
  32843. UniformBuffer._tempBuffer[2] = z;
  32844. UniformBuffer._tempBuffer[3] = w;
  32845. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32846. };
  32847. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32848. this._currentEffect.setMatrix(name, mat);
  32849. };
  32850. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32851. this.updateUniform(name, mat.toArray(), 16);
  32852. };
  32853. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32854. this._currentEffect.setVector3(name, vector);
  32855. };
  32856. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32857. vector.toArray(UniformBuffer._tempBuffer);
  32858. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32859. };
  32860. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32861. this._currentEffect.setVector4(name, vector);
  32862. };
  32863. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32864. vector.toArray(UniformBuffer._tempBuffer);
  32865. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32866. };
  32867. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32868. if (suffix === void 0) { suffix = ""; }
  32869. this._currentEffect.setColor3(name + suffix, color);
  32870. };
  32871. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32872. if (suffix === void 0) { suffix = ""; }
  32873. color.toArray(UniformBuffer._tempBuffer);
  32874. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32875. };
  32876. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32877. if (suffix === void 0) { suffix = ""; }
  32878. this._currentEffect.setColor4(name + suffix, color, alpha);
  32879. };
  32880. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32881. if (suffix === void 0) { suffix = ""; }
  32882. color.toArray(UniformBuffer._tempBuffer);
  32883. UniformBuffer._tempBuffer[3] = alpha;
  32884. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32885. };
  32886. /**
  32887. * Sets a sampler uniform on the effect.
  32888. * @param {string} name Name of the sampler.
  32889. * @param {Texture} texture
  32890. */
  32891. UniformBuffer.prototype.setTexture = function (name, texture) {
  32892. this._currentEffect.setTexture(name, texture);
  32893. };
  32894. /**
  32895. * Directly updates the value of the uniform in the cache AND on the GPU.
  32896. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32897. * @param {number[]|Float32Array} data Flattened data
  32898. */
  32899. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32900. this.updateUniform(uniformName, data, data.length);
  32901. this.update();
  32902. };
  32903. /**
  32904. * Binds this uniform buffer to an effect.
  32905. * @param {Effect} effect
  32906. * @param {string} name Name of the uniform block in the shader.
  32907. */
  32908. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32909. this._currentEffect = effect;
  32910. if (this._noUBO || !this._buffer) {
  32911. return;
  32912. }
  32913. effect.bindUniformBuffer(this._buffer, name);
  32914. };
  32915. /**
  32916. * Disposes the uniform buffer.
  32917. */
  32918. UniformBuffer.prototype.dispose = function () {
  32919. if (this._noUBO) {
  32920. return;
  32921. }
  32922. var index = this._engine._uniformBuffers.indexOf(this);
  32923. if (index !== -1) {
  32924. this._engine._uniformBuffers.splice(index, 1);
  32925. }
  32926. if (!this._buffer) {
  32927. return;
  32928. }
  32929. if (this._engine._releaseBuffer(this._buffer)) {
  32930. this._buffer = null;
  32931. }
  32932. };
  32933. // Pool for avoiding memory leaks
  32934. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32935. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32936. return UniformBuffer;
  32937. }());
  32938. BABYLON.UniformBuffer = UniformBuffer;
  32939. })(BABYLON || (BABYLON = {}));
  32940. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32941. "use strict";
  32942. var BABYLON;
  32943. (function (BABYLON) {
  32944. var VertexData = /** @class */ (function () {
  32945. function VertexData() {
  32946. }
  32947. VertexData.prototype.set = function (data, kind) {
  32948. switch (kind) {
  32949. case BABYLON.VertexBuffer.PositionKind:
  32950. this.positions = data;
  32951. break;
  32952. case BABYLON.VertexBuffer.NormalKind:
  32953. this.normals = data;
  32954. break;
  32955. case BABYLON.VertexBuffer.TangentKind:
  32956. this.tangents = data;
  32957. break;
  32958. case BABYLON.VertexBuffer.UVKind:
  32959. this.uvs = data;
  32960. break;
  32961. case BABYLON.VertexBuffer.UV2Kind:
  32962. this.uvs2 = data;
  32963. break;
  32964. case BABYLON.VertexBuffer.UV3Kind:
  32965. this.uvs3 = data;
  32966. break;
  32967. case BABYLON.VertexBuffer.UV4Kind:
  32968. this.uvs4 = data;
  32969. break;
  32970. case BABYLON.VertexBuffer.UV5Kind:
  32971. this.uvs5 = data;
  32972. break;
  32973. case BABYLON.VertexBuffer.UV6Kind:
  32974. this.uvs6 = data;
  32975. break;
  32976. case BABYLON.VertexBuffer.ColorKind:
  32977. this.colors = data;
  32978. break;
  32979. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32980. this.matricesIndices = data;
  32981. break;
  32982. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32983. this.matricesWeights = data;
  32984. break;
  32985. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32986. this.matricesIndicesExtra = data;
  32987. break;
  32988. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32989. this.matricesWeightsExtra = data;
  32990. break;
  32991. }
  32992. };
  32993. /**
  32994. * Associates the vertexData to the passed Mesh.
  32995. * Sets it as updatable or not (default `false`).
  32996. * Returns the VertexData.
  32997. */
  32998. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32999. this._applyTo(mesh, updatable);
  33000. return this;
  33001. };
  33002. /**
  33003. * Associates the vertexData to the passed Geometry.
  33004. * Sets it as updatable or not (default `false`).
  33005. * Returns the VertexData.
  33006. */
  33007. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  33008. this._applyTo(geometry, updatable);
  33009. return this;
  33010. };
  33011. /**
  33012. * Updates the associated mesh.
  33013. * Returns the VertexData.
  33014. */
  33015. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  33016. this._update(mesh);
  33017. return this;
  33018. };
  33019. /**
  33020. * Updates the associated geometry.
  33021. * Returns the VertexData.
  33022. */
  33023. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  33024. this._update(geometry);
  33025. return this;
  33026. };
  33027. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  33028. if (updatable === void 0) { updatable = false; }
  33029. if (this.positions) {
  33030. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  33031. }
  33032. if (this.normals) {
  33033. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  33034. }
  33035. if (this.tangents) {
  33036. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  33037. }
  33038. if (this.uvs) {
  33039. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  33040. }
  33041. if (this.uvs2) {
  33042. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  33043. }
  33044. if (this.uvs3) {
  33045. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  33046. }
  33047. if (this.uvs4) {
  33048. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  33049. }
  33050. if (this.uvs5) {
  33051. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  33052. }
  33053. if (this.uvs6) {
  33054. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  33055. }
  33056. if (this.colors) {
  33057. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  33058. }
  33059. if (this.matricesIndices) {
  33060. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  33061. }
  33062. if (this.matricesWeights) {
  33063. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  33064. }
  33065. if (this.matricesIndicesExtra) {
  33066. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  33067. }
  33068. if (this.matricesWeightsExtra) {
  33069. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  33070. }
  33071. if (this.indices) {
  33072. meshOrGeometry.setIndices(this.indices, null, updatable);
  33073. }
  33074. return this;
  33075. };
  33076. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  33077. if (this.positions) {
  33078. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  33079. }
  33080. if (this.normals) {
  33081. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  33082. }
  33083. if (this.tangents) {
  33084. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  33085. }
  33086. if (this.uvs) {
  33087. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  33088. }
  33089. if (this.uvs2) {
  33090. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  33091. }
  33092. if (this.uvs3) {
  33093. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  33094. }
  33095. if (this.uvs4) {
  33096. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  33097. }
  33098. if (this.uvs5) {
  33099. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  33100. }
  33101. if (this.uvs6) {
  33102. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  33103. }
  33104. if (this.colors) {
  33105. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  33106. }
  33107. if (this.matricesIndices) {
  33108. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  33109. }
  33110. if (this.matricesWeights) {
  33111. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  33112. }
  33113. if (this.matricesIndicesExtra) {
  33114. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  33115. }
  33116. if (this.matricesWeightsExtra) {
  33117. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  33118. }
  33119. if (this.indices) {
  33120. meshOrGeometry.setIndices(this.indices, null);
  33121. }
  33122. return this;
  33123. };
  33124. /**
  33125. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  33126. * Returns the VertexData.
  33127. */
  33128. VertexData.prototype.transform = function (matrix) {
  33129. var transformed = BABYLON.Vector3.Zero();
  33130. var index;
  33131. if (this.positions) {
  33132. var position = BABYLON.Vector3.Zero();
  33133. for (index = 0; index < this.positions.length; index += 3) {
  33134. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  33135. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  33136. this.positions[index] = transformed.x;
  33137. this.positions[index + 1] = transformed.y;
  33138. this.positions[index + 2] = transformed.z;
  33139. }
  33140. }
  33141. if (this.normals) {
  33142. var normal = BABYLON.Vector3.Zero();
  33143. for (index = 0; index < this.normals.length; index += 3) {
  33144. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  33145. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  33146. this.normals[index] = transformed.x;
  33147. this.normals[index + 1] = transformed.y;
  33148. this.normals[index + 2] = transformed.z;
  33149. }
  33150. }
  33151. if (this.tangents) {
  33152. var tangent = BABYLON.Vector4.Zero();
  33153. var tangentTransformed = BABYLON.Vector4.Zero();
  33154. for (index = 0; index < this.tangents.length; index += 4) {
  33155. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  33156. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  33157. this.tangents[index] = tangentTransformed.x;
  33158. this.tangents[index + 1] = tangentTransformed.y;
  33159. this.tangents[index + 2] = tangentTransformed.z;
  33160. this.tangents[index + 3] = tangentTransformed.w;
  33161. }
  33162. }
  33163. return this;
  33164. };
  33165. /**
  33166. * Merges the passed VertexData into the current one.
  33167. * Returns the modified VertexData.
  33168. */
  33169. VertexData.prototype.merge = function (other) {
  33170. this._validate();
  33171. other._validate();
  33172. if (!this.normals !== !other.normals ||
  33173. !this.tangents !== !other.tangents ||
  33174. !this.uvs !== !other.uvs ||
  33175. !this.uvs2 !== !other.uvs2 ||
  33176. !this.uvs3 !== !other.uvs3 ||
  33177. !this.uvs4 !== !other.uvs4 ||
  33178. !this.uvs5 !== !other.uvs5 ||
  33179. !this.uvs6 !== !other.uvs6 ||
  33180. !this.colors !== !other.colors ||
  33181. !this.matricesIndices !== !other.matricesIndices ||
  33182. !this.matricesWeights !== !other.matricesWeights ||
  33183. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  33184. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  33185. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  33186. }
  33187. if (other.indices) {
  33188. if (!this.indices) {
  33189. this.indices = [];
  33190. }
  33191. var offset = this.positions ? this.positions.length / 3 : 0;
  33192. for (var index = 0; index < other.indices.length; index++) {
  33193. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  33194. this.indices.push(other.indices[index] + offset);
  33195. }
  33196. }
  33197. this.positions = this._mergeElement(this.positions, other.positions);
  33198. this.normals = this._mergeElement(this.normals, other.normals);
  33199. this.tangents = this._mergeElement(this.tangents, other.tangents);
  33200. this.uvs = this._mergeElement(this.uvs, other.uvs);
  33201. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  33202. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  33203. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  33204. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  33205. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  33206. this.colors = this._mergeElement(this.colors, other.colors);
  33207. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  33208. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  33209. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  33210. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  33211. return this;
  33212. };
  33213. VertexData.prototype._mergeElement = function (source, other) {
  33214. if (!source) {
  33215. return other;
  33216. }
  33217. if (!other) {
  33218. return source;
  33219. }
  33220. var len = other.length + source.length;
  33221. var isSrcTypedArray = source instanceof Float32Array;
  33222. var isOthTypedArray = other instanceof Float32Array;
  33223. // use non-loop method when the source is Float32Array
  33224. if (isSrcTypedArray) {
  33225. var ret32 = new Float32Array(len);
  33226. ret32.set(source);
  33227. ret32.set(other, source.length);
  33228. return ret32;
  33229. // source is number[], when other is also use concat
  33230. }
  33231. else if (!isOthTypedArray) {
  33232. return source.concat(other);
  33233. // source is a number[], but other is a Float32Array, loop required
  33234. }
  33235. else {
  33236. var ret = source.slice(0); // copy source to a separate array
  33237. for (var i = 0, len = other.length; i < len; i++) {
  33238. ret.push(other[i]);
  33239. }
  33240. return ret;
  33241. }
  33242. };
  33243. VertexData.prototype._validate = function () {
  33244. if (!this.positions) {
  33245. throw new Error("Positions are required");
  33246. }
  33247. var getElementCount = function (kind, values) {
  33248. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  33249. if ((values.length % stride) !== 0) {
  33250. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  33251. }
  33252. return values.length / stride;
  33253. };
  33254. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  33255. var validateElementCount = function (kind, values) {
  33256. var elementCount = getElementCount(kind, values);
  33257. if (elementCount !== positionsElementCount) {
  33258. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  33259. }
  33260. };
  33261. if (this.normals)
  33262. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  33263. if (this.tangents)
  33264. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  33265. if (this.uvs)
  33266. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  33267. if (this.uvs2)
  33268. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  33269. if (this.uvs3)
  33270. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  33271. if (this.uvs4)
  33272. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  33273. if (this.uvs5)
  33274. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  33275. if (this.uvs6)
  33276. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  33277. if (this.colors)
  33278. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  33279. if (this.matricesIndices)
  33280. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  33281. if (this.matricesWeights)
  33282. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  33283. if (this.matricesIndicesExtra)
  33284. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  33285. if (this.matricesWeightsExtra)
  33286. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  33287. };
  33288. /**
  33289. * Serializes the VertexData.
  33290. * Returns a serialized object.
  33291. */
  33292. VertexData.prototype.serialize = function () {
  33293. var serializationObject = this.serialize();
  33294. if (this.positions) {
  33295. serializationObject.positions = this.positions;
  33296. }
  33297. if (this.normals) {
  33298. serializationObject.normals = this.normals;
  33299. }
  33300. if (this.tangents) {
  33301. serializationObject.tangents = this.tangents;
  33302. }
  33303. if (this.uvs) {
  33304. serializationObject.uvs = this.uvs;
  33305. }
  33306. if (this.uvs2) {
  33307. serializationObject.uvs2 = this.uvs2;
  33308. }
  33309. if (this.uvs3) {
  33310. serializationObject.uvs3 = this.uvs3;
  33311. }
  33312. if (this.uvs4) {
  33313. serializationObject.uvs4 = this.uvs4;
  33314. }
  33315. if (this.uvs5) {
  33316. serializationObject.uvs5 = this.uvs5;
  33317. }
  33318. if (this.uvs6) {
  33319. serializationObject.uvs6 = this.uvs6;
  33320. }
  33321. if (this.colors) {
  33322. serializationObject.colors = this.colors;
  33323. }
  33324. if (this.matricesIndices) {
  33325. serializationObject.matricesIndices = this.matricesIndices;
  33326. serializationObject.matricesIndices._isExpanded = true;
  33327. }
  33328. if (this.matricesWeights) {
  33329. serializationObject.matricesWeights = this.matricesWeights;
  33330. }
  33331. if (this.matricesIndicesExtra) {
  33332. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  33333. serializationObject.matricesIndicesExtra._isExpanded = true;
  33334. }
  33335. if (this.matricesWeightsExtra) {
  33336. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  33337. }
  33338. serializationObject.indices = this.indices;
  33339. return serializationObject;
  33340. };
  33341. // Statics
  33342. /**
  33343. * Returns the object VertexData associated to the passed mesh.
  33344. */
  33345. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  33346. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  33347. };
  33348. /**
  33349. * Returns the object VertexData associated to the passed geometry.
  33350. */
  33351. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  33352. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  33353. };
  33354. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  33355. var result = new VertexData();
  33356. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33357. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  33358. }
  33359. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33360. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  33361. }
  33362. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  33363. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  33364. }
  33365. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33366. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  33367. }
  33368. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33369. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  33370. }
  33371. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33372. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  33373. }
  33374. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33375. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  33376. }
  33377. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33378. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  33379. }
  33380. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33381. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  33382. }
  33383. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33384. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  33385. }
  33386. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33387. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  33388. }
  33389. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33390. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  33391. }
  33392. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  33393. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  33394. }
  33395. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33396. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  33397. }
  33398. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  33399. return result;
  33400. };
  33401. /**
  33402. * Creates the vertexData of the Ribbon.
  33403. */
  33404. VertexData.CreateRibbon = function (options) {
  33405. var pathArray = options.pathArray;
  33406. var closeArray = options.closeArray || false;
  33407. var closePath = options.closePath || false;
  33408. var invertUV = options.invertUV || false;
  33409. var defaultOffset = Math.floor(pathArray[0].length / 2);
  33410. var offset = options.offset || defaultOffset;
  33411. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  33412. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33413. var customUV = options.uvs;
  33414. var customColors = options.colors;
  33415. var positions = [];
  33416. var indices = [];
  33417. var normals = [];
  33418. var uvs = [];
  33419. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  33420. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  33421. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  33422. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  33423. var minlg; // minimal length among all paths from pathArray
  33424. var lg = []; // array of path lengths : nb of vertex per path
  33425. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  33426. var p; // path iterator
  33427. var i; // point iterator
  33428. var j; // point iterator
  33429. // if single path in pathArray
  33430. if (pathArray.length < 2) {
  33431. var ar1 = [];
  33432. var ar2 = [];
  33433. for (i = 0; i < pathArray[0].length - offset; i++) {
  33434. ar1.push(pathArray[0][i]);
  33435. ar2.push(pathArray[0][i + offset]);
  33436. }
  33437. pathArray = [ar1, ar2];
  33438. }
  33439. // positions and horizontal distances (u)
  33440. var idc = 0;
  33441. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  33442. var path;
  33443. var l;
  33444. minlg = pathArray[0].length;
  33445. var vectlg;
  33446. var dist;
  33447. for (p = 0; p < pathArray.length; p++) {
  33448. uTotalDistance[p] = 0;
  33449. us[p] = [0];
  33450. path = pathArray[p];
  33451. l = path.length;
  33452. minlg = (minlg < l) ? minlg : l;
  33453. j = 0;
  33454. while (j < l) {
  33455. positions.push(path[j].x, path[j].y, path[j].z);
  33456. if (j > 0) {
  33457. vectlg = path[j].subtract(path[j - 1]).length();
  33458. dist = vectlg + uTotalDistance[p];
  33459. us[p].push(dist);
  33460. uTotalDistance[p] = dist;
  33461. }
  33462. j++;
  33463. }
  33464. if (closePath) {
  33465. j--;
  33466. positions.push(path[0].x, path[0].y, path[0].z);
  33467. vectlg = path[j].subtract(path[0]).length();
  33468. dist = vectlg + uTotalDistance[p];
  33469. us[p].push(dist);
  33470. uTotalDistance[p] = dist;
  33471. }
  33472. lg[p] = l + closePathCorr;
  33473. idx[p] = idc;
  33474. idc += (l + closePathCorr);
  33475. }
  33476. // vertical distances (v)
  33477. var path1;
  33478. var path2;
  33479. var vertex1 = null;
  33480. var vertex2 = null;
  33481. for (i = 0; i < minlg + closePathCorr; i++) {
  33482. vTotalDistance[i] = 0;
  33483. vs[i] = [0];
  33484. for (p = 0; p < pathArray.length - 1; p++) {
  33485. path1 = pathArray[p];
  33486. path2 = pathArray[p + 1];
  33487. if (i === minlg) {
  33488. vertex1 = path1[0];
  33489. vertex2 = path2[0];
  33490. }
  33491. else {
  33492. vertex1 = path1[i];
  33493. vertex2 = path2[i];
  33494. }
  33495. vectlg = vertex2.subtract(vertex1).length();
  33496. dist = vectlg + vTotalDistance[i];
  33497. vs[i].push(dist);
  33498. vTotalDistance[i] = dist;
  33499. }
  33500. if (closeArray && vertex2 && vertex1) {
  33501. path1 = pathArray[p];
  33502. path2 = pathArray[0];
  33503. if (i === minlg) {
  33504. vertex2 = path2[0];
  33505. }
  33506. vectlg = vertex2.subtract(vertex1).length();
  33507. dist = vectlg + vTotalDistance[i];
  33508. vTotalDistance[i] = dist;
  33509. }
  33510. }
  33511. // uvs
  33512. var u;
  33513. var v;
  33514. if (customUV) {
  33515. for (p = 0; p < customUV.length; p++) {
  33516. uvs.push(customUV[p].x, customUV[p].y);
  33517. }
  33518. }
  33519. else {
  33520. for (p = 0; p < pathArray.length; p++) {
  33521. for (i = 0; i < minlg + closePathCorr; i++) {
  33522. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  33523. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  33524. if (invertUV) {
  33525. uvs.push(v, u);
  33526. }
  33527. else {
  33528. uvs.push(u, v);
  33529. }
  33530. }
  33531. }
  33532. }
  33533. // indices
  33534. p = 0; // path index
  33535. var pi = 0; // positions array index
  33536. var l1 = lg[p] - 1; // path1 length
  33537. var l2 = lg[p + 1] - 1; // path2 length
  33538. var min = (l1 < l2) ? l1 : l2; // current path stop index
  33539. var shft = idx[1] - idx[0]; // shift
  33540. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  33541. while (pi <= min && p < path1nb) {
  33542. // 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
  33543. indices.push(pi, pi + shft, pi + 1);
  33544. indices.push(pi + shft + 1, pi + 1, pi + shft);
  33545. pi += 1;
  33546. if (pi === min) {
  33547. p++;
  33548. if (p === lg.length - 1) {
  33549. shft = idx[0] - idx[p];
  33550. l1 = lg[p] - 1;
  33551. l2 = lg[0] - 1;
  33552. }
  33553. else {
  33554. shft = idx[p + 1] - idx[p];
  33555. l1 = lg[p] - 1;
  33556. l2 = lg[p + 1] - 1;
  33557. }
  33558. pi = idx[p];
  33559. min = (l1 < l2) ? l1 + pi : l2 + pi;
  33560. }
  33561. }
  33562. // normals
  33563. VertexData.ComputeNormals(positions, indices, normals);
  33564. if (closePath) {
  33565. var indexFirst = 0;
  33566. var indexLast = 0;
  33567. for (p = 0; p < pathArray.length; p++) {
  33568. indexFirst = idx[p] * 3;
  33569. if (p + 1 < pathArray.length) {
  33570. indexLast = (idx[p + 1] - 1) * 3;
  33571. }
  33572. else {
  33573. indexLast = normals.length - 3;
  33574. }
  33575. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33576. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33577. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33578. normals[indexLast] = normals[indexFirst];
  33579. normals[indexLast + 1] = normals[indexFirst + 1];
  33580. normals[indexLast + 2] = normals[indexFirst + 2];
  33581. }
  33582. }
  33583. // sides
  33584. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33585. // Colors
  33586. var colors = null;
  33587. if (customColors) {
  33588. colors = new Float32Array(customColors.length * 4);
  33589. for (var c = 0; c < customColors.length; c++) {
  33590. colors[c * 4] = customColors[c].r;
  33591. colors[c * 4 + 1] = customColors[c].g;
  33592. colors[c * 4 + 2] = customColors[c].b;
  33593. colors[c * 4 + 3] = customColors[c].a;
  33594. }
  33595. }
  33596. // Result
  33597. var vertexData = new VertexData();
  33598. var positions32 = new Float32Array(positions);
  33599. var normals32 = new Float32Array(normals);
  33600. var uvs32 = new Float32Array(uvs);
  33601. vertexData.indices = indices;
  33602. vertexData.positions = positions32;
  33603. vertexData.normals = normals32;
  33604. vertexData.uvs = uvs32;
  33605. if (colors) {
  33606. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  33607. }
  33608. if (closePath) {
  33609. vertexData._idx = idx;
  33610. }
  33611. return vertexData;
  33612. };
  33613. /**
  33614. * Creates the VertexData of the Box.
  33615. */
  33616. VertexData.CreateBox = function (options) {
  33617. var normalsSource = [
  33618. new BABYLON.Vector3(0, 0, 1),
  33619. new BABYLON.Vector3(0, 0, -1),
  33620. new BABYLON.Vector3(1, 0, 0),
  33621. new BABYLON.Vector3(-1, 0, 0),
  33622. new BABYLON.Vector3(0, 1, 0),
  33623. new BABYLON.Vector3(0, -1, 0)
  33624. ];
  33625. var indices = [];
  33626. var positions = [];
  33627. var normals = [];
  33628. var uvs = [];
  33629. var width = options.width || options.size || 1;
  33630. var height = options.height || options.size || 1;
  33631. var depth = options.depth || options.size || 1;
  33632. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33633. var faceUV = options.faceUV || new Array(6);
  33634. var faceColors = options.faceColors;
  33635. var colors = [];
  33636. // default face colors and UV if undefined
  33637. for (var f = 0; f < 6; f++) {
  33638. if (faceUV[f] === undefined) {
  33639. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33640. }
  33641. if (faceColors && faceColors[f] === undefined) {
  33642. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33643. }
  33644. }
  33645. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33646. // Create each face in turn.
  33647. for (var index = 0; index < normalsSource.length; index++) {
  33648. var normal = normalsSource[index];
  33649. // Get two vectors perpendicular to the face normal and to each other.
  33650. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33651. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33652. // Six indices (two triangles) per face.
  33653. var verticesLength = positions.length / 3;
  33654. indices.push(verticesLength);
  33655. indices.push(verticesLength + 1);
  33656. indices.push(verticesLength + 2);
  33657. indices.push(verticesLength);
  33658. indices.push(verticesLength + 2);
  33659. indices.push(verticesLength + 3);
  33660. // Four vertices per face.
  33661. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33662. positions.push(vertex.x, vertex.y, vertex.z);
  33663. normals.push(normal.x, normal.y, normal.z);
  33664. uvs.push(faceUV[index].z, faceUV[index].w);
  33665. if (faceColors) {
  33666. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33667. }
  33668. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33669. positions.push(vertex.x, vertex.y, vertex.z);
  33670. normals.push(normal.x, normal.y, normal.z);
  33671. uvs.push(faceUV[index].x, faceUV[index].w);
  33672. if (faceColors) {
  33673. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33674. }
  33675. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33676. positions.push(vertex.x, vertex.y, vertex.z);
  33677. normals.push(normal.x, normal.y, normal.z);
  33678. uvs.push(faceUV[index].x, faceUV[index].y);
  33679. if (faceColors) {
  33680. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33681. }
  33682. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33683. positions.push(vertex.x, vertex.y, vertex.z);
  33684. normals.push(normal.x, normal.y, normal.z);
  33685. uvs.push(faceUV[index].z, faceUV[index].y);
  33686. if (faceColors) {
  33687. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33688. }
  33689. }
  33690. // sides
  33691. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33692. // Result
  33693. var vertexData = new VertexData();
  33694. vertexData.indices = indices;
  33695. vertexData.positions = positions;
  33696. vertexData.normals = normals;
  33697. vertexData.uvs = uvs;
  33698. if (faceColors) {
  33699. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33700. vertexData.colors = totalColors;
  33701. }
  33702. return vertexData;
  33703. };
  33704. /**
  33705. * Creates the VertexData of the Sphere.
  33706. */
  33707. VertexData.CreateSphere = function (options) {
  33708. var segments = options.segments || 32;
  33709. var diameterX = options.diameterX || options.diameter || 1;
  33710. var diameterY = options.diameterY || options.diameter || 1;
  33711. var diameterZ = options.diameterZ || options.diameter || 1;
  33712. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33713. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33714. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33715. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33716. var totalZRotationSteps = 2 + segments;
  33717. var totalYRotationSteps = 2 * totalZRotationSteps;
  33718. var indices = [];
  33719. var positions = [];
  33720. var normals = [];
  33721. var uvs = [];
  33722. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33723. var normalizedZ = zRotationStep / totalZRotationSteps;
  33724. var angleZ = normalizedZ * Math.PI * slice;
  33725. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33726. var normalizedY = yRotationStep / totalYRotationSteps;
  33727. var angleY = normalizedY * Math.PI * 2 * arc;
  33728. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33729. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33730. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33731. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33732. var vertex = complete.multiply(radius);
  33733. var normal = complete.divide(radius).normalize();
  33734. positions.push(vertex.x, vertex.y, vertex.z);
  33735. normals.push(normal.x, normal.y, normal.z);
  33736. uvs.push(normalizedY, normalizedZ);
  33737. }
  33738. if (zRotationStep > 0) {
  33739. var verticesCount = positions.length / 3;
  33740. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33741. indices.push((firstIndex));
  33742. indices.push((firstIndex + 1));
  33743. indices.push(firstIndex + totalYRotationSteps + 1);
  33744. indices.push((firstIndex + totalYRotationSteps + 1));
  33745. indices.push((firstIndex + 1));
  33746. indices.push((firstIndex + totalYRotationSteps + 2));
  33747. }
  33748. }
  33749. }
  33750. // Sides
  33751. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33752. // Result
  33753. var vertexData = new VertexData();
  33754. vertexData.indices = indices;
  33755. vertexData.positions = positions;
  33756. vertexData.normals = normals;
  33757. vertexData.uvs = uvs;
  33758. return vertexData;
  33759. };
  33760. /**
  33761. * Creates the VertexData of the Cylinder or Cone.
  33762. */
  33763. VertexData.CreateCylinder = function (options) {
  33764. var height = options.height || 2;
  33765. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33766. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33767. var tessellation = options.tessellation || 24;
  33768. var subdivisions = options.subdivisions || 1;
  33769. var hasRings = options.hasRings ? true : false;
  33770. var enclose = options.enclose ? true : false;
  33771. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33772. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33773. var faceUV = options.faceUV || new Array(3);
  33774. var faceColors = options.faceColors;
  33775. // default face colors and UV if undefined
  33776. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33777. var ringNb = (hasRings) ? subdivisions : 1;
  33778. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33779. var f;
  33780. for (f = 0; f < surfaceNb; f++) {
  33781. if (faceColors && faceColors[f] === undefined) {
  33782. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33783. }
  33784. }
  33785. for (f = 0; f < surfaceNb; f++) {
  33786. if (faceUV && faceUV[f] === undefined) {
  33787. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33788. }
  33789. }
  33790. var indices = new Array();
  33791. var positions = new Array();
  33792. var normals = new Array();
  33793. var uvs = new Array();
  33794. var colors = new Array();
  33795. var angle_step = Math.PI * 2 * arc / tessellation;
  33796. var angle;
  33797. var h;
  33798. var radius;
  33799. var tan = (diameterBottom - diameterTop) / 2 / height;
  33800. var ringVertex = BABYLON.Vector3.Zero();
  33801. var ringNormal = BABYLON.Vector3.Zero();
  33802. var ringFirstVertex = BABYLON.Vector3.Zero();
  33803. var ringFirstNormal = BABYLON.Vector3.Zero();
  33804. var quadNormal = BABYLON.Vector3.Zero();
  33805. var Y = BABYLON.Axis.Y;
  33806. // positions, normals, uvs
  33807. var i;
  33808. var j;
  33809. var r;
  33810. var ringIdx = 1;
  33811. var s = 1; // surface index
  33812. var cs = 0;
  33813. var v = 0;
  33814. for (i = 0; i <= subdivisions; i++) {
  33815. h = i / subdivisions;
  33816. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33817. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33818. for (r = 0; r < ringIdx; r++) {
  33819. if (hasRings) {
  33820. s += r;
  33821. }
  33822. if (enclose) {
  33823. s += 2 * r;
  33824. }
  33825. for (j = 0; j <= tessellation; j++) {
  33826. angle = j * angle_step;
  33827. // position
  33828. ringVertex.x = Math.cos(-angle) * radius;
  33829. ringVertex.y = -height / 2 + h * height;
  33830. ringVertex.z = Math.sin(-angle) * radius;
  33831. // normal
  33832. if (diameterTop === 0 && i === subdivisions) {
  33833. // if no top cap, reuse former normals
  33834. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33835. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33836. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33837. }
  33838. else {
  33839. ringNormal.x = ringVertex.x;
  33840. ringNormal.z = ringVertex.z;
  33841. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33842. ringNormal.normalize();
  33843. }
  33844. // keep first ring vertex values for enclose
  33845. if (j === 0) {
  33846. ringFirstVertex.copyFrom(ringVertex);
  33847. ringFirstNormal.copyFrom(ringNormal);
  33848. }
  33849. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33850. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33851. if (hasRings) {
  33852. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33853. }
  33854. else {
  33855. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33856. }
  33857. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33858. if (faceColors) {
  33859. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33860. }
  33861. }
  33862. // if enclose, add four vertices and their dedicated normals
  33863. if (arc !== 1 && enclose) {
  33864. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33865. positions.push(0, ringVertex.y, 0);
  33866. positions.push(0, ringVertex.y, 0);
  33867. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33868. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33869. quadNormal.normalize();
  33870. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33871. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33872. quadNormal.normalize();
  33873. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33874. if (hasRings) {
  33875. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33876. }
  33877. else {
  33878. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33879. }
  33880. uvs.push(faceUV[s + 1].x, v);
  33881. uvs.push(faceUV[s + 1].z, v);
  33882. if (hasRings) {
  33883. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33884. }
  33885. else {
  33886. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33887. }
  33888. uvs.push(faceUV[s + 2].x, v);
  33889. uvs.push(faceUV[s + 2].z, v);
  33890. if (faceColors) {
  33891. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33892. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33893. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33894. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33895. }
  33896. }
  33897. if (cs !== s) {
  33898. cs = s;
  33899. }
  33900. }
  33901. }
  33902. // indices
  33903. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33904. var s;
  33905. i = 0;
  33906. for (s = 0; s < subdivisions; s++) {
  33907. var i0 = 0;
  33908. var i1 = 0;
  33909. var i2 = 0;
  33910. var i3 = 0;
  33911. for (j = 0; j < tessellation; j++) {
  33912. i0 = i * (e + 1) + j;
  33913. i1 = (i + 1) * (e + 1) + j;
  33914. i2 = i * (e + 1) + (j + 1);
  33915. i3 = (i + 1) * (e + 1) + (j + 1);
  33916. indices.push(i0, i1, i2);
  33917. indices.push(i3, i2, i1);
  33918. }
  33919. if (arc !== 1 && enclose) {
  33920. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33921. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33922. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33923. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33924. }
  33925. i = (hasRings) ? (i + 2) : (i + 1);
  33926. }
  33927. // Caps
  33928. var createCylinderCap = function (isTop) {
  33929. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33930. if (radius === 0) {
  33931. return;
  33932. }
  33933. // Cap positions, normals & uvs
  33934. var angle;
  33935. var circleVector;
  33936. var i;
  33937. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33938. var c = null;
  33939. if (faceColors) {
  33940. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33941. }
  33942. // cap center
  33943. var vbase = positions.length / 3;
  33944. var offset = isTop ? height / 2 : -height / 2;
  33945. var center = new BABYLON.Vector3(0, offset, 0);
  33946. positions.push(center.x, center.y, center.z);
  33947. normals.push(0, isTop ? 1 : -1, 0);
  33948. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33949. if (c) {
  33950. colors.push(c.r, c.g, c.b, c.a);
  33951. }
  33952. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33953. for (i = 0; i <= tessellation; i++) {
  33954. angle = Math.PI * 2 * i * arc / tessellation;
  33955. var cos = Math.cos(-angle);
  33956. var sin = Math.sin(-angle);
  33957. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33958. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33959. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33960. normals.push(0, isTop ? 1 : -1, 0);
  33961. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33962. if (c) {
  33963. colors.push(c.r, c.g, c.b, c.a);
  33964. }
  33965. }
  33966. // Cap indices
  33967. for (i = 0; i < tessellation; i++) {
  33968. if (!isTop) {
  33969. indices.push(vbase);
  33970. indices.push(vbase + (i + 1));
  33971. indices.push(vbase + (i + 2));
  33972. }
  33973. else {
  33974. indices.push(vbase);
  33975. indices.push(vbase + (i + 2));
  33976. indices.push(vbase + (i + 1));
  33977. }
  33978. }
  33979. };
  33980. // add caps to geometry
  33981. createCylinderCap(false);
  33982. createCylinderCap(true);
  33983. // Sides
  33984. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33985. var vertexData = new VertexData();
  33986. vertexData.indices = indices;
  33987. vertexData.positions = positions;
  33988. vertexData.normals = normals;
  33989. vertexData.uvs = uvs;
  33990. if (faceColors) {
  33991. vertexData.colors = colors;
  33992. }
  33993. return vertexData;
  33994. };
  33995. /**
  33996. * Creates the VertexData of the Torus.
  33997. */
  33998. VertexData.CreateTorus = function (options) {
  33999. var indices = [];
  34000. var positions = [];
  34001. var normals = [];
  34002. var uvs = [];
  34003. var diameter = options.diameter || 1;
  34004. var thickness = options.thickness || 0.5;
  34005. var tessellation = options.tessellation || 16;
  34006. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34007. var stride = tessellation + 1;
  34008. for (var i = 0; i <= tessellation; i++) {
  34009. var u = i / tessellation;
  34010. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  34011. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  34012. for (var j = 0; j <= tessellation; j++) {
  34013. var v = 1 - j / tessellation;
  34014. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  34015. var dx = Math.cos(innerAngle);
  34016. var dy = Math.sin(innerAngle);
  34017. // Create a vertex.
  34018. var normal = new BABYLON.Vector3(dx, dy, 0);
  34019. var position = normal.scale(thickness / 2);
  34020. var textureCoordinate = new BABYLON.Vector2(u, v);
  34021. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  34022. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  34023. positions.push(position.x, position.y, position.z);
  34024. normals.push(normal.x, normal.y, normal.z);
  34025. uvs.push(textureCoordinate.x, textureCoordinate.y);
  34026. // And create indices for two triangles.
  34027. var nextI = (i + 1) % stride;
  34028. var nextJ = (j + 1) % stride;
  34029. indices.push(i * stride + j);
  34030. indices.push(i * stride + nextJ);
  34031. indices.push(nextI * stride + j);
  34032. indices.push(i * stride + nextJ);
  34033. indices.push(nextI * stride + nextJ);
  34034. indices.push(nextI * stride + j);
  34035. }
  34036. }
  34037. // Sides
  34038. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34039. // Result
  34040. var vertexData = new VertexData();
  34041. vertexData.indices = indices;
  34042. vertexData.positions = positions;
  34043. vertexData.normals = normals;
  34044. vertexData.uvs = uvs;
  34045. return vertexData;
  34046. };
  34047. /**
  34048. * Creates the VertexData of the LineSystem.
  34049. */
  34050. VertexData.CreateLineSystem = function (options) {
  34051. var indices = [];
  34052. var positions = [];
  34053. var lines = options.lines;
  34054. var colors = options.colors;
  34055. var vertexColors = [];
  34056. var idx = 0;
  34057. for (var l = 0; l < lines.length; l++) {
  34058. var points = lines[l];
  34059. for (var index = 0; index < points.length; index++) {
  34060. positions.push(points[index].x, points[index].y, points[index].z);
  34061. if (colors) {
  34062. var color = colors[l];
  34063. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  34064. }
  34065. if (index > 0) {
  34066. indices.push(idx - 1);
  34067. indices.push(idx);
  34068. }
  34069. idx++;
  34070. }
  34071. }
  34072. var vertexData = new VertexData();
  34073. vertexData.indices = indices;
  34074. vertexData.positions = positions;
  34075. if (colors) {
  34076. vertexData.colors = vertexColors;
  34077. }
  34078. return vertexData;
  34079. };
  34080. /**
  34081. * Create the VertexData of the DashedLines.
  34082. */
  34083. VertexData.CreateDashedLines = function (options) {
  34084. var dashSize = options.dashSize || 3;
  34085. var gapSize = options.gapSize || 1;
  34086. var dashNb = options.dashNb || 200;
  34087. var points = options.points;
  34088. var positions = new Array();
  34089. var indices = new Array();
  34090. var curvect = BABYLON.Vector3.Zero();
  34091. var lg = 0;
  34092. var nb = 0;
  34093. var shft = 0;
  34094. var dashshft = 0;
  34095. var curshft = 0;
  34096. var idx = 0;
  34097. var i = 0;
  34098. for (i = 0; i < points.length - 1; i++) {
  34099. points[i + 1].subtractToRef(points[i], curvect);
  34100. lg += curvect.length();
  34101. }
  34102. shft = lg / dashNb;
  34103. dashshft = dashSize * shft / (dashSize + gapSize);
  34104. for (i = 0; i < points.length - 1; i++) {
  34105. points[i + 1].subtractToRef(points[i], curvect);
  34106. nb = Math.floor(curvect.length() / shft);
  34107. curvect.normalize();
  34108. for (var j = 0; j < nb; j++) {
  34109. curshft = shft * j;
  34110. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  34111. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  34112. indices.push(idx, idx + 1);
  34113. idx += 2;
  34114. }
  34115. }
  34116. // Result
  34117. var vertexData = new VertexData();
  34118. vertexData.positions = positions;
  34119. vertexData.indices = indices;
  34120. return vertexData;
  34121. };
  34122. /**
  34123. * Creates the VertexData of the Ground.
  34124. */
  34125. VertexData.CreateGround = function (options) {
  34126. var indices = [];
  34127. var positions = [];
  34128. var normals = [];
  34129. var uvs = [];
  34130. var row, col;
  34131. var width = options.width || 1;
  34132. var height = options.height || 1;
  34133. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  34134. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  34135. for (row = 0; row <= subdivisionsY; row++) {
  34136. for (col = 0; col <= subdivisionsX; col++) {
  34137. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  34138. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34139. positions.push(position.x, position.y, position.z);
  34140. normals.push(normal.x, normal.y, normal.z);
  34141. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  34142. }
  34143. }
  34144. for (row = 0; row < subdivisionsY; row++) {
  34145. for (col = 0; col < subdivisionsX; col++) {
  34146. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34147. indices.push(col + 1 + row * (subdivisionsX + 1));
  34148. indices.push(col + row * (subdivisionsX + 1));
  34149. indices.push(col + (row + 1) * (subdivisionsX + 1));
  34150. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34151. indices.push(col + row * (subdivisionsX + 1));
  34152. }
  34153. }
  34154. // Result
  34155. var vertexData = new VertexData();
  34156. vertexData.indices = indices;
  34157. vertexData.positions = positions;
  34158. vertexData.normals = normals;
  34159. vertexData.uvs = uvs;
  34160. return vertexData;
  34161. };
  34162. /**
  34163. * Creates the VertexData of the TiledGround.
  34164. */
  34165. VertexData.CreateTiledGround = function (options) {
  34166. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  34167. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  34168. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  34169. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  34170. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  34171. var precision = options.precision || { w: 1, h: 1 };
  34172. var indices = new Array();
  34173. var positions = new Array();
  34174. var normals = new Array();
  34175. var uvs = new Array();
  34176. var row, col, tileRow, tileCol;
  34177. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  34178. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  34179. precision.w = (precision.w < 1) ? 1 : precision.w;
  34180. precision.h = (precision.h < 1) ? 1 : precision.h;
  34181. var tileSize = {
  34182. 'w': (xmax - xmin) / subdivisions.w,
  34183. 'h': (zmax - zmin) / subdivisions.h
  34184. };
  34185. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  34186. // Indices
  34187. var base = positions.length / 3;
  34188. var rowLength = precision.w + 1;
  34189. for (row = 0; row < precision.h; row++) {
  34190. for (col = 0; col < precision.w; col++) {
  34191. var square = [
  34192. base + col + row * rowLength,
  34193. base + (col + 1) + row * rowLength,
  34194. base + (col + 1) + (row + 1) * rowLength,
  34195. base + col + (row + 1) * rowLength
  34196. ];
  34197. indices.push(square[1]);
  34198. indices.push(square[2]);
  34199. indices.push(square[3]);
  34200. indices.push(square[0]);
  34201. indices.push(square[1]);
  34202. indices.push(square[3]);
  34203. }
  34204. }
  34205. // Position, normals and uvs
  34206. var position = BABYLON.Vector3.Zero();
  34207. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34208. for (row = 0; row <= precision.h; row++) {
  34209. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  34210. for (col = 0; col <= precision.w; col++) {
  34211. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  34212. position.y = 0;
  34213. positions.push(position.x, position.y, position.z);
  34214. normals.push(normal.x, normal.y, normal.z);
  34215. uvs.push(col / precision.w, row / precision.h);
  34216. }
  34217. }
  34218. }
  34219. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  34220. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  34221. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  34222. }
  34223. }
  34224. // Result
  34225. var vertexData = new VertexData();
  34226. vertexData.indices = indices;
  34227. vertexData.positions = positions;
  34228. vertexData.normals = normals;
  34229. vertexData.uvs = uvs;
  34230. return vertexData;
  34231. };
  34232. /**
  34233. * Creates the VertexData of the Ground designed from a heightmap.
  34234. */
  34235. VertexData.CreateGroundFromHeightMap = function (options) {
  34236. var indices = [];
  34237. var positions = [];
  34238. var normals = [];
  34239. var uvs = [];
  34240. var row, col;
  34241. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  34242. // Vertices
  34243. for (row = 0; row <= options.subdivisions; row++) {
  34244. for (col = 0; col <= options.subdivisions; col++) {
  34245. 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));
  34246. // Compute height
  34247. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  34248. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  34249. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  34250. var r = options.buffer[pos] / 255.0;
  34251. var g = options.buffer[pos + 1] / 255.0;
  34252. var b = options.buffer[pos + 2] / 255.0;
  34253. var gradient = r * filter.r + g * filter.g + b * filter.b;
  34254. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  34255. // Add vertex
  34256. positions.push(position.x, position.y, position.z);
  34257. normals.push(0, 0, 0);
  34258. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  34259. }
  34260. }
  34261. // Indices
  34262. for (row = 0; row < options.subdivisions; row++) {
  34263. for (col = 0; col < options.subdivisions; col++) {
  34264. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34265. indices.push(col + 1 + row * (options.subdivisions + 1));
  34266. indices.push(col + row * (options.subdivisions + 1));
  34267. indices.push(col + (row + 1) * (options.subdivisions + 1));
  34268. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34269. indices.push(col + row * (options.subdivisions + 1));
  34270. }
  34271. }
  34272. // Normals
  34273. VertexData.ComputeNormals(positions, indices, normals);
  34274. // Result
  34275. var vertexData = new VertexData();
  34276. vertexData.indices = indices;
  34277. vertexData.positions = positions;
  34278. vertexData.normals = normals;
  34279. vertexData.uvs = uvs;
  34280. return vertexData;
  34281. };
  34282. /**
  34283. * Creates the VertexData of the Plane.
  34284. */
  34285. VertexData.CreatePlane = function (options) {
  34286. var indices = [];
  34287. var positions = [];
  34288. var normals = [];
  34289. var uvs = [];
  34290. var width = options.width || options.size || 1;
  34291. var height = options.height || options.size || 1;
  34292. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34293. // Vertices
  34294. var halfWidth = width / 2.0;
  34295. var halfHeight = height / 2.0;
  34296. positions.push(-halfWidth, -halfHeight, 0);
  34297. normals.push(0, 0, -1.0);
  34298. uvs.push(0.0, 0.0);
  34299. positions.push(halfWidth, -halfHeight, 0);
  34300. normals.push(0, 0, -1.0);
  34301. uvs.push(1.0, 0.0);
  34302. positions.push(halfWidth, halfHeight, 0);
  34303. normals.push(0, 0, -1.0);
  34304. uvs.push(1.0, 1.0);
  34305. positions.push(-halfWidth, halfHeight, 0);
  34306. normals.push(0, 0, -1.0);
  34307. uvs.push(0.0, 1.0);
  34308. // Indices
  34309. indices.push(0);
  34310. indices.push(1);
  34311. indices.push(2);
  34312. indices.push(0);
  34313. indices.push(2);
  34314. indices.push(3);
  34315. // Sides
  34316. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34317. // Result
  34318. var vertexData = new VertexData();
  34319. vertexData.indices = indices;
  34320. vertexData.positions = positions;
  34321. vertexData.normals = normals;
  34322. vertexData.uvs = uvs;
  34323. return vertexData;
  34324. };
  34325. /**
  34326. * Creates the VertexData of the Disc or regular Polygon.
  34327. */
  34328. VertexData.CreateDisc = function (options) {
  34329. var positions = new Array();
  34330. var indices = new Array();
  34331. var normals = new Array();
  34332. var uvs = new Array();
  34333. var radius = options.radius || 0.5;
  34334. var tessellation = options.tessellation || 64;
  34335. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  34336. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34337. // positions and uvs
  34338. positions.push(0, 0, 0); // disc center first
  34339. uvs.push(0.5, 0.5);
  34340. var theta = Math.PI * 2 * arc;
  34341. var step = theta / tessellation;
  34342. for (var a = 0; a < theta; a += step) {
  34343. var x = Math.cos(a);
  34344. var y = Math.sin(a);
  34345. var u = (x + 1) / 2;
  34346. var v = (1 - y) / 2;
  34347. positions.push(radius * x, radius * y, 0);
  34348. uvs.push(u, v);
  34349. }
  34350. if (arc === 1) {
  34351. positions.push(positions[3], positions[4], positions[5]); // close the circle
  34352. uvs.push(uvs[2], uvs[3]);
  34353. }
  34354. //indices
  34355. var vertexNb = positions.length / 3;
  34356. for (var i = 1; i < vertexNb - 1; i++) {
  34357. indices.push(i + 1, 0, i);
  34358. }
  34359. // result
  34360. VertexData.ComputeNormals(positions, indices, normals);
  34361. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34362. var vertexData = new VertexData();
  34363. vertexData.indices = indices;
  34364. vertexData.positions = positions;
  34365. vertexData.normals = normals;
  34366. vertexData.uvs = uvs;
  34367. return vertexData;
  34368. };
  34369. /**
  34370. * Re-creates the VertexData of the Polygon for sideOrientation.
  34371. */
  34372. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  34373. var faceUV = fUV || new Array(3);
  34374. var faceColors = fColors;
  34375. var colors = [];
  34376. // default face colors and UV if undefined
  34377. for (var f = 0; f < 3; f++) {
  34378. if (faceUV[f] === undefined) {
  34379. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34380. }
  34381. if (faceColors && faceColors[f] === undefined) {
  34382. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34383. }
  34384. }
  34385. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34386. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34387. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34388. var indices = polygon.getIndices();
  34389. // set face colours and textures
  34390. var idx = 0;
  34391. var face = 0;
  34392. for (var index = 0; index < normals.length; index += 3) {
  34393. //Edge Face no. 1
  34394. if (Math.abs(normals[index + 1]) < 0.001) {
  34395. face = 1;
  34396. }
  34397. //Top Face no. 0
  34398. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  34399. face = 0;
  34400. }
  34401. //Bottom Face no. 2
  34402. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  34403. face = 2;
  34404. }
  34405. idx = index / 3;
  34406. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  34407. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  34408. if (faceColors) {
  34409. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  34410. }
  34411. }
  34412. // sides
  34413. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  34414. // Result
  34415. var vertexData = new VertexData();
  34416. vertexData.indices = indices;
  34417. vertexData.positions = positions;
  34418. vertexData.normals = normals;
  34419. vertexData.uvs = uvs;
  34420. if (faceColors) {
  34421. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  34422. vertexData.colors = totalColors;
  34423. }
  34424. return vertexData;
  34425. };
  34426. /**
  34427. * Creates the VertexData of the IcoSphere.
  34428. */
  34429. VertexData.CreateIcoSphere = function (options) {
  34430. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34431. var radius = options.radius || 1;
  34432. var flat = (options.flat === undefined) ? true : options.flat;
  34433. var subdivisions = options.subdivisions || 4;
  34434. var radiusX = options.radiusX || radius;
  34435. var radiusY = options.radiusY || radius;
  34436. var radiusZ = options.radiusZ || radius;
  34437. var t = (1 + Math.sqrt(5)) / 2;
  34438. // 12 vertex x,y,z
  34439. var ico_vertices = [
  34440. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  34441. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  34442. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  34443. ];
  34444. // index of 3 vertex makes a face of icopshere
  34445. var ico_indices = [
  34446. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  34447. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  34448. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  34449. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  34450. ];
  34451. // vertex for uv have aliased position, not for UV
  34452. var vertices_unalias_id = [
  34453. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  34454. // vertex alias
  34455. 0,
  34456. 2,
  34457. 3,
  34458. 3,
  34459. 3,
  34460. 4,
  34461. 7,
  34462. 8,
  34463. 9,
  34464. 9,
  34465. 10,
  34466. 11 // 23: B + 12
  34467. ];
  34468. // uv as integer step (not pixels !)
  34469. var ico_vertexuv = [
  34470. 5, 1, 3, 1, 6, 4, 0, 0,
  34471. 5, 3, 4, 2, 2, 2, 4, 0,
  34472. 2, 0, 1, 1, 6, 0, 6, 2,
  34473. // vertex alias (for same vertex on different faces)
  34474. 0, 4,
  34475. 3, 3,
  34476. 4, 4,
  34477. 3, 1,
  34478. 4, 2,
  34479. 4, 4,
  34480. 0, 2,
  34481. 1, 1,
  34482. 2, 2,
  34483. 3, 3,
  34484. 1, 3,
  34485. 2, 4 // 23: B + 12
  34486. ];
  34487. // Vertices[0, 1, ...9, A, B] : position on UV plane
  34488. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  34489. // First island of uv mapping
  34490. // v = 4h 3+ 2
  34491. // v = 3h 9+ 4
  34492. // v = 2h 9+ 5 B
  34493. // v = 1h 9 1 0
  34494. // v = 0h 3 8 7 A
  34495. // u = 0 1 2 3 4 5 6 *a
  34496. // Second island of uv mapping
  34497. // v = 4h 0+ B+ 4+
  34498. // v = 3h A+ 2+
  34499. // v = 2h 7+ 6 3+
  34500. // v = 1h 8+ 3+
  34501. // v = 0h
  34502. // u = 0 1 2 3 4 5 6 *a
  34503. // Face layout on texture UV mapping
  34504. // ============
  34505. // \ 4 /\ 16 / ======
  34506. // \ / \ / /\ 11 /
  34507. // \/ 7 \/ / \ /
  34508. // ======= / 10 \/
  34509. // /\ 17 /\ =======
  34510. // / \ / \ \ 15 /\
  34511. // / 8 \/ 12 \ \ / \
  34512. // ============ \/ 6 \
  34513. // \ 18 /\ ============
  34514. // \ / \ \ 5 /\ 0 /
  34515. // \/ 13 \ \ / \ /
  34516. // ======= \/ 1 \/
  34517. // =============
  34518. // /\ 19 /\ 2 /\
  34519. // / \ / \ / \
  34520. // / 14 \/ 9 \/ 3 \
  34521. // ===================
  34522. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  34523. var ustep = 138 / 1024;
  34524. var vstep = 239 / 1024;
  34525. var uoffset = 60 / 1024;
  34526. var voffset = 26 / 1024;
  34527. // Second island should have margin, not to touch the first island
  34528. // avoid any borderline artefact in pixel rounding
  34529. var island_u_offset = -40 / 1024;
  34530. var island_v_offset = +20 / 1024;
  34531. // face is either island 0 or 1 :
  34532. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  34533. var island = [
  34534. 0, 0, 0, 0, 1,
  34535. 0, 0, 1, 1, 0,
  34536. 0, 0, 1, 1, 0,
  34537. 0, 1, 1, 1, 0 // 15 - 19
  34538. ];
  34539. var indices = new Array();
  34540. var positions = new Array();
  34541. var normals = new Array();
  34542. var uvs = new Array();
  34543. var current_indice = 0;
  34544. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  34545. var face_vertex_pos = new Array(3);
  34546. var face_vertex_uv = new Array(3);
  34547. var v012;
  34548. for (v012 = 0; v012 < 3; v012++) {
  34549. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  34550. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  34551. }
  34552. // create all with normals
  34553. for (var face = 0; face < 20; face++) {
  34554. // 3 vertex per face
  34555. for (v012 = 0; v012 < 3; v012++) {
  34556. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  34557. var v_id = ico_indices[3 * face + v012];
  34558. // vertex have 3D position (x,y,z)
  34559. 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]);
  34560. // Normalize to get normal, then scale to radius
  34561. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  34562. // uv Coordinates from vertex ID
  34563. 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);
  34564. }
  34565. // Subdivide the face (interpolate pos, norm, uv)
  34566. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  34567. // - norm is linear interpolation of vertex corner normal
  34568. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  34569. // - uv is linear interpolation
  34570. //
  34571. // Topology is as below for sub-divide by 2
  34572. // vertex shown as v0,v1,v2
  34573. // interp index is i1 to progress in range [v0,v1[
  34574. // interp index is i2 to progress in range [v0,v2[
  34575. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  34576. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34577. //
  34578. //
  34579. // i2 v2
  34580. // ^ ^
  34581. // / / \
  34582. // / / \
  34583. // / / \
  34584. // / / (0,1) \
  34585. // / #---------\
  34586. // / / \ (0,0)'/ \
  34587. // / / \ / \
  34588. // / / \ / \
  34589. // / / (0,0) \ / (1,0) \
  34590. // / #---------#---------\
  34591. // v0 v1
  34592. //
  34593. // --------------------> i1
  34594. //
  34595. // interp of (i1,i2):
  34596. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34597. // along i1 : lerp(x0,x1, i1/(S-i2))
  34598. //
  34599. // centroid of triangle is needed to get help normal computation
  34600. // (c1,c2) are used for centroid location
  34601. var interp_vertex = function (i1, i2, c1, c2) {
  34602. // vertex is interpolated from
  34603. // - face_vertex_pos[0..2]
  34604. // - face_vertex_uv[0..2]
  34605. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34606. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34607. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34608. pos_interp.normalize();
  34609. var vertex_normal;
  34610. if (flat) {
  34611. // in flat mode, recalculate normal as face centroid normal
  34612. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34613. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34614. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34615. }
  34616. else {
  34617. // in smooth mode, recalculate normal from each single vertex position
  34618. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34619. }
  34620. // Vertex normal need correction due to X,Y,Z radius scaling
  34621. vertex_normal.x /= radiusX;
  34622. vertex_normal.y /= radiusY;
  34623. vertex_normal.z /= radiusZ;
  34624. vertex_normal.normalize();
  34625. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34626. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34627. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34628. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34629. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34630. uvs.push(uv_interp.x, uv_interp.y);
  34631. // push each vertex has member of a face
  34632. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34633. indices.push(current_indice);
  34634. current_indice++;
  34635. };
  34636. for (var i2 = 0; i2 < subdivisions; i2++) {
  34637. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34638. // face : (i1,i2) for /\ :
  34639. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34640. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34641. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34642. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34643. if (i1 + i2 + 1 < subdivisions) {
  34644. // face : (i1,i2)' for \/ :
  34645. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34646. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34647. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34648. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34649. }
  34650. }
  34651. }
  34652. }
  34653. // Sides
  34654. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34655. // Result
  34656. var vertexData = new VertexData();
  34657. vertexData.indices = indices;
  34658. vertexData.positions = positions;
  34659. vertexData.normals = normals;
  34660. vertexData.uvs = uvs;
  34661. return vertexData;
  34662. };
  34663. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34664. /**
  34665. * Creates the VertexData of the Polyhedron.
  34666. */
  34667. VertexData.CreatePolyhedron = function (options) {
  34668. // provided polyhedron types :
  34669. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34670. // 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)
  34671. var polyhedra = [];
  34672. 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]] };
  34673. 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]] };
  34674. polyhedra[2] = {
  34675. 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]],
  34676. 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]]
  34677. };
  34678. polyhedra[3] = {
  34679. 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]],
  34680. 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]]
  34681. };
  34682. polyhedra[4] = {
  34683. 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]],
  34684. 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]]
  34685. };
  34686. 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]] };
  34687. 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]] };
  34688. 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]] };
  34689. 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]] };
  34690. 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]] };
  34691. 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]] };
  34692. 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]] };
  34693. 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]] };
  34694. 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]] };
  34695. polyhedra[14] = {
  34696. 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]],
  34697. 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]]
  34698. };
  34699. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34700. var size = options.size;
  34701. var sizeX = options.sizeX || size || 1;
  34702. var sizeY = options.sizeY || size || 1;
  34703. var sizeZ = options.sizeZ || size || 1;
  34704. var data = options.custom || polyhedra[type];
  34705. var nbfaces = data.face.length;
  34706. var faceUV = options.faceUV || new Array(nbfaces);
  34707. var faceColors = options.faceColors;
  34708. var flat = (options.flat === undefined) ? true : options.flat;
  34709. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34710. var positions = new Array();
  34711. var indices = new Array();
  34712. var normals = new Array();
  34713. var uvs = new Array();
  34714. var colors = new Array();
  34715. var index = 0;
  34716. var faceIdx = 0; // face cursor in the array "indexes"
  34717. var indexes = new Array();
  34718. var i = 0;
  34719. var f = 0;
  34720. var u, v, ang, x, y, tmp;
  34721. // default face colors and UV if undefined
  34722. if (flat) {
  34723. for (f = 0; f < nbfaces; f++) {
  34724. if (faceColors && faceColors[f] === undefined) {
  34725. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34726. }
  34727. if (faceUV && faceUV[f] === undefined) {
  34728. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34729. }
  34730. }
  34731. }
  34732. if (!flat) {
  34733. for (i = 0; i < data.vertex.length; i++) {
  34734. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34735. uvs.push(0, 0);
  34736. }
  34737. for (f = 0; f < nbfaces; f++) {
  34738. for (i = 0; i < data.face[f].length - 2; i++) {
  34739. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34740. }
  34741. }
  34742. }
  34743. else {
  34744. for (f = 0; f < nbfaces; f++) {
  34745. var fl = data.face[f].length; // number of vertices of the current face
  34746. ang = 2 * Math.PI / fl;
  34747. x = 0.5 * Math.tan(ang / 2);
  34748. y = 0.5;
  34749. // positions, uvs, colors
  34750. for (i = 0; i < fl; i++) {
  34751. // positions
  34752. 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);
  34753. indexes.push(index);
  34754. index++;
  34755. // uvs
  34756. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34757. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34758. uvs.push(u, v);
  34759. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34760. y = x * Math.sin(ang) + y * Math.cos(ang);
  34761. x = tmp;
  34762. // colors
  34763. if (faceColors) {
  34764. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34765. }
  34766. }
  34767. // indices from indexes
  34768. for (i = 0; i < fl - 2; i++) {
  34769. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34770. }
  34771. faceIdx += fl;
  34772. }
  34773. }
  34774. VertexData.ComputeNormals(positions, indices, normals);
  34775. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34776. var vertexData = new VertexData();
  34777. vertexData.positions = positions;
  34778. vertexData.indices = indices;
  34779. vertexData.normals = normals;
  34780. vertexData.uvs = uvs;
  34781. if (faceColors && flat) {
  34782. vertexData.colors = colors;
  34783. }
  34784. return vertexData;
  34785. };
  34786. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34787. /**
  34788. * Creates the VertexData of the Torus Knot.
  34789. */
  34790. VertexData.CreateTorusKnot = function (options) {
  34791. var indices = new Array();
  34792. var positions = new Array();
  34793. var normals = new Array();
  34794. var uvs = new Array();
  34795. var radius = options.radius || 2;
  34796. var tube = options.tube || 0.5;
  34797. var radialSegments = options.radialSegments || 32;
  34798. var tubularSegments = options.tubularSegments || 32;
  34799. var p = options.p || 2;
  34800. var q = options.q || 3;
  34801. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34802. // Helper
  34803. var getPos = function (angle) {
  34804. var cu = Math.cos(angle);
  34805. var su = Math.sin(angle);
  34806. var quOverP = q / p * angle;
  34807. var cs = Math.cos(quOverP);
  34808. var tx = radius * (2 + cs) * 0.5 * cu;
  34809. var ty = radius * (2 + cs) * su * 0.5;
  34810. var tz = radius * Math.sin(quOverP) * 0.5;
  34811. return new BABYLON.Vector3(tx, ty, tz);
  34812. };
  34813. // Vertices
  34814. var i;
  34815. var j;
  34816. for (i = 0; i <= radialSegments; i++) {
  34817. var modI = i % radialSegments;
  34818. var u = modI / radialSegments * 2 * p * Math.PI;
  34819. var p1 = getPos(u);
  34820. var p2 = getPos(u + 0.01);
  34821. var tang = p2.subtract(p1);
  34822. var n = p2.add(p1);
  34823. var bitan = BABYLON.Vector3.Cross(tang, n);
  34824. n = BABYLON.Vector3.Cross(bitan, tang);
  34825. bitan.normalize();
  34826. n.normalize();
  34827. for (j = 0; j < tubularSegments; j++) {
  34828. var modJ = j % tubularSegments;
  34829. var v = modJ / tubularSegments * 2 * Math.PI;
  34830. var cx = -tube * Math.cos(v);
  34831. var cy = tube * Math.sin(v);
  34832. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34833. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34834. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34835. uvs.push(i / radialSegments);
  34836. uvs.push(j / tubularSegments);
  34837. }
  34838. }
  34839. for (i = 0; i < radialSegments; i++) {
  34840. for (j = 0; j < tubularSegments; j++) {
  34841. var jNext = (j + 1) % tubularSegments;
  34842. var a = i * tubularSegments + j;
  34843. var b = (i + 1) * tubularSegments + j;
  34844. var c = (i + 1) * tubularSegments + jNext;
  34845. var d = i * tubularSegments + jNext;
  34846. indices.push(d);
  34847. indices.push(b);
  34848. indices.push(a);
  34849. indices.push(d);
  34850. indices.push(c);
  34851. indices.push(b);
  34852. }
  34853. }
  34854. // Normals
  34855. VertexData.ComputeNormals(positions, indices, normals);
  34856. // Sides
  34857. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34858. // Result
  34859. var vertexData = new VertexData();
  34860. vertexData.indices = indices;
  34861. vertexData.positions = positions;
  34862. vertexData.normals = normals;
  34863. vertexData.uvs = uvs;
  34864. return vertexData;
  34865. };
  34866. // Tools
  34867. /**
  34868. * @param {any} - positions (number[] or Float32Array)
  34869. * @param {any} - indices (number[] or Uint16Array)
  34870. * @param {any} - normals (number[] or Float32Array)
  34871. * options (optional) :
  34872. * facetPositions : optional array of facet positions (vector3)
  34873. * facetNormals : optional array of facet normals (vector3)
  34874. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34875. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34876. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34877. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34878. * bInfo : optional bounding info, required for facetPartitioning computation
  34879. * useRightHandedSystem: optional boolean to for right handed system computation
  34880. * depthSort : optional boolean to enable the facet depth sort computation
  34881. * distanceTo : optional Vector3 to compute the facet depth from this location
  34882. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34883. */
  34884. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34885. // temporary scalar variables
  34886. var index = 0; // facet index
  34887. var p1p2x = 0.0; // p1p2 vector x coordinate
  34888. var p1p2y = 0.0; // p1p2 vector y coordinate
  34889. var p1p2z = 0.0; // p1p2 vector z coordinate
  34890. var p3p2x = 0.0; // p3p2 vector x coordinate
  34891. var p3p2y = 0.0; // p3p2 vector y coordinate
  34892. var p3p2z = 0.0; // p3p2 vector z coordinate
  34893. var faceNormalx = 0.0; // facet normal x coordinate
  34894. var faceNormaly = 0.0; // facet normal y coordinate
  34895. var faceNormalz = 0.0; // facet normal z coordinate
  34896. var length = 0.0; // facet normal length before normalization
  34897. var v1x = 0; // vector1 x index in the positions array
  34898. var v1y = 0; // vector1 y index in the positions array
  34899. var v1z = 0; // vector1 z index in the positions array
  34900. var v2x = 0; // vector2 x index in the positions array
  34901. var v2y = 0; // vector2 y index in the positions array
  34902. var v2z = 0; // vector2 z index in the positions array
  34903. var v3x = 0; // vector3 x index in the positions array
  34904. var v3y = 0; // vector3 y index in the positions array
  34905. var v3z = 0; // vector3 z index in the positions array
  34906. var computeFacetNormals = false;
  34907. var computeFacetPositions = false;
  34908. var computeFacetPartitioning = false;
  34909. var computeDepthSort = false;
  34910. var faceNormalSign = 1;
  34911. var ratio = 0;
  34912. var distanceTo = null;
  34913. if (options) {
  34914. computeFacetNormals = (options.facetNormals) ? true : false;
  34915. computeFacetPositions = (options.facetPositions) ? true : false;
  34916. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34917. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34918. ratio = options.ratio || 0;
  34919. computeDepthSort = (options.depthSort) ? true : false;
  34920. distanceTo = (options.distanceTo);
  34921. if (computeDepthSort) {
  34922. if (distanceTo === undefined) {
  34923. distanceTo = BABYLON.Vector3.Zero();
  34924. }
  34925. var depthSortedFacets = options.depthSortedFacets;
  34926. }
  34927. }
  34928. // facetPartitioning reinit if needed
  34929. var xSubRatio = 0;
  34930. var ySubRatio = 0;
  34931. var zSubRatio = 0;
  34932. var subSq = 0;
  34933. if (computeFacetPartitioning && options && options.bbSize) {
  34934. var ox = 0; // X partitioning index for facet position
  34935. var oy = 0; // Y partinioning index for facet position
  34936. var oz = 0; // Z partinioning index for facet position
  34937. var b1x = 0; // X partitioning index for facet v1 vertex
  34938. var b1y = 0; // Y partitioning index for facet v1 vertex
  34939. var b1z = 0; // z partitioning index for facet v1 vertex
  34940. var b2x = 0; // X partitioning index for facet v2 vertex
  34941. var b2y = 0; // Y partitioning index for facet v2 vertex
  34942. var b2z = 0; // Z partitioning index for facet v2 vertex
  34943. var b3x = 0; // X partitioning index for facet v3 vertex
  34944. var b3y = 0; // Y partitioning index for facet v3 vertex
  34945. var b3z = 0; // Z partitioning index for facet v3 vertex
  34946. var block_idx_o = 0; // facet barycenter block index
  34947. var block_idx_v1 = 0; // v1 vertex block index
  34948. var block_idx_v2 = 0; // v2 vertex block index
  34949. var block_idx_v3 = 0; // v3 vertex block index
  34950. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34951. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34952. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34953. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34954. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34955. subSq = options.subDiv.max * options.subDiv.max;
  34956. options.facetPartitioning.length = 0;
  34957. }
  34958. // reset the normals
  34959. for (index = 0; index < positions.length; index++) {
  34960. normals[index] = 0.0;
  34961. }
  34962. // Loop : 1 indice triplet = 1 facet
  34963. var nbFaces = (indices.length / 3) | 0;
  34964. for (index = 0; index < nbFaces; index++) {
  34965. // get the indexes of the coordinates of each vertex of the facet
  34966. v1x = indices[index * 3] * 3;
  34967. v1y = v1x + 1;
  34968. v1z = v1x + 2;
  34969. v2x = indices[index * 3 + 1] * 3;
  34970. v2y = v2x + 1;
  34971. v2z = v2x + 2;
  34972. v3x = indices[index * 3 + 2] * 3;
  34973. v3y = v3x + 1;
  34974. v3z = v3x + 2;
  34975. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34976. p1p2y = positions[v1y] - positions[v2y];
  34977. p1p2z = positions[v1z] - positions[v2z];
  34978. p3p2x = positions[v3x] - positions[v2x];
  34979. p3p2y = positions[v3y] - positions[v2y];
  34980. p3p2z = positions[v3z] - positions[v2z];
  34981. // compute the face normal with the cross product
  34982. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34983. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34984. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34985. // normalize this normal and store it in the array facetData
  34986. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34987. length = (length === 0) ? 1.0 : length;
  34988. faceNormalx /= length;
  34989. faceNormaly /= length;
  34990. faceNormalz /= length;
  34991. if (computeFacetNormals && options) {
  34992. options.facetNormals[index].x = faceNormalx;
  34993. options.facetNormals[index].y = faceNormaly;
  34994. options.facetNormals[index].z = faceNormalz;
  34995. }
  34996. if (computeFacetPositions && options) {
  34997. // compute and the facet barycenter coordinates in the array facetPositions
  34998. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34999. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  35000. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  35001. }
  35002. if (computeFacetPartitioning && options) {
  35003. // store the facet indexes in arrays in the main facetPartitioning array :
  35004. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  35005. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  35006. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  35007. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  35008. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  35009. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  35010. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  35011. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  35012. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  35013. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  35014. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  35015. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  35016. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  35017. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  35018. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  35019. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  35020. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  35021. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  35022. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  35023. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  35024. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  35025. // push each facet index in each block containing the vertex
  35026. options.facetPartitioning[block_idx_v1].push(index);
  35027. if (block_idx_v2 != block_idx_v1) {
  35028. options.facetPartitioning[block_idx_v2].push(index);
  35029. }
  35030. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  35031. options.facetPartitioning[block_idx_v3].push(index);
  35032. }
  35033. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  35034. options.facetPartitioning[block_idx_o].push(index);
  35035. }
  35036. }
  35037. if (computeDepthSort && options && options.facetPositions) {
  35038. var dsf = depthSortedFacets[index];
  35039. dsf.ind = index * 3;
  35040. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  35041. }
  35042. // compute the normals anyway
  35043. normals[v1x] += faceNormalx; // accumulate all the normals per face
  35044. normals[v1y] += faceNormaly;
  35045. normals[v1z] += faceNormalz;
  35046. normals[v2x] += faceNormalx;
  35047. normals[v2y] += faceNormaly;
  35048. normals[v2z] += faceNormalz;
  35049. normals[v3x] += faceNormalx;
  35050. normals[v3y] += faceNormaly;
  35051. normals[v3z] += faceNormalz;
  35052. }
  35053. // last normalization of each normal
  35054. for (index = 0; index < normals.length / 3; index++) {
  35055. faceNormalx = normals[index * 3];
  35056. faceNormaly = normals[index * 3 + 1];
  35057. faceNormalz = normals[index * 3 + 2];
  35058. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  35059. length = (length === 0) ? 1.0 : length;
  35060. faceNormalx /= length;
  35061. faceNormaly /= length;
  35062. faceNormalz /= length;
  35063. normals[index * 3] = faceNormalx;
  35064. normals[index * 3 + 1] = faceNormaly;
  35065. normals[index * 3 + 2] = faceNormalz;
  35066. }
  35067. };
  35068. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  35069. var li = indices.length;
  35070. var ln = normals.length;
  35071. var i;
  35072. var n;
  35073. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35074. switch (sideOrientation) {
  35075. case BABYLON.Mesh.FRONTSIDE:
  35076. // nothing changed
  35077. break;
  35078. case BABYLON.Mesh.BACKSIDE:
  35079. var tmp;
  35080. // indices
  35081. for (i = 0; i < li; i += 3) {
  35082. tmp = indices[i];
  35083. indices[i] = indices[i + 2];
  35084. indices[i + 2] = tmp;
  35085. }
  35086. // normals
  35087. for (n = 0; n < ln; n++) {
  35088. normals[n] = -normals[n];
  35089. }
  35090. break;
  35091. case BABYLON.Mesh.DOUBLESIDE:
  35092. // positions
  35093. var lp = positions.length;
  35094. var l = lp / 3;
  35095. for (var p = 0; p < lp; p++) {
  35096. positions[lp + p] = positions[p];
  35097. }
  35098. // indices
  35099. for (i = 0; i < li; i += 3) {
  35100. indices[i + li] = indices[i + 2] + l;
  35101. indices[i + 1 + li] = indices[i + 1] + l;
  35102. indices[i + 2 + li] = indices[i] + l;
  35103. }
  35104. // normals
  35105. for (n = 0; n < ln; n++) {
  35106. normals[ln + n] = -normals[n];
  35107. }
  35108. // uvs
  35109. var lu = uvs.length;
  35110. var u = 0;
  35111. for (u = 0; u < lu; u++) {
  35112. uvs[u + lu] = uvs[u];
  35113. }
  35114. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35115. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35116. u = 0;
  35117. for (i = 0; i < lu / 2; i++) {
  35118. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  35119. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  35120. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  35121. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  35122. u += 2;
  35123. }
  35124. break;
  35125. }
  35126. };
  35127. /**
  35128. * Creates a new VertexData from the imported parameters.
  35129. */
  35130. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  35131. var vertexData = new VertexData();
  35132. // positions
  35133. var positions = parsedVertexData.positions;
  35134. if (positions) {
  35135. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  35136. }
  35137. // normals
  35138. var normals = parsedVertexData.normals;
  35139. if (normals) {
  35140. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  35141. }
  35142. // tangents
  35143. var tangents = parsedVertexData.tangents;
  35144. if (tangents) {
  35145. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  35146. }
  35147. // uvs
  35148. var uvs = parsedVertexData.uvs;
  35149. if (uvs) {
  35150. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  35151. }
  35152. // uv2s
  35153. var uv2s = parsedVertexData.uv2s;
  35154. if (uv2s) {
  35155. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  35156. }
  35157. // uv3s
  35158. var uv3s = parsedVertexData.uv3s;
  35159. if (uv3s) {
  35160. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  35161. }
  35162. // uv4s
  35163. var uv4s = parsedVertexData.uv4s;
  35164. if (uv4s) {
  35165. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  35166. }
  35167. // uv5s
  35168. var uv5s = parsedVertexData.uv5s;
  35169. if (uv5s) {
  35170. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  35171. }
  35172. // uv6s
  35173. var uv6s = parsedVertexData.uv6s;
  35174. if (uv6s) {
  35175. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  35176. }
  35177. // colors
  35178. var colors = parsedVertexData.colors;
  35179. if (colors) {
  35180. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  35181. }
  35182. // matricesIndices
  35183. var matricesIndices = parsedVertexData.matricesIndices;
  35184. if (matricesIndices) {
  35185. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  35186. }
  35187. // matricesWeights
  35188. var matricesWeights = parsedVertexData.matricesWeights;
  35189. if (matricesWeights) {
  35190. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  35191. }
  35192. // indices
  35193. var indices = parsedVertexData.indices;
  35194. if (indices) {
  35195. vertexData.indices = indices;
  35196. }
  35197. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  35198. };
  35199. return VertexData;
  35200. }());
  35201. BABYLON.VertexData = VertexData;
  35202. })(BABYLON || (BABYLON = {}));
  35203. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  35204. "use strict";
  35205. var BABYLON;
  35206. (function (BABYLON) {
  35207. /**
  35208. * Class used to store geometry data (vertex buffers + index buffer)
  35209. */
  35210. var Geometry = /** @class */ (function () {
  35211. /**
  35212. * Creates a new geometry
  35213. * @param id defines the unique ID
  35214. * @param scene defines the hosting scene
  35215. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  35216. * @param updatable defines if geometry must be updatable (false by default)
  35217. * @param mesh defines the mesh that will be associated with the geometry
  35218. */
  35219. function Geometry(id, scene, vertexData, updatable, mesh) {
  35220. if (updatable === void 0) { updatable = false; }
  35221. if (mesh === void 0) { mesh = null; }
  35222. /**
  35223. * Gets the delay loading state of the geometry (none by default which means not delayed)
  35224. */
  35225. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35226. this._totalVertices = 0;
  35227. this._isDisposed = false;
  35228. this._indexBufferIsUpdatable = false;
  35229. this.id = id;
  35230. this._engine = scene.getEngine();
  35231. this._meshes = [];
  35232. this._scene = scene;
  35233. //Init vertex buffer cache
  35234. this._vertexBuffers = {};
  35235. this._indices = [];
  35236. this._updatable = updatable;
  35237. // vertexData
  35238. if (vertexData) {
  35239. this.setAllVerticesData(vertexData, updatable);
  35240. }
  35241. else {
  35242. this._totalVertices = 0;
  35243. this._indices = [];
  35244. }
  35245. if (this._engine.getCaps().vertexArrayObject) {
  35246. this._vertexArrayObjects = {};
  35247. }
  35248. // applyToMesh
  35249. if (mesh) {
  35250. if (mesh.getClassName() === "LinesMesh") {
  35251. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  35252. this.updateExtend();
  35253. }
  35254. this.applyToMesh(mesh);
  35255. mesh.computeWorldMatrix(true);
  35256. }
  35257. }
  35258. Object.defineProperty(Geometry.prototype, "boundingBias", {
  35259. /**
  35260. * 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
  35261. */
  35262. get: function () {
  35263. return this._boundingBias;
  35264. },
  35265. /**
  35266. * 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
  35267. */
  35268. set: function (value) {
  35269. if (this._boundingBias && this._boundingBias.equals(value)) {
  35270. return;
  35271. }
  35272. this._boundingBias = value.clone();
  35273. this.updateBoundingInfo(true, null);
  35274. },
  35275. enumerable: true,
  35276. configurable: true
  35277. });
  35278. /**
  35279. * Static function used to attach a new empty geometry to a mesh
  35280. * @param mesh defines the mesh to attach the geometry to
  35281. * @returns the new {BABYLON.Geometry}
  35282. */
  35283. Geometry.CreateGeometryForMesh = function (mesh) {
  35284. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  35285. geometry.applyToMesh(mesh);
  35286. return geometry;
  35287. };
  35288. Object.defineProperty(Geometry.prototype, "extend", {
  35289. /**
  35290. * Gets the current extend of the geometry
  35291. */
  35292. get: function () {
  35293. return this._extend;
  35294. },
  35295. enumerable: true,
  35296. configurable: true
  35297. });
  35298. /**
  35299. * Gets the hosting scene
  35300. * @returns the hosting {BABYLON.Scene}
  35301. */
  35302. Geometry.prototype.getScene = function () {
  35303. return this._scene;
  35304. };
  35305. /**
  35306. * Gets the hosting engine
  35307. * @returns the hosting {BABYLON.Engine}
  35308. */
  35309. Geometry.prototype.getEngine = function () {
  35310. return this._engine;
  35311. };
  35312. /**
  35313. * Defines if the geometry is ready to use
  35314. * @returns true if the geometry is ready to be used
  35315. */
  35316. Geometry.prototype.isReady = function () {
  35317. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  35318. };
  35319. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  35320. /**
  35321. * Gets a value indicating that the geometry should not be serialized
  35322. */
  35323. get: function () {
  35324. for (var index = 0; index < this._meshes.length; index++) {
  35325. if (!this._meshes[index].doNotSerialize) {
  35326. return false;
  35327. }
  35328. }
  35329. return true;
  35330. },
  35331. enumerable: true,
  35332. configurable: true
  35333. });
  35334. /** @ignore */
  35335. Geometry.prototype._rebuild = function () {
  35336. if (this._vertexArrayObjects) {
  35337. this._vertexArrayObjects = {};
  35338. }
  35339. // Index buffer
  35340. if (this._meshes.length !== 0 && this._indices) {
  35341. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35342. }
  35343. // Vertex buffers
  35344. for (var key in this._vertexBuffers) {
  35345. var vertexBuffer = this._vertexBuffers[key];
  35346. vertexBuffer._rebuild();
  35347. }
  35348. };
  35349. /**
  35350. * Affects all gemetry data in one call
  35351. * @param vertexData defines the geometry data
  35352. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  35353. */
  35354. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35355. vertexData.applyToGeometry(this, updatable);
  35356. this.notifyUpdate();
  35357. };
  35358. /**
  35359. * Set specific vertex data
  35360. * @param kind defines the data kind (Position, normal, etc...)
  35361. * @param data defines the vertex data to use
  35362. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  35363. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  35364. */
  35365. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  35366. if (updatable === void 0) { updatable = false; }
  35367. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  35368. this.setVerticesBuffer(buffer);
  35369. };
  35370. /**
  35371. * Removes a specific vertex data
  35372. * @param kind defines the data kind (Position, normal, etc...)
  35373. */
  35374. Geometry.prototype.removeVerticesData = function (kind) {
  35375. if (this._vertexBuffers[kind]) {
  35376. this._vertexBuffers[kind].dispose();
  35377. delete this._vertexBuffers[kind];
  35378. }
  35379. };
  35380. /**
  35381. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  35382. * @param buffer defines the vertex buffer to use
  35383. */
  35384. Geometry.prototype.setVerticesBuffer = function (buffer) {
  35385. var kind = buffer.getKind();
  35386. if (this._vertexBuffers[kind]) {
  35387. this._vertexBuffers[kind].dispose();
  35388. }
  35389. this._vertexBuffers[kind] = buffer;
  35390. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35391. var data = buffer.getData();
  35392. var stride = buffer.getStrideSize();
  35393. this._totalVertices = data.length / stride;
  35394. this.updateExtend(data, stride);
  35395. this._resetPointsArrayCache();
  35396. var meshes = this._meshes;
  35397. var numOfMeshes = meshes.length;
  35398. for (var index = 0; index < numOfMeshes; index++) {
  35399. var mesh = meshes[index];
  35400. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35401. mesh._createGlobalSubMesh(false);
  35402. mesh.computeWorldMatrix(true);
  35403. }
  35404. }
  35405. this.notifyUpdate(kind);
  35406. if (this._vertexArrayObjects) {
  35407. this._disposeVertexArrayObjects();
  35408. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  35409. }
  35410. };
  35411. /**
  35412. * Update a specific vertex buffer
  35413. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  35414. * It will do nothing if the buffer is not updatable
  35415. * @param kind defines the data kind (Position, normal, etc...)
  35416. * @param data defines the data to use
  35417. * @param offset defines the offset in the target buffer where to store the data
  35418. */
  35419. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  35420. var vertexBuffer = this.getVertexBuffer(kind);
  35421. if (!vertexBuffer) {
  35422. return;
  35423. }
  35424. vertexBuffer.updateDirectly(data, offset);
  35425. this.notifyUpdate(kind);
  35426. };
  35427. /**
  35428. * Update a specific vertex buffer
  35429. * This function will create a new buffer if the current one is not updatable
  35430. * @param kind defines the data kind (Position, normal, etc...)
  35431. * @param data defines the data to use
  35432. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  35433. */
  35434. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  35435. if (updateExtends === void 0) { updateExtends = false; }
  35436. var vertexBuffer = this.getVertexBuffer(kind);
  35437. if (!vertexBuffer) {
  35438. return;
  35439. }
  35440. vertexBuffer.update(data);
  35441. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35442. var stride = vertexBuffer.getStrideSize();
  35443. this._totalVertices = data.length / stride;
  35444. this.updateBoundingInfo(updateExtends, data);
  35445. }
  35446. this.notifyUpdate(kind);
  35447. };
  35448. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  35449. if (updateExtends) {
  35450. this.updateExtend(data);
  35451. }
  35452. var meshes = this._meshes;
  35453. var numOfMeshes = meshes.length;
  35454. this._resetPointsArrayCache();
  35455. for (var index = 0; index < numOfMeshes; index++) {
  35456. var mesh = meshes[index];
  35457. if (updateExtends) {
  35458. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35459. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  35460. var subMesh = mesh.subMeshes[subIndex];
  35461. subMesh.refreshBoundingInfo();
  35462. }
  35463. }
  35464. }
  35465. };
  35466. /** @ignore */
  35467. Geometry.prototype._bind = function (effect, indexToBind) {
  35468. if (!effect) {
  35469. return;
  35470. }
  35471. if (indexToBind === undefined) {
  35472. indexToBind = this._indexBuffer;
  35473. }
  35474. var vbs = this.getVertexBuffers();
  35475. if (!vbs) {
  35476. return;
  35477. }
  35478. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  35479. this._engine.bindBuffers(vbs, indexToBind, effect);
  35480. return;
  35481. }
  35482. // Using VAO
  35483. if (!this._vertexArrayObjects[effect.key]) {
  35484. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  35485. }
  35486. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  35487. };
  35488. /**
  35489. * Gets total number of vertices
  35490. * @returns the total number of vertices
  35491. */
  35492. Geometry.prototype.getTotalVertices = function () {
  35493. if (!this.isReady()) {
  35494. return 0;
  35495. }
  35496. return this._totalVertices;
  35497. };
  35498. /**
  35499. * Gets a specific vertex data attached to this geometry
  35500. * @param kind defines the data kind (Position, normal, etc...)
  35501. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35502. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  35503. * @returns a float array containing vertex data
  35504. */
  35505. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  35506. var vertexBuffer = this.getVertexBuffer(kind);
  35507. if (!vertexBuffer) {
  35508. return null;
  35509. }
  35510. var orig = vertexBuffer.getData();
  35511. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  35512. return orig;
  35513. }
  35514. else {
  35515. var len = orig.length;
  35516. var copy = [];
  35517. for (var i = 0; i < len; i++) {
  35518. copy.push(orig[i]);
  35519. }
  35520. return copy;
  35521. }
  35522. };
  35523. /**
  35524. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  35525. * @param kind defines the data kind (Position, normal, etc...)
  35526. * @returns true if the vertex buffer with the specified kind is updatable
  35527. */
  35528. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  35529. var vb = this._vertexBuffers[kind];
  35530. if (!vb) {
  35531. return false;
  35532. }
  35533. return vb.isUpdatable();
  35534. };
  35535. /**
  35536. * Gets a specific vertex buffer
  35537. * @param kind defines the data kind (Position, normal, etc...)
  35538. * @returns a {BABYLON.VertexBuffer}
  35539. */
  35540. Geometry.prototype.getVertexBuffer = function (kind) {
  35541. if (!this.isReady()) {
  35542. return null;
  35543. }
  35544. return this._vertexBuffers[kind];
  35545. };
  35546. /**
  35547. * Returns all vertex buffers
  35548. * @return an object holding all vertex buffers indexed by kind
  35549. */
  35550. Geometry.prototype.getVertexBuffers = function () {
  35551. if (!this.isReady()) {
  35552. return null;
  35553. }
  35554. return this._vertexBuffers;
  35555. };
  35556. /**
  35557. * Gets a boolean indicating if specific vertex buffer is present
  35558. * @param kind defines the data kind (Position, normal, etc...)
  35559. * @returns true if data is present
  35560. */
  35561. Geometry.prototype.isVerticesDataPresent = function (kind) {
  35562. if (!this._vertexBuffers) {
  35563. if (this._delayInfo) {
  35564. return this._delayInfo.indexOf(kind) !== -1;
  35565. }
  35566. return false;
  35567. }
  35568. return this._vertexBuffers[kind] !== undefined;
  35569. };
  35570. /**
  35571. * Gets a list of all attached data kinds (Position, normal, etc...)
  35572. * @returns a list of string containing all kinds
  35573. */
  35574. Geometry.prototype.getVerticesDataKinds = function () {
  35575. var result = [];
  35576. var kind;
  35577. if (!this._vertexBuffers && this._delayInfo) {
  35578. for (kind in this._delayInfo) {
  35579. result.push(kind);
  35580. }
  35581. }
  35582. else {
  35583. for (kind in this._vertexBuffers) {
  35584. result.push(kind);
  35585. }
  35586. }
  35587. return result;
  35588. };
  35589. /**
  35590. * Update index buffer
  35591. * @param indices defines the indices to store in the index buffer
  35592. * @param offset defines the offset in the target buffer where to store the data
  35593. */
  35594. Geometry.prototype.updateIndices = function (indices, offset) {
  35595. if (!this._indexBuffer) {
  35596. return;
  35597. }
  35598. if (!this._indexBufferIsUpdatable) {
  35599. this.setIndices(indices, null, true);
  35600. }
  35601. else {
  35602. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  35603. }
  35604. };
  35605. /**
  35606. * Creates a new index buffer
  35607. * @param indices defines the indices to store in the index buffer
  35608. * @param totalVertices defines the total number of vertices (could be null)
  35609. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  35610. */
  35611. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  35612. if (totalVertices === void 0) { totalVertices = null; }
  35613. if (updatable === void 0) { updatable = false; }
  35614. if (this._indexBuffer) {
  35615. this._engine._releaseBuffer(this._indexBuffer);
  35616. }
  35617. this._disposeVertexArrayObjects();
  35618. this._indices = indices;
  35619. this._indexBufferIsUpdatable = updatable;
  35620. if (this._meshes.length !== 0 && this._indices) {
  35621. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  35622. }
  35623. if (totalVertices != undefined) {
  35624. this._totalVertices = totalVertices;
  35625. }
  35626. var meshes = this._meshes;
  35627. var numOfMeshes = meshes.length;
  35628. for (var index = 0; index < numOfMeshes; index++) {
  35629. meshes[index]._createGlobalSubMesh(true);
  35630. }
  35631. this.notifyUpdate();
  35632. };
  35633. /**
  35634. * Return the total number of indices
  35635. * @returns the total number of indices
  35636. */
  35637. Geometry.prototype.getTotalIndices = function () {
  35638. if (!this.isReady()) {
  35639. return 0;
  35640. }
  35641. return this._indices.length;
  35642. };
  35643. /**
  35644. * Gets the index buffer array
  35645. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35646. * @returns the index buffer array
  35647. */
  35648. Geometry.prototype.getIndices = function (copyWhenShared) {
  35649. if (!this.isReady()) {
  35650. return null;
  35651. }
  35652. var orig = this._indices;
  35653. if (!copyWhenShared || this._meshes.length === 1) {
  35654. return orig;
  35655. }
  35656. else {
  35657. var len = orig.length;
  35658. var copy = [];
  35659. for (var i = 0; i < len; i++) {
  35660. copy.push(orig[i]);
  35661. }
  35662. return copy;
  35663. }
  35664. };
  35665. /**
  35666. * Gets the index buffer
  35667. * @return the index buffer
  35668. */
  35669. Geometry.prototype.getIndexBuffer = function () {
  35670. if (!this.isReady()) {
  35671. return null;
  35672. }
  35673. return this._indexBuffer;
  35674. };
  35675. /** @ignore */
  35676. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35677. if (effect === void 0) { effect = null; }
  35678. if (!effect || !this._vertexArrayObjects) {
  35679. return;
  35680. }
  35681. if (this._vertexArrayObjects[effect.key]) {
  35682. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35683. delete this._vertexArrayObjects[effect.key];
  35684. }
  35685. };
  35686. /**
  35687. * Release the associated resources for a specific mesh
  35688. * @param mesh defines the source mesh
  35689. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35690. */
  35691. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35692. var meshes = this._meshes;
  35693. var index = meshes.indexOf(mesh);
  35694. if (index === -1) {
  35695. return;
  35696. }
  35697. meshes.splice(index, 1);
  35698. mesh._geometry = null;
  35699. if (meshes.length === 0 && shouldDispose) {
  35700. this.dispose();
  35701. }
  35702. };
  35703. /**
  35704. * Apply current geometry to a given mesh
  35705. * @param mesh defines the mesh to apply geometry to
  35706. */
  35707. Geometry.prototype.applyToMesh = function (mesh) {
  35708. if (mesh._geometry === this) {
  35709. return;
  35710. }
  35711. var previousGeometry = mesh._geometry;
  35712. if (previousGeometry) {
  35713. previousGeometry.releaseForMesh(mesh);
  35714. }
  35715. var meshes = this._meshes;
  35716. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35717. mesh._geometry = this;
  35718. this._scene.pushGeometry(this);
  35719. meshes.push(mesh);
  35720. if (this.isReady()) {
  35721. this._applyToMesh(mesh);
  35722. }
  35723. else {
  35724. mesh._boundingInfo = this._boundingInfo;
  35725. }
  35726. };
  35727. Geometry.prototype.updateExtend = function (data, stride) {
  35728. if (data === void 0) { data = null; }
  35729. if (!data) {
  35730. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35731. }
  35732. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35733. };
  35734. Geometry.prototype._applyToMesh = function (mesh) {
  35735. var numOfMeshes = this._meshes.length;
  35736. // vertexBuffers
  35737. for (var kind in this._vertexBuffers) {
  35738. if (numOfMeshes === 1) {
  35739. this._vertexBuffers[kind].create();
  35740. }
  35741. var buffer = this._vertexBuffers[kind].getBuffer();
  35742. if (buffer)
  35743. buffer.references = numOfMeshes;
  35744. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35745. if (!this._extend) {
  35746. this.updateExtend(this._vertexBuffers[kind].getData());
  35747. }
  35748. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35749. mesh._createGlobalSubMesh(false);
  35750. //bounding info was just created again, world matrix should be applied again.
  35751. mesh._updateBoundingInfo();
  35752. }
  35753. }
  35754. // indexBuffer
  35755. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35756. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35757. }
  35758. if (this._indexBuffer) {
  35759. this._indexBuffer.references = numOfMeshes;
  35760. }
  35761. };
  35762. Geometry.prototype.notifyUpdate = function (kind) {
  35763. if (this.onGeometryUpdated) {
  35764. this.onGeometryUpdated(this, kind);
  35765. }
  35766. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35767. var mesh = _a[_i];
  35768. mesh._markSubMeshesAsAttributesDirty();
  35769. }
  35770. };
  35771. /**
  35772. * Load the geometry if it was flagged as delay loaded
  35773. * @param scene defines the hosting scene
  35774. * @param onLoaded defines a callback called when the geometry is loaded
  35775. */
  35776. Geometry.prototype.load = function (scene, onLoaded) {
  35777. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35778. return;
  35779. }
  35780. if (this.isReady()) {
  35781. if (onLoaded) {
  35782. onLoaded();
  35783. }
  35784. return;
  35785. }
  35786. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35787. this._queueLoad(scene, onLoaded);
  35788. };
  35789. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35790. var _this = this;
  35791. if (!this.delayLoadingFile) {
  35792. return;
  35793. }
  35794. scene._addPendingData(this);
  35795. scene._loadFile(this.delayLoadingFile, function (data) {
  35796. if (!_this._delayLoadingFunction) {
  35797. return;
  35798. }
  35799. _this._delayLoadingFunction(JSON.parse(data), _this);
  35800. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35801. _this._delayInfo = [];
  35802. scene._removePendingData(_this);
  35803. var meshes = _this._meshes;
  35804. var numOfMeshes = meshes.length;
  35805. for (var index = 0; index < numOfMeshes; index++) {
  35806. _this._applyToMesh(meshes[index]);
  35807. }
  35808. if (onLoaded) {
  35809. onLoaded();
  35810. }
  35811. }, undefined, true);
  35812. };
  35813. /**
  35814. * Invert the geometry to move from a right handed system to a left handed one.
  35815. */
  35816. Geometry.prototype.toLeftHanded = function () {
  35817. // Flip faces
  35818. var tIndices = this.getIndices(false);
  35819. if (tIndices != null && tIndices.length > 0) {
  35820. for (var i = 0; i < tIndices.length; i += 3) {
  35821. var tTemp = tIndices[i + 0];
  35822. tIndices[i + 0] = tIndices[i + 2];
  35823. tIndices[i + 2] = tTemp;
  35824. }
  35825. this.setIndices(tIndices);
  35826. }
  35827. // Negate position.z
  35828. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35829. if (tPositions != null && tPositions.length > 0) {
  35830. for (var i = 0; i < tPositions.length; i += 3) {
  35831. tPositions[i + 2] = -tPositions[i + 2];
  35832. }
  35833. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35834. }
  35835. // Negate normal.z
  35836. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35837. if (tNormals != null && tNormals.length > 0) {
  35838. for (var i = 0; i < tNormals.length; i += 3) {
  35839. tNormals[i + 2] = -tNormals[i + 2];
  35840. }
  35841. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35842. }
  35843. };
  35844. // Cache
  35845. /** @ignore */
  35846. Geometry.prototype._resetPointsArrayCache = function () {
  35847. this._positions = null;
  35848. };
  35849. /** @ignore */
  35850. Geometry.prototype._generatePointsArray = function () {
  35851. if (this._positions)
  35852. return true;
  35853. this._positions = [];
  35854. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35855. if (!data) {
  35856. return false;
  35857. }
  35858. for (var index = 0; index < data.length; index += 3) {
  35859. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35860. }
  35861. return true;
  35862. };
  35863. /**
  35864. * Gets a value indicating if the geometry is disposed
  35865. * @returns true if the geometry was disposed
  35866. */
  35867. Geometry.prototype.isDisposed = function () {
  35868. return this._isDisposed;
  35869. };
  35870. Geometry.prototype._disposeVertexArrayObjects = function () {
  35871. if (this._vertexArrayObjects) {
  35872. for (var kind in this._vertexArrayObjects) {
  35873. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35874. }
  35875. this._vertexArrayObjects = {};
  35876. }
  35877. };
  35878. /**
  35879. * Free all associated resources
  35880. */
  35881. Geometry.prototype.dispose = function () {
  35882. var meshes = this._meshes;
  35883. var numOfMeshes = meshes.length;
  35884. var index;
  35885. for (index = 0; index < numOfMeshes; index++) {
  35886. this.releaseForMesh(meshes[index]);
  35887. }
  35888. this._meshes = [];
  35889. this._disposeVertexArrayObjects();
  35890. for (var kind in this._vertexBuffers) {
  35891. this._vertexBuffers[kind].dispose();
  35892. }
  35893. this._vertexBuffers = {};
  35894. this._totalVertices = 0;
  35895. if (this._indexBuffer) {
  35896. this._engine._releaseBuffer(this._indexBuffer);
  35897. }
  35898. this._indexBuffer = null;
  35899. this._indices = [];
  35900. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35901. this.delayLoadingFile = null;
  35902. this._delayLoadingFunction = null;
  35903. this._delayInfo = [];
  35904. this._boundingInfo = null;
  35905. this._scene.removeGeometry(this);
  35906. this._isDisposed = true;
  35907. };
  35908. /**
  35909. * Clone the current geometry into a new geometry
  35910. * @param id defines the unique ID of the new geometry
  35911. * @returns a new geometry object
  35912. */
  35913. Geometry.prototype.copy = function (id) {
  35914. var vertexData = new BABYLON.VertexData();
  35915. vertexData.indices = [];
  35916. var indices = this.getIndices();
  35917. if (indices) {
  35918. for (var index = 0; index < indices.length; index++) {
  35919. vertexData.indices.push(indices[index]);
  35920. }
  35921. }
  35922. var updatable = false;
  35923. var stopChecking = false;
  35924. var kind;
  35925. for (kind in this._vertexBuffers) {
  35926. // using slice() to make a copy of the array and not just reference it
  35927. var data = this.getVerticesData(kind);
  35928. if (data instanceof Float32Array) {
  35929. vertexData.set(new Float32Array(data), kind);
  35930. }
  35931. else {
  35932. vertexData.set(data.slice(0), kind);
  35933. }
  35934. if (!stopChecking) {
  35935. var vb = this.getVertexBuffer(kind);
  35936. if (vb) {
  35937. updatable = vb.isUpdatable();
  35938. stopChecking = !updatable;
  35939. }
  35940. }
  35941. }
  35942. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35943. geometry.delayLoadState = this.delayLoadState;
  35944. geometry.delayLoadingFile = this.delayLoadingFile;
  35945. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35946. for (kind in this._delayInfo) {
  35947. geometry._delayInfo = geometry._delayInfo || [];
  35948. geometry._delayInfo.push(kind);
  35949. }
  35950. // Bounding info
  35951. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35952. return geometry;
  35953. };
  35954. /**
  35955. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35956. * @return a JSON representation of the current geometry data (without the vertices data)
  35957. */
  35958. Geometry.prototype.serialize = function () {
  35959. var serializationObject = {};
  35960. serializationObject.id = this.id;
  35961. serializationObject.updatable = this._updatable;
  35962. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35963. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35964. }
  35965. return serializationObject;
  35966. };
  35967. Geometry.prototype.toNumberArray = function (origin) {
  35968. if (Array.isArray(origin)) {
  35969. return origin;
  35970. }
  35971. else {
  35972. return Array.prototype.slice.call(origin);
  35973. }
  35974. };
  35975. /**
  35976. * Serialize all vertices data into a JSON oject
  35977. * @returns a JSON representation of the current geometry data
  35978. */
  35979. Geometry.prototype.serializeVerticeData = function () {
  35980. var serializationObject = this.serialize();
  35981. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35982. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35983. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35984. serializationObject.positions._updatable = true;
  35985. }
  35986. }
  35987. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35988. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35989. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35990. serializationObject.normals._updatable = true;
  35991. }
  35992. }
  35993. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35994. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35995. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35996. serializationObject.tangets._updatable = true;
  35997. }
  35998. }
  35999. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36000. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  36001. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  36002. serializationObject.uvs._updatable = true;
  36003. }
  36004. }
  36005. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36006. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  36007. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  36008. serializationObject.uv2s._updatable = true;
  36009. }
  36010. }
  36011. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36012. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  36013. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  36014. serializationObject.uv3s._updatable = true;
  36015. }
  36016. }
  36017. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36018. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  36019. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  36020. serializationObject.uv4s._updatable = true;
  36021. }
  36022. }
  36023. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36024. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  36025. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  36026. serializationObject.uv5s._updatable = true;
  36027. }
  36028. }
  36029. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36030. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  36031. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  36032. serializationObject.uv6s._updatable = true;
  36033. }
  36034. }
  36035. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36036. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  36037. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  36038. serializationObject.colors._updatable = true;
  36039. }
  36040. }
  36041. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36042. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  36043. serializationObject.matricesIndices._isExpanded = true;
  36044. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36045. serializationObject.matricesIndices._updatable = true;
  36046. }
  36047. }
  36048. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36049. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  36050. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36051. serializationObject.matricesWeights._updatable = true;
  36052. }
  36053. }
  36054. serializationObject.indices = this.toNumberArray(this.getIndices());
  36055. return serializationObject;
  36056. };
  36057. // Statics
  36058. /**
  36059. * Extracts a clone of a mesh geometry
  36060. * @param mesh defines the source mesh
  36061. * @param id defines the unique ID of the new geometry object
  36062. * @returns the new geometry object
  36063. */
  36064. Geometry.ExtractFromMesh = function (mesh, id) {
  36065. var geometry = mesh._geometry;
  36066. if (!geometry) {
  36067. return null;
  36068. }
  36069. return geometry.copy(id);
  36070. };
  36071. /**
  36072. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  36073. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  36074. * Be aware Math.random() could cause collisions, but:
  36075. * "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"
  36076. * @returns a string containing a new GUID
  36077. */
  36078. Geometry.RandomId = function () {
  36079. return BABYLON.Tools.RandomId();
  36080. };
  36081. /** @ignore */
  36082. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  36083. var scene = mesh.getScene();
  36084. // Geometry
  36085. var geometryId = parsedGeometry.geometryId;
  36086. if (geometryId) {
  36087. var geometry = scene.getGeometryByID(geometryId);
  36088. if (geometry) {
  36089. geometry.applyToMesh(mesh);
  36090. }
  36091. }
  36092. else if (parsedGeometry instanceof ArrayBuffer) {
  36093. var binaryInfo = mesh._binaryInfo;
  36094. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  36095. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  36096. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  36097. }
  36098. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  36099. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  36100. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  36101. }
  36102. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  36103. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  36104. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  36105. }
  36106. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  36107. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  36108. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  36109. }
  36110. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  36111. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  36112. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  36113. }
  36114. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  36115. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  36116. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  36117. }
  36118. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  36119. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  36120. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  36121. }
  36122. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  36123. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  36124. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  36125. }
  36126. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  36127. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  36128. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  36129. }
  36130. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  36131. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  36132. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  36133. }
  36134. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  36135. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  36136. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  36137. }
  36138. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  36139. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  36140. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  36141. }
  36142. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  36143. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  36144. mesh.setIndices(indicesData, null);
  36145. }
  36146. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  36147. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  36148. mesh.subMeshes = [];
  36149. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  36150. var materialIndex = subMeshesData[(i * 5) + 0];
  36151. var verticesStart = subMeshesData[(i * 5) + 1];
  36152. var verticesCount = subMeshesData[(i * 5) + 2];
  36153. var indexStart = subMeshesData[(i * 5) + 3];
  36154. var indexCount = subMeshesData[(i * 5) + 4];
  36155. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  36156. }
  36157. }
  36158. }
  36159. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  36160. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  36161. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  36162. if (parsedGeometry.tangents) {
  36163. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  36164. }
  36165. if (parsedGeometry.uvs) {
  36166. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  36167. }
  36168. if (parsedGeometry.uvs2) {
  36169. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  36170. }
  36171. if (parsedGeometry.uvs3) {
  36172. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  36173. }
  36174. if (parsedGeometry.uvs4) {
  36175. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  36176. }
  36177. if (parsedGeometry.uvs5) {
  36178. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  36179. }
  36180. if (parsedGeometry.uvs6) {
  36181. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  36182. }
  36183. if (parsedGeometry.colors) {
  36184. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  36185. }
  36186. if (parsedGeometry.matricesIndices) {
  36187. if (!parsedGeometry.matricesIndices._isExpanded) {
  36188. var floatIndices = [];
  36189. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  36190. var matricesIndex = parsedGeometry.matricesIndices[i];
  36191. floatIndices.push(matricesIndex & 0x000000FF);
  36192. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36193. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36194. floatIndices.push(matricesIndex >> 24);
  36195. }
  36196. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  36197. }
  36198. else {
  36199. delete parsedGeometry.matricesIndices._isExpanded;
  36200. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  36201. }
  36202. }
  36203. if (parsedGeometry.matricesIndicesExtra) {
  36204. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  36205. var floatIndices = [];
  36206. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  36207. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  36208. floatIndices.push(matricesIndex & 0x000000FF);
  36209. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36210. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36211. floatIndices.push(matricesIndex >> 24);
  36212. }
  36213. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  36214. }
  36215. else {
  36216. delete parsedGeometry.matricesIndices._isExpanded;
  36217. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  36218. }
  36219. }
  36220. if (parsedGeometry.matricesWeights) {
  36221. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  36222. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  36223. }
  36224. if (parsedGeometry.matricesWeightsExtra) {
  36225. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  36226. }
  36227. mesh.setIndices(parsedGeometry.indices, null);
  36228. }
  36229. // SubMeshes
  36230. if (parsedGeometry.subMeshes) {
  36231. mesh.subMeshes = [];
  36232. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  36233. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  36234. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  36235. }
  36236. }
  36237. // Flat shading
  36238. if (mesh._shouldGenerateFlatShading) {
  36239. mesh.convertToFlatShadedMesh();
  36240. delete mesh._shouldGenerateFlatShading;
  36241. }
  36242. // Update
  36243. mesh.computeWorldMatrix(true);
  36244. // Octree
  36245. var sceneOctree = scene.selectionOctree;
  36246. if (sceneOctree !== undefined && sceneOctree !== null) {
  36247. sceneOctree.addMesh(mesh);
  36248. }
  36249. };
  36250. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  36251. var epsilon = 1e-3;
  36252. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  36253. return;
  36254. }
  36255. var noInfluenceBoneIndex = 0.0;
  36256. if (parsedGeometry.skeletonId > -1) {
  36257. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  36258. if (!skeleton) {
  36259. return;
  36260. }
  36261. noInfluenceBoneIndex = skeleton.bones.length;
  36262. }
  36263. else {
  36264. return;
  36265. }
  36266. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  36267. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36268. var matricesWeights = parsedGeometry.matricesWeights;
  36269. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  36270. var influencers = parsedGeometry.numBoneInfluencer;
  36271. var size = matricesWeights.length;
  36272. for (var i = 0; i < size; i += 4) {
  36273. var weight = 0.0;
  36274. var firstZeroWeight = -1;
  36275. for (var j = 0; j < 4; j++) {
  36276. var w = matricesWeights[i + j];
  36277. weight += w;
  36278. if (w < epsilon && firstZeroWeight < 0) {
  36279. firstZeroWeight = j;
  36280. }
  36281. }
  36282. if (matricesWeightsExtra) {
  36283. for (var j = 0; j < 4; j++) {
  36284. var w = matricesWeightsExtra[i + j];
  36285. weight += w;
  36286. if (w < epsilon && firstZeroWeight < 0) {
  36287. firstZeroWeight = j + 4;
  36288. }
  36289. }
  36290. }
  36291. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  36292. firstZeroWeight = influencers - 1;
  36293. }
  36294. if (weight > epsilon) {
  36295. var mweight = 1.0 / weight;
  36296. for (var j = 0; j < 4; j++) {
  36297. matricesWeights[i + j] *= mweight;
  36298. }
  36299. if (matricesWeightsExtra) {
  36300. for (var j = 0; j < 4; j++) {
  36301. matricesWeightsExtra[i + j] *= mweight;
  36302. }
  36303. }
  36304. }
  36305. else {
  36306. if (firstZeroWeight >= 4) {
  36307. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  36308. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  36309. }
  36310. else {
  36311. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  36312. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  36313. }
  36314. }
  36315. }
  36316. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  36317. if (parsedGeometry.matricesWeightsExtra) {
  36318. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  36319. }
  36320. };
  36321. /**
  36322. * Create a new geometry from persisted data (Using .babylon file format)
  36323. * @param parsedVertexData defines the persisted data
  36324. * @param scene defines the hosting scene
  36325. * @param rootUrl defines the root url to use to load assets (like delayed data)
  36326. * @returns the new geometry object
  36327. */
  36328. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  36329. if (scene.getGeometryByID(parsedVertexData.id)) {
  36330. return null; // null since geometry could be something else than a box...
  36331. }
  36332. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  36333. if (BABYLON.Tags) {
  36334. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  36335. }
  36336. if (parsedVertexData.delayLoadingFile) {
  36337. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36338. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  36339. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  36340. geometry._delayInfo = [];
  36341. if (parsedVertexData.hasUVs) {
  36342. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  36343. }
  36344. if (parsedVertexData.hasUVs2) {
  36345. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  36346. }
  36347. if (parsedVertexData.hasUVs3) {
  36348. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  36349. }
  36350. if (parsedVertexData.hasUVs4) {
  36351. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  36352. }
  36353. if (parsedVertexData.hasUVs5) {
  36354. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  36355. }
  36356. if (parsedVertexData.hasUVs6) {
  36357. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  36358. }
  36359. if (parsedVertexData.hasColors) {
  36360. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  36361. }
  36362. if (parsedVertexData.hasMatricesIndices) {
  36363. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36364. }
  36365. if (parsedVertexData.hasMatricesWeights) {
  36366. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36367. }
  36368. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  36369. }
  36370. else {
  36371. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  36372. }
  36373. scene.pushGeometry(geometry, true);
  36374. return geometry;
  36375. };
  36376. return Geometry;
  36377. }());
  36378. BABYLON.Geometry = Geometry;
  36379. // Primitives
  36380. /// Abstract class
  36381. /**
  36382. * Abstract class used to provide common services for all typed geometries
  36383. */
  36384. var _PrimitiveGeometry = /** @class */ (function (_super) {
  36385. __extends(_PrimitiveGeometry, _super);
  36386. /**
  36387. * Creates a new typed geometry
  36388. * @param id defines the unique ID of the geometry
  36389. * @param scene defines the hosting scene
  36390. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36391. * @param mesh defines the hosting mesh (can be null)
  36392. */
  36393. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  36394. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  36395. if (mesh === void 0) { mesh = null; }
  36396. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  36397. _this._canBeRegenerated = _canBeRegenerated;
  36398. _this._beingRegenerated = true;
  36399. _this.regenerate();
  36400. _this._beingRegenerated = false;
  36401. return _this;
  36402. }
  36403. /**
  36404. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  36405. * @returns true if the geometry can be regenerated
  36406. */
  36407. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  36408. return this._canBeRegenerated;
  36409. };
  36410. /**
  36411. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  36412. */
  36413. _PrimitiveGeometry.prototype.regenerate = function () {
  36414. if (!this._canBeRegenerated) {
  36415. return;
  36416. }
  36417. this._beingRegenerated = true;
  36418. this.setAllVerticesData(this._regenerateVertexData(), false);
  36419. this._beingRegenerated = false;
  36420. };
  36421. /**
  36422. * Clone the geometry
  36423. * @param id defines the unique ID of the new geometry
  36424. * @returns the new geometry
  36425. */
  36426. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  36427. return _super.prototype.copy.call(this, id);
  36428. };
  36429. // overrides
  36430. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  36431. if (!this._beingRegenerated) {
  36432. return;
  36433. }
  36434. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  36435. };
  36436. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  36437. if (!this._beingRegenerated) {
  36438. return;
  36439. }
  36440. _super.prototype.setVerticesData.call(this, kind, data, false);
  36441. };
  36442. // to override
  36443. /** @ignore */
  36444. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  36445. throw new Error("Abstract method");
  36446. };
  36447. _PrimitiveGeometry.prototype.copy = function (id) {
  36448. throw new Error("Must be overriden in sub-classes.");
  36449. };
  36450. _PrimitiveGeometry.prototype.serialize = function () {
  36451. var serializationObject = _super.prototype.serialize.call(this);
  36452. serializationObject.canBeRegenerated = this.canBeRegenerated();
  36453. return serializationObject;
  36454. };
  36455. return _PrimitiveGeometry;
  36456. }(Geometry));
  36457. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  36458. /**
  36459. * Creates a ribbon geometry
  36460. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  36461. */
  36462. var RibbonGeometry = /** @class */ (function (_super) {
  36463. __extends(RibbonGeometry, _super);
  36464. /**
  36465. * Creates a ribbon geometry
  36466. * @param id defines the unique ID of the geometry
  36467. * @param scene defines the hosting scene
  36468. * @param pathArray defines the array of paths to use
  36469. * @param closeArray defines if the last path and the first path must be joined
  36470. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  36471. * @param offset defines the offset between points
  36472. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36473. * @param mesh defines the hosting mesh (can be null)
  36474. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36475. */
  36476. function RibbonGeometry(id, scene,
  36477. /**
  36478. * Defines the array of paths to use
  36479. */
  36480. pathArray,
  36481. /**
  36482. * Defines if the last and first points of each path in your pathArray must be joined
  36483. */
  36484. closeArray,
  36485. /**
  36486. * Defines if the last and first points of each path in your pathArray must be joined
  36487. */
  36488. closePath,
  36489. /**
  36490. * Defines the offset between points
  36491. */
  36492. offset, canBeRegenerated, mesh,
  36493. /**
  36494. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36495. */
  36496. side) {
  36497. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36498. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36499. _this.pathArray = pathArray;
  36500. _this.closeArray = closeArray;
  36501. _this.closePath = closePath;
  36502. _this.offset = offset;
  36503. _this.side = side;
  36504. return _this;
  36505. }
  36506. /** @ignore */
  36507. RibbonGeometry.prototype._regenerateVertexData = function () {
  36508. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36509. };
  36510. RibbonGeometry.prototype.copy = function (id) {
  36511. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  36512. };
  36513. return RibbonGeometry;
  36514. }(_PrimitiveGeometry));
  36515. BABYLON.RibbonGeometry = RibbonGeometry;
  36516. /**
  36517. * Creates a box geometry
  36518. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  36519. */
  36520. var BoxGeometry = /** @class */ (function (_super) {
  36521. __extends(BoxGeometry, _super);
  36522. /**
  36523. * Creates a box geometry
  36524. * @param id defines the unique ID of the geometry
  36525. * @param scene defines the hosting scene
  36526. * @param size defines the zise of the box (width, height and depth are the same)
  36527. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36528. * @param mesh defines the hosting mesh (can be null)
  36529. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36530. */
  36531. function BoxGeometry(id, scene,
  36532. /**
  36533. * Defines the zise of the box (width, height and depth are the same)
  36534. */
  36535. size, canBeRegenerated, mesh,
  36536. /**
  36537. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36538. */
  36539. side) {
  36540. if (mesh === void 0) { mesh = null; }
  36541. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36542. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36543. _this.size = size;
  36544. _this.side = side;
  36545. return _this;
  36546. }
  36547. BoxGeometry.prototype._regenerateVertexData = function () {
  36548. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36549. };
  36550. BoxGeometry.prototype.copy = function (id) {
  36551. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  36552. };
  36553. BoxGeometry.prototype.serialize = function () {
  36554. var serializationObject = _super.prototype.serialize.call(this);
  36555. serializationObject.size = this.size;
  36556. return serializationObject;
  36557. };
  36558. BoxGeometry.Parse = function (parsedBox, scene) {
  36559. if (scene.getGeometryByID(parsedBox.id)) {
  36560. return null; // null since geometry could be something else than a box...
  36561. }
  36562. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36563. if (BABYLON.Tags) {
  36564. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36565. }
  36566. scene.pushGeometry(box, true);
  36567. return box;
  36568. };
  36569. return BoxGeometry;
  36570. }(_PrimitiveGeometry));
  36571. BABYLON.BoxGeometry = BoxGeometry;
  36572. /**
  36573. * Creates a sphere geometry
  36574. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  36575. */
  36576. var SphereGeometry = /** @class */ (function (_super) {
  36577. __extends(SphereGeometry, _super);
  36578. /**
  36579. * Create a new sphere geometry
  36580. * @param id defines the unique ID of the geometry
  36581. * @param scene defines the hosting scene
  36582. * @param segments defines the number of segments to use to create the sphere
  36583. * @param diameter defines the diameter of the sphere
  36584. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36585. * @param mesh defines the hosting mesh (can be null)
  36586. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36587. */
  36588. function SphereGeometry(id, scene,
  36589. /**
  36590. * Defines the number of segments to use to create the sphere
  36591. */
  36592. segments,
  36593. /**
  36594. * Defines the diameter of the sphere
  36595. */
  36596. diameter, canBeRegenerated, mesh,
  36597. /**
  36598. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36599. */
  36600. side) {
  36601. if (mesh === void 0) { mesh = null; }
  36602. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36603. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36604. _this.segments = segments;
  36605. _this.diameter = diameter;
  36606. _this.side = side;
  36607. return _this;
  36608. }
  36609. SphereGeometry.prototype._regenerateVertexData = function () {
  36610. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36611. };
  36612. SphereGeometry.prototype.copy = function (id) {
  36613. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36614. };
  36615. SphereGeometry.prototype.serialize = function () {
  36616. var serializationObject = _super.prototype.serialize.call(this);
  36617. serializationObject.segments = this.segments;
  36618. serializationObject.diameter = this.diameter;
  36619. return serializationObject;
  36620. };
  36621. SphereGeometry.Parse = function (parsedSphere, scene) {
  36622. if (scene.getGeometryByID(parsedSphere.id)) {
  36623. return null; // null since geometry could be something else than a sphere...
  36624. }
  36625. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36626. if (BABYLON.Tags) {
  36627. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36628. }
  36629. scene.pushGeometry(sphere, true);
  36630. return sphere;
  36631. };
  36632. return SphereGeometry;
  36633. }(_PrimitiveGeometry));
  36634. BABYLON.SphereGeometry = SphereGeometry;
  36635. /**
  36636. * Creates a disc geometry
  36637. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  36638. */
  36639. var DiscGeometry = /** @class */ (function (_super) {
  36640. __extends(DiscGeometry, _super);
  36641. /**
  36642. * Creates a new disc geometry
  36643. * @param id defines the unique ID of the geometry
  36644. * @param scene defines the hosting scene
  36645. * @param radius defines the radius of the disc
  36646. * @param tessellation defines the tesselation factor to apply to the disc
  36647. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36648. * @param mesh defines the hosting mesh (can be null)
  36649. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36650. */
  36651. function DiscGeometry(id, scene,
  36652. /**
  36653. * Defines the radius of the disc
  36654. */
  36655. radius,
  36656. /**
  36657. * Defines the tesselation factor to apply to the disc
  36658. */
  36659. tessellation, canBeRegenerated, mesh,
  36660. /**
  36661. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36662. */
  36663. side) {
  36664. if (mesh === void 0) { mesh = null; }
  36665. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36666. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36667. _this.radius = radius;
  36668. _this.tessellation = tessellation;
  36669. _this.side = side;
  36670. return _this;
  36671. }
  36672. DiscGeometry.prototype._regenerateVertexData = function () {
  36673. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36674. };
  36675. DiscGeometry.prototype.copy = function (id) {
  36676. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36677. };
  36678. return DiscGeometry;
  36679. }(_PrimitiveGeometry));
  36680. BABYLON.DiscGeometry = DiscGeometry;
  36681. /**
  36682. * Creates a new cylinder geometry
  36683. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36684. */
  36685. var CylinderGeometry = /** @class */ (function (_super) {
  36686. __extends(CylinderGeometry, _super);
  36687. /**
  36688. * Creates a new cylinder geometry
  36689. * @param id defines the unique ID of the geometry
  36690. * @param scene defines the hosting scene
  36691. * @param height defines the height of the cylinder
  36692. * @param diameterTop defines the diameter of the cylinder's top cap
  36693. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36694. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36695. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36696. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36697. * @param mesh defines the hosting mesh (can be null)
  36698. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36699. */
  36700. function CylinderGeometry(id, scene,
  36701. /**
  36702. * Defines the height of the cylinder
  36703. */
  36704. height,
  36705. /**
  36706. * Defines the diameter of the cylinder's top cap
  36707. */
  36708. diameterTop,
  36709. /**
  36710. * Defines the diameter of the cylinder's bottom cap
  36711. */
  36712. diameterBottom,
  36713. /**
  36714. * Defines the tessellation factor to apply to the cylinder
  36715. */
  36716. tessellation,
  36717. /**
  36718. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36719. */
  36720. subdivisions, canBeRegenerated, mesh,
  36721. /**
  36722. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36723. */
  36724. side) {
  36725. if (subdivisions === void 0) { subdivisions = 1; }
  36726. if (mesh === void 0) { mesh = null; }
  36727. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36728. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36729. _this.height = height;
  36730. _this.diameterTop = diameterTop;
  36731. _this.diameterBottom = diameterBottom;
  36732. _this.tessellation = tessellation;
  36733. _this.subdivisions = subdivisions;
  36734. _this.side = side;
  36735. return _this;
  36736. }
  36737. CylinderGeometry.prototype._regenerateVertexData = function () {
  36738. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36739. };
  36740. CylinderGeometry.prototype.copy = function (id) {
  36741. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36742. };
  36743. CylinderGeometry.prototype.serialize = function () {
  36744. var serializationObject = _super.prototype.serialize.call(this);
  36745. serializationObject.height = this.height;
  36746. serializationObject.diameterTop = this.diameterTop;
  36747. serializationObject.diameterBottom = this.diameterBottom;
  36748. serializationObject.tessellation = this.tessellation;
  36749. return serializationObject;
  36750. };
  36751. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36752. if (scene.getGeometryByID(parsedCylinder.id)) {
  36753. return null; // null since geometry could be something else than a cylinder...
  36754. }
  36755. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36756. if (BABYLON.Tags) {
  36757. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36758. }
  36759. scene.pushGeometry(cylinder, true);
  36760. return cylinder;
  36761. };
  36762. return CylinderGeometry;
  36763. }(_PrimitiveGeometry));
  36764. BABYLON.CylinderGeometry = CylinderGeometry;
  36765. /**
  36766. * Creates a new torus geometry
  36767. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36768. */
  36769. var TorusGeometry = /** @class */ (function (_super) {
  36770. __extends(TorusGeometry, _super);
  36771. /**
  36772. * Creates a new torus geometry
  36773. * @param id defines the unique ID of the geometry
  36774. * @param scene defines the hosting scene
  36775. * @param diameter defines the diameter of the torus
  36776. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36777. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36778. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36779. * @param mesh defines the hosting mesh (can be null)
  36780. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36781. */
  36782. function TorusGeometry(id, scene,
  36783. /**
  36784. * Defines the diameter of the torus
  36785. */
  36786. diameter,
  36787. /**
  36788. * Defines the thickness of the torus (ie. internal diameter)
  36789. */
  36790. thickness,
  36791. /**
  36792. * Defines the tesselation factor to apply to the torus
  36793. */
  36794. tessellation, canBeRegenerated, mesh,
  36795. /**
  36796. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36797. */
  36798. side) {
  36799. if (mesh === void 0) { mesh = null; }
  36800. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36801. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36802. _this.diameter = diameter;
  36803. _this.thickness = thickness;
  36804. _this.tessellation = tessellation;
  36805. _this.side = side;
  36806. return _this;
  36807. }
  36808. TorusGeometry.prototype._regenerateVertexData = function () {
  36809. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36810. };
  36811. TorusGeometry.prototype.copy = function (id) {
  36812. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36813. };
  36814. TorusGeometry.prototype.serialize = function () {
  36815. var serializationObject = _super.prototype.serialize.call(this);
  36816. serializationObject.diameter = this.diameter;
  36817. serializationObject.thickness = this.thickness;
  36818. serializationObject.tessellation = this.tessellation;
  36819. return serializationObject;
  36820. };
  36821. TorusGeometry.Parse = function (parsedTorus, scene) {
  36822. if (scene.getGeometryByID(parsedTorus.id)) {
  36823. return null; // null since geometry could be something else than a torus...
  36824. }
  36825. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36826. if (BABYLON.Tags) {
  36827. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36828. }
  36829. scene.pushGeometry(torus, true);
  36830. return torus;
  36831. };
  36832. return TorusGeometry;
  36833. }(_PrimitiveGeometry));
  36834. BABYLON.TorusGeometry = TorusGeometry;
  36835. /**
  36836. * Creates a new ground geometry
  36837. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36838. */
  36839. var GroundGeometry = /** @class */ (function (_super) {
  36840. __extends(GroundGeometry, _super);
  36841. /**
  36842. * Creates a new ground geometry
  36843. * @param id defines the unique ID of the geometry
  36844. * @param scene defines the hosting scene
  36845. * @param width defines the width of the ground
  36846. * @param height defines the height of the ground
  36847. * @param subdivisions defines the subdivisions to apply to the ground
  36848. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36849. * @param mesh defines the hosting mesh (can be null)
  36850. */
  36851. function GroundGeometry(id, scene,
  36852. /**
  36853. * Defines the width of the ground
  36854. */
  36855. width,
  36856. /**
  36857. * Defines the height of the ground
  36858. */
  36859. height,
  36860. /**
  36861. * Defines the subdivisions to apply to the ground
  36862. */
  36863. subdivisions, canBeRegenerated, mesh) {
  36864. if (mesh === void 0) { mesh = null; }
  36865. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36866. _this.width = width;
  36867. _this.height = height;
  36868. _this.subdivisions = subdivisions;
  36869. return _this;
  36870. }
  36871. GroundGeometry.prototype._regenerateVertexData = function () {
  36872. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36873. };
  36874. GroundGeometry.prototype.copy = function (id) {
  36875. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36876. };
  36877. GroundGeometry.prototype.serialize = function () {
  36878. var serializationObject = _super.prototype.serialize.call(this);
  36879. serializationObject.width = this.width;
  36880. serializationObject.height = this.height;
  36881. serializationObject.subdivisions = this.subdivisions;
  36882. return serializationObject;
  36883. };
  36884. GroundGeometry.Parse = function (parsedGround, scene) {
  36885. if (scene.getGeometryByID(parsedGround.id)) {
  36886. return null; // null since geometry could be something else than a ground...
  36887. }
  36888. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36889. if (BABYLON.Tags) {
  36890. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36891. }
  36892. scene.pushGeometry(ground, true);
  36893. return ground;
  36894. };
  36895. return GroundGeometry;
  36896. }(_PrimitiveGeometry));
  36897. BABYLON.GroundGeometry = GroundGeometry;
  36898. /**
  36899. * Creates a tiled ground geometry
  36900. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36901. */
  36902. var TiledGroundGeometry = /** @class */ (function (_super) {
  36903. __extends(TiledGroundGeometry, _super);
  36904. /**
  36905. * Creates a tiled ground geometry
  36906. * @param id defines the unique ID of the geometry
  36907. * @param scene defines the hosting scene
  36908. * @param xmin defines the minimum value on X axis
  36909. * @param zmin defines the minimum value on Z axis
  36910. * @param xmax defines the maximum value on X axis
  36911. * @param zmax defines the maximum value on Z axis
  36912. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36913. * @param precision defines the precision to use when computing the tiles
  36914. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36915. * @param mesh defines the hosting mesh (can be null)
  36916. */
  36917. function TiledGroundGeometry(id, scene,
  36918. /**
  36919. * Defines the minimum value on X axis
  36920. */
  36921. xmin,
  36922. /**
  36923. * Defines the minimum value on Z axis
  36924. */
  36925. zmin,
  36926. /**
  36927. * Defines the maximum value on X axis
  36928. */
  36929. xmax,
  36930. /**
  36931. * Defines the maximum value on Z axis
  36932. */
  36933. zmax,
  36934. /**
  36935. * Defines the subdivisions to apply to the ground
  36936. */
  36937. subdivisions,
  36938. /**
  36939. * Defines the precision to use when computing the tiles
  36940. */
  36941. precision, canBeRegenerated, mesh) {
  36942. if (mesh === void 0) { mesh = null; }
  36943. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36944. _this.xmin = xmin;
  36945. _this.zmin = zmin;
  36946. _this.xmax = xmax;
  36947. _this.zmax = zmax;
  36948. _this.subdivisions = subdivisions;
  36949. _this.precision = precision;
  36950. return _this;
  36951. }
  36952. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36953. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36954. };
  36955. TiledGroundGeometry.prototype.copy = function (id) {
  36956. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36957. };
  36958. return TiledGroundGeometry;
  36959. }(_PrimitiveGeometry));
  36960. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36961. /**
  36962. * Creates a plane geometry
  36963. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36964. */
  36965. var PlaneGeometry = /** @class */ (function (_super) {
  36966. __extends(PlaneGeometry, _super);
  36967. /**
  36968. * Creates a plane geometry
  36969. * @param id defines the unique ID of the geometry
  36970. * @param scene defines the hosting scene
  36971. * @param size defines the size of the plane (width === height)
  36972. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36973. * @param mesh defines the hosting mesh (can be null)
  36974. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36975. */
  36976. function PlaneGeometry(id, scene,
  36977. /**
  36978. * Defines the size of the plane (width === height)
  36979. */
  36980. size, canBeRegenerated, mesh,
  36981. /**
  36982. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36983. */
  36984. side) {
  36985. if (mesh === void 0) { mesh = null; }
  36986. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36987. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36988. _this.size = size;
  36989. _this.side = side;
  36990. return _this;
  36991. }
  36992. PlaneGeometry.prototype._regenerateVertexData = function () {
  36993. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36994. };
  36995. PlaneGeometry.prototype.copy = function (id) {
  36996. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36997. };
  36998. PlaneGeometry.prototype.serialize = function () {
  36999. var serializationObject = _super.prototype.serialize.call(this);
  37000. serializationObject.size = this.size;
  37001. return serializationObject;
  37002. };
  37003. PlaneGeometry.Parse = function (parsedPlane, scene) {
  37004. if (scene.getGeometryByID(parsedPlane.id)) {
  37005. return null; // null since geometry could be something else than a ground...
  37006. }
  37007. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  37008. if (BABYLON.Tags) {
  37009. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  37010. }
  37011. scene.pushGeometry(plane, true);
  37012. return plane;
  37013. };
  37014. return PlaneGeometry;
  37015. }(_PrimitiveGeometry));
  37016. BABYLON.PlaneGeometry = PlaneGeometry;
  37017. /**
  37018. * Creates a torus knot geometry
  37019. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  37020. */
  37021. var TorusKnotGeometry = /** @class */ (function (_super) {
  37022. __extends(TorusKnotGeometry, _super);
  37023. /**
  37024. * Creates a torus knot geometry
  37025. * @param id defines the unique ID of the geometry
  37026. * @param scene defines the hosting scene
  37027. * @param radius defines the radius of the torus knot
  37028. * @param tube defines the thickness of the torus knot tube
  37029. * @param radialSegments defines the number of radial segments
  37030. * @param tubularSegments defines the number of tubular segments
  37031. * @param p defines the first number of windings
  37032. * @param q defines the second number of windings
  37033. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  37034. * @param mesh defines the hosting mesh (can be null)
  37035. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37036. */
  37037. function TorusKnotGeometry(id, scene,
  37038. /**
  37039. * Defines the radius of the torus knot
  37040. */
  37041. radius,
  37042. /**
  37043. * Defines the thickness of the torus knot tube
  37044. */
  37045. tube,
  37046. /**
  37047. * Defines the number of radial segments
  37048. */
  37049. radialSegments,
  37050. /**
  37051. * Defines the number of tubular segments
  37052. */
  37053. tubularSegments,
  37054. /**
  37055. * Defines the first number of windings
  37056. */
  37057. p,
  37058. /**
  37059. * Defines the second number of windings
  37060. */
  37061. q, canBeRegenerated, mesh,
  37062. /**
  37063. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37064. */
  37065. side) {
  37066. if (mesh === void 0) { mesh = null; }
  37067. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37068. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37069. _this.radius = radius;
  37070. _this.tube = tube;
  37071. _this.radialSegments = radialSegments;
  37072. _this.tubularSegments = tubularSegments;
  37073. _this.p = p;
  37074. _this.q = q;
  37075. _this.side = side;
  37076. return _this;
  37077. }
  37078. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  37079. 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 });
  37080. };
  37081. TorusKnotGeometry.prototype.copy = function (id) {
  37082. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  37083. };
  37084. TorusKnotGeometry.prototype.serialize = function () {
  37085. var serializationObject = _super.prototype.serialize.call(this);
  37086. serializationObject.radius = this.radius;
  37087. serializationObject.tube = this.tube;
  37088. serializationObject.radialSegments = this.radialSegments;
  37089. serializationObject.tubularSegments = this.tubularSegments;
  37090. serializationObject.p = this.p;
  37091. serializationObject.q = this.q;
  37092. return serializationObject;
  37093. };
  37094. ;
  37095. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  37096. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  37097. return null; // null since geometry could be something else than a ground...
  37098. }
  37099. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  37100. if (BABYLON.Tags) {
  37101. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  37102. }
  37103. scene.pushGeometry(torusKnot, true);
  37104. return torusKnot;
  37105. };
  37106. return TorusKnotGeometry;
  37107. }(_PrimitiveGeometry));
  37108. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  37109. //}
  37110. })(BABYLON || (BABYLON = {}));
  37111. //# sourceMappingURL=babylon.geometry.js.map
  37112. "use strict";
  37113. var BABYLON;
  37114. (function (BABYLON) {
  37115. /**
  37116. * PostProcessManager is used to manage one or more post processes or post process pipelines
  37117. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  37118. */
  37119. var PostProcessManager = /** @class */ (function () {
  37120. /**
  37121. * Creates a new instance of @see PostProcess
  37122. * @param scene The scene that the post process is associated with.
  37123. */
  37124. function PostProcessManager(scene) {
  37125. this._vertexBuffers = {};
  37126. this._scene = scene;
  37127. }
  37128. PostProcessManager.prototype._prepareBuffers = function () {
  37129. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  37130. return;
  37131. }
  37132. // VBO
  37133. var vertices = [];
  37134. vertices.push(1, 1);
  37135. vertices.push(-1, 1);
  37136. vertices.push(-1, -1);
  37137. vertices.push(1, -1);
  37138. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  37139. this._buildIndexBuffer();
  37140. };
  37141. PostProcessManager.prototype._buildIndexBuffer = function () {
  37142. // Indices
  37143. var indices = [];
  37144. indices.push(0);
  37145. indices.push(1);
  37146. indices.push(2);
  37147. indices.push(0);
  37148. indices.push(2);
  37149. indices.push(3);
  37150. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  37151. };
  37152. /**
  37153. * Rebuilds the vertex buffers of the manager.
  37154. */
  37155. PostProcessManager.prototype._rebuild = function () {
  37156. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37157. if (!vb) {
  37158. return;
  37159. }
  37160. vb._rebuild();
  37161. this._buildIndexBuffer();
  37162. };
  37163. // Methods
  37164. /**
  37165. * Prepares a frame to be run through a post process.
  37166. * @param sourceTexture The input texture to the post procesess. (default: null)
  37167. * @param postProcesses An array of post processes to be run. (default: null)
  37168. * @returns True if the post processes were able to be run.
  37169. */
  37170. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  37171. if (sourceTexture === void 0) { sourceTexture = null; }
  37172. if (postProcesses === void 0) { postProcesses = null; }
  37173. var camera = this._scene.activeCamera;
  37174. if (!camera) {
  37175. return false;
  37176. }
  37177. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37178. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37179. return false;
  37180. }
  37181. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  37182. return true;
  37183. };
  37184. /**
  37185. * Manually render a set of post processes to a texture.
  37186. * @param postProcesses An array of post processes to be run.
  37187. * @param targetTexture The target texture to render to.
  37188. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  37189. */
  37190. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  37191. if (targetTexture === void 0) { targetTexture = null; }
  37192. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37193. var engine = this._scene.getEngine();
  37194. for (var index = 0; index < postProcesses.length; index++) {
  37195. if (index < postProcesses.length - 1) {
  37196. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  37197. }
  37198. else {
  37199. if (targetTexture) {
  37200. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  37201. }
  37202. else {
  37203. engine.restoreDefaultFramebuffer();
  37204. }
  37205. }
  37206. var pp = postProcesses[index];
  37207. var effect = pp.apply();
  37208. if (effect) {
  37209. pp.onBeforeRenderObservable.notifyObservers(effect);
  37210. // VBOs
  37211. this._prepareBuffers();
  37212. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37213. // Draw order
  37214. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37215. pp.onAfterRenderObservable.notifyObservers(effect);
  37216. }
  37217. }
  37218. // Restore depth buffer
  37219. engine.setDepthBuffer(true);
  37220. engine.setDepthWrite(true);
  37221. };
  37222. /**
  37223. * Finalize the result of the output of the postprocesses.
  37224. * @param doNotPresent If true the result will not be displayed to the screen.
  37225. * @param targetTexture The target texture to render to.
  37226. * @param faceIndex The index of the face to bind the target texture to.
  37227. * @param postProcesses The array of post processes to render.
  37228. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  37229. */
  37230. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  37231. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37232. var camera = this._scene.activeCamera;
  37233. if (!camera) {
  37234. return;
  37235. }
  37236. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37237. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37238. return;
  37239. }
  37240. var engine = this._scene.getEngine();
  37241. for (var index = 0, len = postProcesses.length; index < len; index++) {
  37242. var pp = postProcesses[index];
  37243. if (index < len - 1) {
  37244. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  37245. }
  37246. else {
  37247. if (targetTexture) {
  37248. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  37249. }
  37250. else {
  37251. engine.restoreDefaultFramebuffer();
  37252. }
  37253. }
  37254. if (doNotPresent) {
  37255. break;
  37256. }
  37257. var effect = pp.apply();
  37258. if (effect) {
  37259. pp.onBeforeRenderObservable.notifyObservers(effect);
  37260. // VBOs
  37261. this._prepareBuffers();
  37262. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37263. // Draw order
  37264. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37265. pp.onAfterRenderObservable.notifyObservers(effect);
  37266. }
  37267. }
  37268. // Restore states
  37269. engine.setDepthBuffer(true);
  37270. engine.setDepthWrite(true);
  37271. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  37272. };
  37273. /**
  37274. * Disposes of the post process manager.
  37275. */
  37276. PostProcessManager.prototype.dispose = function () {
  37277. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37278. if (buffer) {
  37279. buffer.dispose();
  37280. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  37281. }
  37282. if (this._indexBuffer) {
  37283. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37284. this._indexBuffer = null;
  37285. }
  37286. };
  37287. return PostProcessManager;
  37288. }());
  37289. BABYLON.PostProcessManager = PostProcessManager;
  37290. })(BABYLON || (BABYLON = {}));
  37291. //# sourceMappingURL=babylon.postProcessManager.js.map
  37292. "use strict";
  37293. var BABYLON;
  37294. (function (BABYLON) {
  37295. /**
  37296. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  37297. */
  37298. var PerformanceMonitor = /** @class */ (function () {
  37299. /**
  37300. * constructor
  37301. * @param frameSampleSize The number of samples required to saturate the sliding window
  37302. */
  37303. function PerformanceMonitor(frameSampleSize) {
  37304. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  37305. this._enabled = true;
  37306. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  37307. }
  37308. /**
  37309. * Samples current frame
  37310. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  37311. */
  37312. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  37313. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  37314. if (!this._enabled)
  37315. return;
  37316. if (this._lastFrameTimeMs != null) {
  37317. var dt = timeMs - this._lastFrameTimeMs;
  37318. this._rollingFrameTime.add(dt);
  37319. }
  37320. this._lastFrameTimeMs = timeMs;
  37321. };
  37322. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  37323. /**
  37324. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37325. * @return Average frame time in milliseconds
  37326. */
  37327. get: function () {
  37328. return this._rollingFrameTime.average;
  37329. },
  37330. enumerable: true,
  37331. configurable: true
  37332. });
  37333. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  37334. /**
  37335. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37336. * @return Frame time variance in milliseconds squared
  37337. */
  37338. get: function () {
  37339. return this._rollingFrameTime.variance;
  37340. },
  37341. enumerable: true,
  37342. configurable: true
  37343. });
  37344. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  37345. /**
  37346. * Returns the frame time of the most recent frame
  37347. * @return Frame time in milliseconds
  37348. */
  37349. get: function () {
  37350. return this._rollingFrameTime.history(0);
  37351. },
  37352. enumerable: true,
  37353. configurable: true
  37354. });
  37355. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  37356. /**
  37357. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  37358. * @return Framerate in frames per second
  37359. */
  37360. get: function () {
  37361. return 1000.0 / this._rollingFrameTime.average;
  37362. },
  37363. enumerable: true,
  37364. configurable: true
  37365. });
  37366. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  37367. /**
  37368. * Returns the average framerate in frames per second using the most recent frame time
  37369. * @return Framerate in frames per second
  37370. */
  37371. get: function () {
  37372. var history = this._rollingFrameTime.history(0);
  37373. if (history === 0) {
  37374. return 0;
  37375. }
  37376. return 1000.0 / history;
  37377. },
  37378. enumerable: true,
  37379. configurable: true
  37380. });
  37381. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  37382. /**
  37383. * Returns true if enough samples have been taken to completely fill the sliding window
  37384. * @return true if saturated
  37385. */
  37386. get: function () {
  37387. return this._rollingFrameTime.isSaturated();
  37388. },
  37389. enumerable: true,
  37390. configurable: true
  37391. });
  37392. /**
  37393. * Enables contributions to the sliding window sample set
  37394. */
  37395. PerformanceMonitor.prototype.enable = function () {
  37396. this._enabled = true;
  37397. };
  37398. /**
  37399. * Disables contributions to the sliding window sample set
  37400. * Samples will not be interpolated over the disabled period
  37401. */
  37402. PerformanceMonitor.prototype.disable = function () {
  37403. this._enabled = false;
  37404. //clear last sample to avoid interpolating over the disabled period when next enabled
  37405. this._lastFrameTimeMs = null;
  37406. };
  37407. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  37408. /**
  37409. * Returns true if sampling is enabled
  37410. * @return true if enabled
  37411. */
  37412. get: function () {
  37413. return this._enabled;
  37414. },
  37415. enumerable: true,
  37416. configurable: true
  37417. });
  37418. /**
  37419. * Resets performance monitor
  37420. */
  37421. PerformanceMonitor.prototype.reset = function () {
  37422. //clear last sample to avoid interpolating over the disabled period when next enabled
  37423. this._lastFrameTimeMs = null;
  37424. //wipe record
  37425. this._rollingFrameTime.reset();
  37426. };
  37427. return PerformanceMonitor;
  37428. }());
  37429. BABYLON.PerformanceMonitor = PerformanceMonitor;
  37430. /**
  37431. * RollingAverage
  37432. *
  37433. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  37434. */
  37435. var RollingAverage = /** @class */ (function () {
  37436. /**
  37437. * constructor
  37438. * @param length The number of samples required to saturate the sliding window
  37439. */
  37440. function RollingAverage(length) {
  37441. this._samples = new Array(length);
  37442. this.reset();
  37443. }
  37444. /**
  37445. * Adds a sample to the sample set
  37446. * @param v The sample value
  37447. */
  37448. RollingAverage.prototype.add = function (v) {
  37449. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  37450. var delta;
  37451. //we need to check if we've already wrapped round
  37452. if (this.isSaturated()) {
  37453. //remove bottom of stack from mean
  37454. var bottomValue = this._samples[this._pos];
  37455. delta = bottomValue - this.average;
  37456. this.average -= delta / (this._sampleCount - 1);
  37457. this._m2 -= delta * (bottomValue - this.average);
  37458. }
  37459. else {
  37460. this._sampleCount++;
  37461. }
  37462. //add new value to mean
  37463. delta = v - this.average;
  37464. this.average += delta / (this._sampleCount);
  37465. this._m2 += delta * (v - this.average);
  37466. //set the new variance
  37467. this.variance = this._m2 / (this._sampleCount - 1);
  37468. this._samples[this._pos] = v;
  37469. this._pos++;
  37470. this._pos %= this._samples.length; //positive wrap around
  37471. };
  37472. /**
  37473. * Returns previously added values or null if outside of history or outside the sliding window domain
  37474. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  37475. * @return Value previously recorded with add() or null if outside of range
  37476. */
  37477. RollingAverage.prototype.history = function (i) {
  37478. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  37479. return 0;
  37480. }
  37481. var i0 = this._wrapPosition(this._pos - 1.0);
  37482. return this._samples[this._wrapPosition(i0 - i)];
  37483. };
  37484. /**
  37485. * Returns true if enough samples have been taken to completely fill the sliding window
  37486. * @return true if sample-set saturated
  37487. */
  37488. RollingAverage.prototype.isSaturated = function () {
  37489. return this._sampleCount >= this._samples.length;
  37490. };
  37491. /**
  37492. * Resets the rolling average (equivalent to 0 samples taken so far)
  37493. */
  37494. RollingAverage.prototype.reset = function () {
  37495. this.average = 0;
  37496. this.variance = 0;
  37497. this._sampleCount = 0;
  37498. this._pos = 0;
  37499. this._m2 = 0;
  37500. };
  37501. /**
  37502. * Wraps a value around the sample range boundaries
  37503. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  37504. * @return Wrapped position in sample range
  37505. */
  37506. RollingAverage.prototype._wrapPosition = function (i) {
  37507. var max = this._samples.length;
  37508. return ((i % max) + max) % max;
  37509. };
  37510. return RollingAverage;
  37511. }());
  37512. BABYLON.RollingAverage = RollingAverage;
  37513. })(BABYLON || (BABYLON = {}));
  37514. //# sourceMappingURL=babylon.performanceMonitor.js.map
  37515. "use strict";
  37516. var BABYLON;
  37517. (function (BABYLON) {
  37518. /**
  37519. * This groups together the common properties used for image processing either in direct forward pass
  37520. * or through post processing effect depending on the use of the image processing pipeline in your scene
  37521. * or not.
  37522. */
  37523. var ImageProcessingConfiguration = /** @class */ (function () {
  37524. function ImageProcessingConfiguration() {
  37525. /**
  37526. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  37527. */
  37528. this.colorCurves = new BABYLON.ColorCurves();
  37529. this._colorCurvesEnabled = false;
  37530. this._colorGradingEnabled = false;
  37531. this._colorGradingWithGreenDepth = true;
  37532. this._colorGradingBGR = true;
  37533. this._exposure = 1.0;
  37534. this._toneMappingEnabled = false;
  37535. this._contrast = 1.0;
  37536. /**
  37537. * Vignette stretch size.
  37538. */
  37539. this.vignetteStretch = 0;
  37540. /**
  37541. * Vignette centre X Offset.
  37542. */
  37543. this.vignetteCentreX = 0;
  37544. /**
  37545. * Vignette centre Y Offset.
  37546. */
  37547. this.vignetteCentreY = 0;
  37548. /**
  37549. * Vignette weight or intensity of the vignette effect.
  37550. */
  37551. this.vignetteWeight = 1.5;
  37552. /**
  37553. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  37554. * if vignetteEnabled is set to true.
  37555. */
  37556. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  37557. /**
  37558. * Camera field of view used by the Vignette effect.
  37559. */
  37560. this.vignetteCameraFov = 0.5;
  37561. this._grainEnabled = false;
  37562. this._grainIntensity = 30;
  37563. this._grainAnimated = false;
  37564. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  37565. this._vignetteEnabled = false;
  37566. this._applyByPostProcess = false;
  37567. this._isEnabled = true;
  37568. /**
  37569. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  37570. * @type {BABYLON.Observable}
  37571. */
  37572. this.onUpdateParameters = new BABYLON.Observable();
  37573. }
  37574. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  37575. /**
  37576. * Gets wether the color curves effect is enabled.
  37577. */
  37578. get: function () {
  37579. return this._colorCurvesEnabled;
  37580. },
  37581. /**
  37582. * Sets wether the color curves effect is enabled.
  37583. */
  37584. set: function (value) {
  37585. if (this._colorCurvesEnabled === value) {
  37586. return;
  37587. }
  37588. this._colorCurvesEnabled = value;
  37589. this._updateParameters();
  37590. },
  37591. enumerable: true,
  37592. configurable: true
  37593. });
  37594. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  37595. /**
  37596. * Gets wether the color grading effect is enabled.
  37597. */
  37598. get: function () {
  37599. return this._colorGradingEnabled;
  37600. },
  37601. /**
  37602. * Sets wether the color grading effect is enabled.
  37603. */
  37604. set: function (value) {
  37605. if (this._colorGradingEnabled === value) {
  37606. return;
  37607. }
  37608. this._colorGradingEnabled = value;
  37609. this._updateParameters();
  37610. },
  37611. enumerable: true,
  37612. configurable: true
  37613. });
  37614. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  37615. /**
  37616. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  37617. */
  37618. get: function () {
  37619. return this._colorGradingWithGreenDepth;
  37620. },
  37621. /**
  37622. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  37623. */
  37624. set: function (value) {
  37625. if (this._colorGradingWithGreenDepth === value) {
  37626. return;
  37627. }
  37628. this._colorGradingWithGreenDepth = value;
  37629. this._updateParameters();
  37630. },
  37631. enumerable: true,
  37632. configurable: true
  37633. });
  37634. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  37635. /**
  37636. * Gets wether the color grading texture contains BGR values.
  37637. */
  37638. get: function () {
  37639. return this._colorGradingBGR;
  37640. },
  37641. /**
  37642. * Sets wether the color grading texture contains BGR values.
  37643. */
  37644. set: function (value) {
  37645. if (this._colorGradingBGR === value) {
  37646. return;
  37647. }
  37648. this._colorGradingBGR = value;
  37649. this._updateParameters();
  37650. },
  37651. enumerable: true,
  37652. configurable: true
  37653. });
  37654. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  37655. /**
  37656. * Gets the Exposure used in the effect.
  37657. */
  37658. get: function () {
  37659. return this._exposure;
  37660. },
  37661. /**
  37662. * Sets the Exposure used in the effect.
  37663. */
  37664. set: function (value) {
  37665. if (this._exposure === value) {
  37666. return;
  37667. }
  37668. this._exposure = value;
  37669. this._updateParameters();
  37670. },
  37671. enumerable: true,
  37672. configurable: true
  37673. });
  37674. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37675. /**
  37676. * Gets wether the tone mapping effect is enabled.
  37677. */
  37678. get: function () {
  37679. return this._toneMappingEnabled;
  37680. },
  37681. /**
  37682. * Sets wether the tone mapping effect is enabled.
  37683. */
  37684. set: function (value) {
  37685. if (this._toneMappingEnabled === value) {
  37686. return;
  37687. }
  37688. this._toneMappingEnabled = value;
  37689. this._updateParameters();
  37690. },
  37691. enumerable: true,
  37692. configurable: true
  37693. });
  37694. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37695. /**
  37696. * Gets the contrast used in the effect.
  37697. */
  37698. get: function () {
  37699. return this._contrast;
  37700. },
  37701. /**
  37702. * Sets the contrast used in the effect.
  37703. */
  37704. set: function (value) {
  37705. if (this._contrast === value) {
  37706. return;
  37707. }
  37708. this._contrast = value;
  37709. this._updateParameters();
  37710. },
  37711. enumerable: true,
  37712. configurable: true
  37713. });
  37714. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainEnabled", {
  37715. /**
  37716. * If the grain effect should be enabled.
  37717. */
  37718. get: function () {
  37719. return this._grainEnabled;
  37720. },
  37721. set: function (value) {
  37722. if (this._grainEnabled === value) {
  37723. return;
  37724. }
  37725. this._grainEnabled = value;
  37726. this._updateParameters();
  37727. },
  37728. enumerable: true,
  37729. configurable: true
  37730. });
  37731. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainIntensity", {
  37732. /**
  37733. * Amount of grain to be applied by the grain effect.
  37734. */
  37735. get: function () {
  37736. return this._grainIntensity;
  37737. },
  37738. set: function (value) {
  37739. if (this._grainIntensity === value) {
  37740. return;
  37741. }
  37742. this._grainIntensity = value;
  37743. },
  37744. enumerable: true,
  37745. configurable: true
  37746. });
  37747. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainAnimated", {
  37748. /**
  37749. * If the grain effect should be animated.
  37750. */
  37751. get: function () {
  37752. return this._grainAnimated;
  37753. },
  37754. set: function (value) {
  37755. if (this._grainAnimated === value) {
  37756. return;
  37757. }
  37758. this._grainAnimated = value;
  37759. this._updateParameters();
  37760. },
  37761. enumerable: true,
  37762. configurable: true
  37763. });
  37764. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37765. /**
  37766. * Gets the vignette blend mode allowing different kind of effect.
  37767. */
  37768. get: function () {
  37769. return this._vignetteBlendMode;
  37770. },
  37771. /**
  37772. * Sets the vignette blend mode allowing different kind of effect.
  37773. */
  37774. set: function (value) {
  37775. if (this._vignetteBlendMode === value) {
  37776. return;
  37777. }
  37778. this._vignetteBlendMode = value;
  37779. this._updateParameters();
  37780. },
  37781. enumerable: true,
  37782. configurable: true
  37783. });
  37784. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37785. /**
  37786. * Gets wether the vignette effect is enabled.
  37787. */
  37788. get: function () {
  37789. return this._vignetteEnabled;
  37790. },
  37791. /**
  37792. * Sets wether the vignette effect is enabled.
  37793. */
  37794. set: function (value) {
  37795. if (this._vignetteEnabled === value) {
  37796. return;
  37797. }
  37798. this._vignetteEnabled = value;
  37799. this._updateParameters();
  37800. },
  37801. enumerable: true,
  37802. configurable: true
  37803. });
  37804. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37805. /**
  37806. * Gets wether the image processing is applied through a post process or not.
  37807. */
  37808. get: function () {
  37809. return this._applyByPostProcess;
  37810. },
  37811. /**
  37812. * Sets wether the image processing is applied through a post process or not.
  37813. */
  37814. set: function (value) {
  37815. if (this._applyByPostProcess === value) {
  37816. return;
  37817. }
  37818. this._applyByPostProcess = value;
  37819. this._updateParameters();
  37820. },
  37821. enumerable: true,
  37822. configurable: true
  37823. });
  37824. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37825. /**
  37826. * Gets wether the image processing is enabled or not.
  37827. */
  37828. get: function () {
  37829. return this._isEnabled;
  37830. },
  37831. /**
  37832. * Sets wether the image processing is enabled or not.
  37833. */
  37834. set: function (value) {
  37835. if (this._isEnabled === value) {
  37836. return;
  37837. }
  37838. this._isEnabled = value;
  37839. this._updateParameters();
  37840. },
  37841. enumerable: true,
  37842. configurable: true
  37843. });
  37844. /**
  37845. * Method called each time the image processing information changes requires to recompile the effect.
  37846. */
  37847. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37848. this.onUpdateParameters.notifyObservers(this);
  37849. };
  37850. ImageProcessingConfiguration.prototype.getClassName = function () {
  37851. return "ImageProcessingConfiguration";
  37852. };
  37853. /**
  37854. * Prepare the list of uniforms associated with the Image Processing effects.
  37855. * @param uniformsList The list of uniforms used in the effect
  37856. * @param defines the list of defines currently in use
  37857. */
  37858. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37859. if (defines.EXPOSURE) {
  37860. uniforms.push("exposureLinear");
  37861. }
  37862. if (defines.CONTRAST) {
  37863. uniforms.push("contrast");
  37864. }
  37865. if (defines.COLORGRADING) {
  37866. uniforms.push("colorTransformSettings");
  37867. }
  37868. if (defines.VIGNETTE) {
  37869. uniforms.push("vInverseScreenSize");
  37870. uniforms.push("vignetteSettings1");
  37871. uniforms.push("vignetteSettings2");
  37872. }
  37873. if (defines.COLORCURVES) {
  37874. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37875. }
  37876. if (defines.GRAIN) {
  37877. uniforms.push("grainVarianceAmount");
  37878. uniforms.push("grainAnimatedSeed");
  37879. }
  37880. };
  37881. /**
  37882. * Prepare the list of samplers associated with the Image Processing effects.
  37883. * @param uniformsList The list of uniforms used in the effect
  37884. * @param defines the list of defines currently in use
  37885. */
  37886. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37887. if (defines.COLORGRADING) {
  37888. samplersList.push("txColorTransform");
  37889. }
  37890. };
  37891. /**
  37892. * Prepare the list of defines associated to the shader.
  37893. * @param defines the list of defines to complete
  37894. */
  37895. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37896. if (forPostProcess === void 0) { forPostProcess = false; }
  37897. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37898. defines.VIGNETTE = false;
  37899. defines.TONEMAPPING = false;
  37900. defines.CONTRAST = false;
  37901. defines.EXPOSURE = false;
  37902. defines.COLORCURVES = false;
  37903. defines.COLORGRADING = false;
  37904. defines.COLORGRADING3D = false;
  37905. defines.IMAGEPROCESSING = false;
  37906. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37907. return;
  37908. }
  37909. defines.VIGNETTE = this.vignetteEnabled;
  37910. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37911. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37912. defines.TONEMAPPING = this.toneMappingEnabled;
  37913. defines.CONTRAST = (this.contrast !== 1.0);
  37914. defines.EXPOSURE = (this.exposure !== 1.0);
  37915. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37916. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37917. if (defines.COLORGRADING) {
  37918. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37919. }
  37920. else {
  37921. defines.COLORGRADING3D = false;
  37922. }
  37923. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37924. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37925. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37926. defines.GRAIN = this.grainEnabled;
  37927. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.GRAIN;
  37928. };
  37929. /**
  37930. * Returns true if all the image processing information are ready.
  37931. */
  37932. ImageProcessingConfiguration.prototype.isReady = function () {
  37933. // Color Grading texure can not be none blocking.
  37934. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37935. };
  37936. /**
  37937. * Binds the image processing to the shader.
  37938. * @param effect The effect to bind to
  37939. */
  37940. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37941. if (aspectRatio === void 0) { aspectRatio = 1; }
  37942. // Color Curves
  37943. if (this._colorCurvesEnabled && this.colorCurves) {
  37944. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37945. }
  37946. // Vignette
  37947. if (this._vignetteEnabled) {
  37948. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37949. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37950. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37951. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37952. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37953. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37954. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37955. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37956. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37957. var vignettePower = -2.0 * this.vignetteWeight;
  37958. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37959. }
  37960. // Exposure
  37961. effect.setFloat("exposureLinear", this.exposure);
  37962. // Contrast
  37963. effect.setFloat("contrast", this.contrast);
  37964. // Color transform settings
  37965. if (this.colorGradingTexture) {
  37966. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37967. var textureSize = this.colorGradingTexture.getSize().height;
  37968. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37969. 0.5 / textureSize, // textureOffset
  37970. textureSize, // textureSize
  37971. this.colorGradingTexture.level // weight
  37972. );
  37973. }
  37974. effect.setFloat("grainVarianceAmount", this.grainIntensity);
  37975. effect.setFloat("grainAnimatedSeed", this.grainAnimated ? Math.random() + 1 : 1);
  37976. };
  37977. /**
  37978. * Clones the current image processing instance.
  37979. * @return The cloned image processing
  37980. */
  37981. ImageProcessingConfiguration.prototype.clone = function () {
  37982. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37983. };
  37984. /**
  37985. * Serializes the current image processing instance to a json representation.
  37986. * @return a JSON representation
  37987. */
  37988. ImageProcessingConfiguration.prototype.serialize = function () {
  37989. return BABYLON.SerializationHelper.Serialize(this);
  37990. };
  37991. /**
  37992. * Parses the image processing from a json representation.
  37993. * @param source the JSON source to parse
  37994. * @return The parsed image processing
  37995. */
  37996. ImageProcessingConfiguration.Parse = function (source) {
  37997. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37998. };
  37999. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  38000. /**
  38001. * Used to apply the vignette as a mix with the pixel color.
  38002. */
  38003. get: function () {
  38004. return this._VIGNETTEMODE_MULTIPLY;
  38005. },
  38006. enumerable: true,
  38007. configurable: true
  38008. });
  38009. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  38010. /**
  38011. * Used to apply the vignette as a replacement of the pixel color.
  38012. */
  38013. get: function () {
  38014. return this._VIGNETTEMODE_OPAQUE;
  38015. },
  38016. enumerable: true,
  38017. configurable: true
  38018. });
  38019. // Static constants associated to the image processing.
  38020. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  38021. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  38022. __decorate([
  38023. BABYLON.serializeAsColorCurves()
  38024. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  38025. __decorate([
  38026. BABYLON.serialize()
  38027. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  38028. __decorate([
  38029. BABYLON.serializeAsTexture()
  38030. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  38031. __decorate([
  38032. BABYLON.serialize()
  38033. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  38034. __decorate([
  38035. BABYLON.serialize()
  38036. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  38037. __decorate([
  38038. BABYLON.serialize()
  38039. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  38040. __decorate([
  38041. BABYLON.serialize()
  38042. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  38043. __decorate([
  38044. BABYLON.serialize()
  38045. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  38046. __decorate([
  38047. BABYLON.serialize()
  38048. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  38049. __decorate([
  38050. BABYLON.serialize()
  38051. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  38052. __decorate([
  38053. BABYLON.serialize()
  38054. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  38055. __decorate([
  38056. BABYLON.serialize()
  38057. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  38058. __decorate([
  38059. BABYLON.serialize()
  38060. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  38061. __decorate([
  38062. BABYLON.serializeAsColor4()
  38063. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  38064. __decorate([
  38065. BABYLON.serialize()
  38066. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  38067. __decorate([
  38068. BABYLON.serialize()
  38069. ], ImageProcessingConfiguration.prototype, "_grainEnabled", void 0);
  38070. __decorate([
  38071. BABYLON.serialize()
  38072. ], ImageProcessingConfiguration.prototype, "_grainIntensity", void 0);
  38073. __decorate([
  38074. BABYLON.serialize()
  38075. ], ImageProcessingConfiguration.prototype, "_grainAnimated", void 0);
  38076. __decorate([
  38077. BABYLON.serialize()
  38078. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  38079. __decorate([
  38080. BABYLON.serialize()
  38081. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  38082. __decorate([
  38083. BABYLON.serialize()
  38084. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  38085. __decorate([
  38086. BABYLON.serialize()
  38087. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  38088. return ImageProcessingConfiguration;
  38089. }());
  38090. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  38091. })(BABYLON || (BABYLON = {}));
  38092. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  38093. "use strict";
  38094. var BABYLON;
  38095. (function (BABYLON) {
  38096. /**
  38097. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  38098. * It can help converting any input color in a desired output one. This can then be used to create effects
  38099. * from sepia, black and white to sixties or futuristic rendering...
  38100. *
  38101. * The only supported format is currently 3dl.
  38102. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  38103. */
  38104. var ColorGradingTexture = /** @class */ (function (_super) {
  38105. __extends(ColorGradingTexture, _super);
  38106. /**
  38107. * Instantiates a ColorGradingTexture from the following parameters.
  38108. *
  38109. * @param url The location of the color gradind data (currently only supporting 3dl)
  38110. * @param scene The scene the texture will be used in
  38111. */
  38112. function ColorGradingTexture(url, scene) {
  38113. var _this = _super.call(this, scene) || this;
  38114. if (!url) {
  38115. return _this;
  38116. }
  38117. _this._engine = scene.getEngine();
  38118. _this._textureMatrix = BABYLON.Matrix.Identity();
  38119. _this.name = url;
  38120. _this.url = url;
  38121. _this.hasAlpha = false;
  38122. _this.isCube = false;
  38123. _this.is3D = _this._engine.webGLVersion > 1;
  38124. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38125. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38126. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38127. _this.anisotropicFilteringLevel = 1;
  38128. _this._texture = _this._getFromCache(url, true);
  38129. if (!_this._texture) {
  38130. if (!scene.useDelayedTextureLoading) {
  38131. _this.loadTexture();
  38132. }
  38133. else {
  38134. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  38135. }
  38136. }
  38137. return _this;
  38138. }
  38139. /**
  38140. * Returns the texture matrix used in most of the material.
  38141. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  38142. */
  38143. ColorGradingTexture.prototype.getTextureMatrix = function () {
  38144. return this._textureMatrix;
  38145. };
  38146. /**
  38147. * Occurs when the file being loaded is a .3dl LUT file.
  38148. */
  38149. ColorGradingTexture.prototype.load3dlTexture = function () {
  38150. var engine = this._engine;
  38151. var texture;
  38152. if (engine.webGLVersion === 1) {
  38153. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38154. }
  38155. else {
  38156. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38157. }
  38158. this._texture = texture;
  38159. var callback = function (text) {
  38160. if (typeof text !== "string") {
  38161. return;
  38162. }
  38163. var data = null;
  38164. var tempData = null;
  38165. var line;
  38166. var lines = text.split('\n');
  38167. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  38168. var maxColor = 0;
  38169. for (var i = 0; i < lines.length; i++) {
  38170. line = lines[i];
  38171. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  38172. continue;
  38173. if (line.indexOf('#') === 0)
  38174. continue;
  38175. var words = line.split(" ");
  38176. if (size === 0) {
  38177. // Number of space + one
  38178. size = words.length;
  38179. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  38180. tempData = new Float32Array(size * size * size * 4);
  38181. continue;
  38182. }
  38183. if (size != 0) {
  38184. var r = Math.max(parseInt(words[0]), 0);
  38185. var g = Math.max(parseInt(words[1]), 0);
  38186. var b = Math.max(parseInt(words[2]), 0);
  38187. maxColor = Math.max(r, maxColor);
  38188. maxColor = Math.max(g, maxColor);
  38189. maxColor = Math.max(b, maxColor);
  38190. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  38191. if (tempData) {
  38192. tempData[pixelStorageIndex + 0] = r;
  38193. tempData[pixelStorageIndex + 1] = g;
  38194. tempData[pixelStorageIndex + 2] = b;
  38195. }
  38196. pixelIndexSlice++;
  38197. if (pixelIndexSlice % size == 0) {
  38198. pixelIndexH++;
  38199. pixelIndexSlice = 0;
  38200. if (pixelIndexH % size == 0) {
  38201. pixelIndexW++;
  38202. pixelIndexH = 0;
  38203. }
  38204. }
  38205. }
  38206. }
  38207. if (tempData && data) {
  38208. for (var i = 0; i < tempData.length; i++) {
  38209. if (i > 0 && (i + 1) % 4 === 0) {
  38210. data[i] = 255;
  38211. }
  38212. else {
  38213. var value = tempData[i];
  38214. data[i] = (value / maxColor * 255);
  38215. }
  38216. }
  38217. }
  38218. if (texture.is3D) {
  38219. texture.updateSize(size, size, size);
  38220. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38221. }
  38222. else {
  38223. texture.updateSize(size * size, size);
  38224. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38225. }
  38226. };
  38227. var scene = this.getScene();
  38228. if (scene) {
  38229. scene._loadFile(this.url, callback);
  38230. }
  38231. else {
  38232. this._engine._loadFile(this.url, callback);
  38233. }
  38234. return this._texture;
  38235. };
  38236. /**
  38237. * Starts the loading process of the texture.
  38238. */
  38239. ColorGradingTexture.prototype.loadTexture = function () {
  38240. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  38241. this.load3dlTexture();
  38242. }
  38243. };
  38244. /**
  38245. * Clones the color gradind texture.
  38246. */
  38247. ColorGradingTexture.prototype.clone = function () {
  38248. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  38249. // Base texture
  38250. newTexture.level = this.level;
  38251. return newTexture;
  38252. };
  38253. /**
  38254. * Called during delayed load for textures.
  38255. */
  38256. ColorGradingTexture.prototype.delayLoad = function () {
  38257. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  38258. return;
  38259. }
  38260. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38261. this._texture = this._getFromCache(this.url, true);
  38262. if (!this._texture) {
  38263. this.loadTexture();
  38264. }
  38265. };
  38266. /**
  38267. * Parses a color grading texture serialized by Babylon.
  38268. * @param parsedTexture The texture information being parsedTexture
  38269. * @param scene The scene to load the texture in
  38270. * @param rootUrl The root url of the data assets to load
  38271. * @return A color gradind texture
  38272. */
  38273. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  38274. var texture = null;
  38275. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  38276. texture = new ColorGradingTexture(parsedTexture.name, scene);
  38277. texture.name = parsedTexture.name;
  38278. texture.level = parsedTexture.level;
  38279. }
  38280. return texture;
  38281. };
  38282. /**
  38283. * Serializes the LUT texture to json format.
  38284. */
  38285. ColorGradingTexture.prototype.serialize = function () {
  38286. if (!this.name) {
  38287. return null;
  38288. }
  38289. var serializationObject = {};
  38290. serializationObject.name = this.name;
  38291. serializationObject.level = this.level;
  38292. serializationObject.customType = "BABYLON.ColorGradingTexture";
  38293. return serializationObject;
  38294. };
  38295. /**
  38296. * Empty line regex stored for GC.
  38297. */
  38298. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  38299. return ColorGradingTexture;
  38300. }(BABYLON.BaseTexture));
  38301. BABYLON.ColorGradingTexture = ColorGradingTexture;
  38302. })(BABYLON || (BABYLON = {}));
  38303. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  38304. "use strict";
  38305. var BABYLON;
  38306. (function (BABYLON) {
  38307. /**
  38308. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38309. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38310. * 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;
  38311. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38312. */
  38313. var ColorCurves = /** @class */ (function () {
  38314. function ColorCurves() {
  38315. this._dirty = true;
  38316. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  38317. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  38318. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38319. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  38320. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38321. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  38322. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  38323. this._globalHue = 30;
  38324. this._globalDensity = 0;
  38325. this._globalSaturation = 0;
  38326. this._globalExposure = 0;
  38327. this._highlightsHue = 30;
  38328. this._highlightsDensity = 0;
  38329. this._highlightsSaturation = 0;
  38330. this._highlightsExposure = 0;
  38331. this._midtonesHue = 30;
  38332. this._midtonesDensity = 0;
  38333. this._midtonesSaturation = 0;
  38334. this._midtonesExposure = 0;
  38335. this._shadowsHue = 30;
  38336. this._shadowsDensity = 0;
  38337. this._shadowsSaturation = 0;
  38338. this._shadowsExposure = 0;
  38339. }
  38340. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  38341. /**
  38342. * Gets the global Hue value.
  38343. * 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).
  38344. */
  38345. get: function () {
  38346. return this._globalHue;
  38347. },
  38348. /**
  38349. * Sets the global Hue value.
  38350. * 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).
  38351. */
  38352. set: function (value) {
  38353. this._globalHue = value;
  38354. this._dirty = true;
  38355. },
  38356. enumerable: true,
  38357. configurable: true
  38358. });
  38359. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  38360. /**
  38361. * Gets the global Density value.
  38362. * 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.
  38363. * Values less than zero provide a filter of opposite hue.
  38364. */
  38365. get: function () {
  38366. return this._globalDensity;
  38367. },
  38368. /**
  38369. * Sets the global Density value.
  38370. * 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.
  38371. * Values less than zero provide a filter of opposite hue.
  38372. */
  38373. set: function (value) {
  38374. this._globalDensity = value;
  38375. this._dirty = true;
  38376. },
  38377. enumerable: true,
  38378. configurable: true
  38379. });
  38380. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  38381. /**
  38382. * Gets the global Saturation value.
  38383. * 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.
  38384. */
  38385. get: function () {
  38386. return this._globalSaturation;
  38387. },
  38388. /**
  38389. * Sets the global Saturation value.
  38390. * 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.
  38391. */
  38392. set: function (value) {
  38393. this._globalSaturation = value;
  38394. this._dirty = true;
  38395. },
  38396. enumerable: true,
  38397. configurable: true
  38398. });
  38399. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  38400. /**
  38401. * Gets the highlights Hue value.
  38402. * 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).
  38403. */
  38404. get: function () {
  38405. return this._highlightsHue;
  38406. },
  38407. /**
  38408. * Sets the highlights Hue value.
  38409. * 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).
  38410. */
  38411. set: function (value) {
  38412. this._highlightsHue = value;
  38413. this._dirty = true;
  38414. },
  38415. enumerable: true,
  38416. configurable: true
  38417. });
  38418. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  38419. /**
  38420. * Gets the highlights Density value.
  38421. * 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.
  38422. * Values less than zero provide a filter of opposite hue.
  38423. */
  38424. get: function () {
  38425. return this._highlightsDensity;
  38426. },
  38427. /**
  38428. * Sets the highlights Density value.
  38429. * 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.
  38430. * Values less than zero provide a filter of opposite hue.
  38431. */
  38432. set: function (value) {
  38433. this._highlightsDensity = value;
  38434. this._dirty = true;
  38435. },
  38436. enumerable: true,
  38437. configurable: true
  38438. });
  38439. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  38440. /**
  38441. * Gets the highlights Saturation value.
  38442. * 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.
  38443. */
  38444. get: function () {
  38445. return this._highlightsSaturation;
  38446. },
  38447. /**
  38448. * Sets the highlights Saturation value.
  38449. * 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.
  38450. */
  38451. set: function (value) {
  38452. this._highlightsSaturation = value;
  38453. this._dirty = true;
  38454. },
  38455. enumerable: true,
  38456. configurable: true
  38457. });
  38458. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  38459. /**
  38460. * Gets the highlights Exposure value.
  38461. * 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.
  38462. */
  38463. get: function () {
  38464. return this._highlightsExposure;
  38465. },
  38466. /**
  38467. * Sets the highlights Exposure value.
  38468. * 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.
  38469. */
  38470. set: function (value) {
  38471. this._highlightsExposure = value;
  38472. this._dirty = true;
  38473. },
  38474. enumerable: true,
  38475. configurable: true
  38476. });
  38477. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  38478. /**
  38479. * Gets the midtones Hue value.
  38480. * 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).
  38481. */
  38482. get: function () {
  38483. return this._midtonesHue;
  38484. },
  38485. /**
  38486. * Sets the midtones Hue value.
  38487. * 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).
  38488. */
  38489. set: function (value) {
  38490. this._midtonesHue = value;
  38491. this._dirty = true;
  38492. },
  38493. enumerable: true,
  38494. configurable: true
  38495. });
  38496. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  38497. /**
  38498. * Gets the midtones Density value.
  38499. * 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.
  38500. * Values less than zero provide a filter of opposite hue.
  38501. */
  38502. get: function () {
  38503. return this._midtonesDensity;
  38504. },
  38505. /**
  38506. * Sets the midtones Density value.
  38507. * 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.
  38508. * Values less than zero provide a filter of opposite hue.
  38509. */
  38510. set: function (value) {
  38511. this._midtonesDensity = value;
  38512. this._dirty = true;
  38513. },
  38514. enumerable: true,
  38515. configurable: true
  38516. });
  38517. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  38518. /**
  38519. * Gets the midtones Saturation value.
  38520. * 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.
  38521. */
  38522. get: function () {
  38523. return this._midtonesSaturation;
  38524. },
  38525. /**
  38526. * Sets the midtones Saturation value.
  38527. * 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.
  38528. */
  38529. set: function (value) {
  38530. this._midtonesSaturation = value;
  38531. this._dirty = true;
  38532. },
  38533. enumerable: true,
  38534. configurable: true
  38535. });
  38536. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  38537. /**
  38538. * Gets the midtones Exposure value.
  38539. * 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.
  38540. */
  38541. get: function () {
  38542. return this._midtonesExposure;
  38543. },
  38544. /**
  38545. * Sets the midtones Exposure value.
  38546. * 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.
  38547. */
  38548. set: function (value) {
  38549. this._midtonesExposure = value;
  38550. this._dirty = true;
  38551. },
  38552. enumerable: true,
  38553. configurable: true
  38554. });
  38555. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  38556. /**
  38557. * Gets the shadows Hue value.
  38558. * 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).
  38559. */
  38560. get: function () {
  38561. return this._shadowsHue;
  38562. },
  38563. /**
  38564. * Sets the shadows Hue value.
  38565. * 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).
  38566. */
  38567. set: function (value) {
  38568. this._shadowsHue = value;
  38569. this._dirty = true;
  38570. },
  38571. enumerable: true,
  38572. configurable: true
  38573. });
  38574. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  38575. /**
  38576. * Gets the shadows Density value.
  38577. * 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.
  38578. * Values less than zero provide a filter of opposite hue.
  38579. */
  38580. get: function () {
  38581. return this._shadowsDensity;
  38582. },
  38583. /**
  38584. * Sets the shadows Density value.
  38585. * 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.
  38586. * Values less than zero provide a filter of opposite hue.
  38587. */
  38588. set: function (value) {
  38589. this._shadowsDensity = value;
  38590. this._dirty = true;
  38591. },
  38592. enumerable: true,
  38593. configurable: true
  38594. });
  38595. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  38596. /**
  38597. * Gets the shadows Saturation value.
  38598. * 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.
  38599. */
  38600. get: function () {
  38601. return this._shadowsSaturation;
  38602. },
  38603. /**
  38604. * Sets the shadows Saturation value.
  38605. * 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.
  38606. */
  38607. set: function (value) {
  38608. this._shadowsSaturation = value;
  38609. this._dirty = true;
  38610. },
  38611. enumerable: true,
  38612. configurable: true
  38613. });
  38614. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  38615. /**
  38616. * Gets the shadows Exposure value.
  38617. * 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.
  38618. */
  38619. get: function () {
  38620. return this._shadowsExposure;
  38621. },
  38622. /**
  38623. * Sets the shadows Exposure value.
  38624. * 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.
  38625. */
  38626. set: function (value) {
  38627. this._shadowsExposure = value;
  38628. this._dirty = true;
  38629. },
  38630. enumerable: true,
  38631. configurable: true
  38632. });
  38633. ColorCurves.prototype.getClassName = function () {
  38634. return "ColorCurves";
  38635. };
  38636. /**
  38637. * Binds the color curves to the shader.
  38638. * @param colorCurves The color curve to bind
  38639. * @param effect The effect to bind to
  38640. */
  38641. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  38642. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  38643. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  38644. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  38645. if (colorCurves._dirty) {
  38646. colorCurves._dirty = false;
  38647. // Fill in global info.
  38648. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  38649. // Compute highlights info.
  38650. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  38651. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  38652. // Compute midtones info.
  38653. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  38654. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  38655. // Compute shadows info.
  38656. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  38657. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  38658. // Compute deltas (neutral is midtones).
  38659. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  38660. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  38661. }
  38662. if (effect) {
  38663. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  38664. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  38665. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  38666. }
  38667. };
  38668. /**
  38669. * Prepare the list of uniforms associated with the ColorCurves effects.
  38670. * @param uniformsList The list of uniforms used in the effect
  38671. */
  38672. ColorCurves.PrepareUniforms = function (uniformsList) {
  38673. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  38674. };
  38675. /**
  38676. * Returns color grading data based on a hue, density, saturation and exposure value.
  38677. * @param filterHue The hue of the color filter.
  38678. * @param filterDensity The density of the color filter.
  38679. * @param saturation The saturation.
  38680. * @param exposure The exposure.
  38681. * @param result The result data container.
  38682. */
  38683. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  38684. if (hue == null) {
  38685. return;
  38686. }
  38687. hue = ColorCurves.clamp(hue, 0, 360);
  38688. density = ColorCurves.clamp(density, -100, 100);
  38689. saturation = ColorCurves.clamp(saturation, -100, 100);
  38690. exposure = ColorCurves.clamp(exposure, -100, 100);
  38691. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38692. // so that the maximum filter density is only 50% control. This provides fine control
  38693. // for small values and reasonable range.
  38694. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38695. density *= 0.5;
  38696. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38697. if (density < 0) {
  38698. density *= -1;
  38699. hue = (hue + 180) % 360;
  38700. }
  38701. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38702. result.scaleToRef(2, result);
  38703. result.a = 1 + 0.01 * saturation;
  38704. };
  38705. /**
  38706. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38707. * @param value The input slider value in range [-100,100].
  38708. * @returns Adjusted value.
  38709. */
  38710. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38711. value /= 100;
  38712. var x = Math.abs(value);
  38713. x = Math.pow(x, 2);
  38714. if (value < 0) {
  38715. x *= -1;
  38716. }
  38717. x *= 100;
  38718. return x;
  38719. };
  38720. /**
  38721. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38722. * @param hue The hue (H) input.
  38723. * @param saturation The saturation (S) input.
  38724. * @param brightness The brightness (B) input.
  38725. * @result An RGBA color represented as Vector4.
  38726. */
  38727. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38728. var h = ColorCurves.clamp(hue, 0, 360);
  38729. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38730. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38731. if (s === 0) {
  38732. result.r = v;
  38733. result.g = v;
  38734. result.b = v;
  38735. }
  38736. else {
  38737. // sector 0 to 5
  38738. h /= 60;
  38739. var i = Math.floor(h);
  38740. // fractional part of h
  38741. var f = h - i;
  38742. var p = v * (1 - s);
  38743. var q = v * (1 - s * f);
  38744. var t = v * (1 - s * (1 - f));
  38745. switch (i) {
  38746. case 0:
  38747. result.r = v;
  38748. result.g = t;
  38749. result.b = p;
  38750. break;
  38751. case 1:
  38752. result.r = q;
  38753. result.g = v;
  38754. result.b = p;
  38755. break;
  38756. case 2:
  38757. result.r = p;
  38758. result.g = v;
  38759. result.b = t;
  38760. break;
  38761. case 3:
  38762. result.r = p;
  38763. result.g = q;
  38764. result.b = v;
  38765. break;
  38766. case 4:
  38767. result.r = t;
  38768. result.g = p;
  38769. result.b = v;
  38770. break;
  38771. default:// case 5:
  38772. result.r = v;
  38773. result.g = p;
  38774. result.b = q;
  38775. break;
  38776. }
  38777. }
  38778. result.a = 1;
  38779. };
  38780. /**
  38781. * Returns a value clamped between min and max
  38782. * @param value The value to clamp
  38783. * @param min The minimum of value
  38784. * @param max The maximum of value
  38785. * @returns The clamped value.
  38786. */
  38787. ColorCurves.clamp = function (value, min, max) {
  38788. return Math.min(Math.max(value, min), max);
  38789. };
  38790. /**
  38791. * Clones the current color curve instance.
  38792. * @return The cloned curves
  38793. */
  38794. ColorCurves.prototype.clone = function () {
  38795. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38796. };
  38797. /**
  38798. * Serializes the current color curve instance to a json representation.
  38799. * @return a JSON representation
  38800. */
  38801. ColorCurves.prototype.serialize = function () {
  38802. return BABYLON.SerializationHelper.Serialize(this);
  38803. };
  38804. /**
  38805. * Parses the color curve from a json representation.
  38806. * @param source the JSON source to parse
  38807. * @return The parsed curves
  38808. */
  38809. ColorCurves.Parse = function (source) {
  38810. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38811. };
  38812. __decorate([
  38813. BABYLON.serialize()
  38814. ], ColorCurves.prototype, "_globalHue", void 0);
  38815. __decorate([
  38816. BABYLON.serialize()
  38817. ], ColorCurves.prototype, "_globalDensity", void 0);
  38818. __decorate([
  38819. BABYLON.serialize()
  38820. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38821. __decorate([
  38822. BABYLON.serialize()
  38823. ], ColorCurves.prototype, "_globalExposure", void 0);
  38824. __decorate([
  38825. BABYLON.serialize()
  38826. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38827. __decorate([
  38828. BABYLON.serialize()
  38829. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38830. __decorate([
  38831. BABYLON.serialize()
  38832. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38833. __decorate([
  38834. BABYLON.serialize()
  38835. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38836. __decorate([
  38837. BABYLON.serialize()
  38838. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38839. __decorate([
  38840. BABYLON.serialize()
  38841. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38842. __decorate([
  38843. BABYLON.serialize()
  38844. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38845. __decorate([
  38846. BABYLON.serialize()
  38847. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38848. return ColorCurves;
  38849. }());
  38850. BABYLON.ColorCurves = ColorCurves;
  38851. })(BABYLON || (BABYLON = {}));
  38852. //# sourceMappingURL=babylon.colorCurves.js.map
  38853. "use strict";
  38854. //# sourceMappingURL=babylon.behavior.js.map
  38855. "use strict";
  38856. var BABYLON;
  38857. (function (BABYLON) {
  38858. /**
  38859. * "Static Class" containing the most commonly used helper while dealing with material for
  38860. * rendering purpose.
  38861. *
  38862. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38863. *
  38864. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38865. */
  38866. var MaterialHelper = /** @class */ (function () {
  38867. function MaterialHelper() {
  38868. }
  38869. /**
  38870. * Bind the current view position to an effect.
  38871. * @param effect The effect to be bound
  38872. * @param scene The scene the eyes position is used from
  38873. */
  38874. MaterialHelper.BindEyePosition = function (effect, scene) {
  38875. if (scene._forcedViewPosition) {
  38876. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38877. return;
  38878. }
  38879. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38880. };
  38881. /**
  38882. * Helps preparing the defines values about the UVs in used in the effect.
  38883. * UVs are shared as much as we can accross chanels in the shaders.
  38884. * @param texture The texture we are preparing the UVs for
  38885. * @param defines The defines to update
  38886. * @param key The chanel key "diffuse", "specular"... used in the shader
  38887. */
  38888. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38889. defines._needUVs = true;
  38890. defines[key] = true;
  38891. if (texture.getTextureMatrix().isIdentity(true)) {
  38892. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38893. if (texture.coordinatesIndex === 0) {
  38894. defines["MAINUV1"] = true;
  38895. }
  38896. else {
  38897. defines["MAINUV2"] = true;
  38898. }
  38899. }
  38900. else {
  38901. defines[key + "DIRECTUV"] = 0;
  38902. }
  38903. };
  38904. /**
  38905. * Binds a texture matrix value to its corrsponding uniform
  38906. * @param texture The texture to bind the matrix for
  38907. * @param uniformBuffer The uniform buffer receivin the data
  38908. * @param key The chanel key "diffuse", "specular"... used in the shader
  38909. */
  38910. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38911. var matrix = texture.getTextureMatrix();
  38912. if (!matrix.isIdentity(true)) {
  38913. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38914. }
  38915. };
  38916. /**
  38917. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38918. * @param mesh defines the current mesh
  38919. * @param scene defines the current scene
  38920. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38921. * @param pointsCloud defines if point cloud rendering has to be turned on
  38922. * @param fogEnabled defines if fog has to be turned on
  38923. * @param alphaTest defines if alpha testing has to be turned on
  38924. * @param defines defines the current list of defines
  38925. */
  38926. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38927. if (defines._areMiscDirty) {
  38928. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38929. defines["POINTSIZE"] = pointsCloud;
  38930. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38931. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38932. defines["ALPHATEST"] = alphaTest;
  38933. }
  38934. };
  38935. /**
  38936. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38937. * @param scene defines the current scene
  38938. * @param engine defines the current engine
  38939. * @param defines specifies the list of active defines
  38940. * @param useInstances defines if instances have to be turned on
  38941. * @param useClipPlane defines if clip plane have to be turned on
  38942. */
  38943. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38944. if (useClipPlane === void 0) { useClipPlane = null; }
  38945. var changed = false;
  38946. if (useClipPlane == null) {
  38947. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38948. }
  38949. if (defines["CLIPPLANE"] !== useClipPlane) {
  38950. defines["CLIPPLANE"] = useClipPlane;
  38951. changed = true;
  38952. }
  38953. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38954. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38955. changed = true;
  38956. }
  38957. if (defines["INSTANCES"] !== useInstances) {
  38958. defines["INSTANCES"] = useInstances;
  38959. changed = true;
  38960. }
  38961. if (changed) {
  38962. defines.markAsUnprocessed();
  38963. }
  38964. };
  38965. /**
  38966. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38967. * @param mesh The mesh containing the geometry data we will draw
  38968. * @param defines The defines to update
  38969. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38970. * @param useBones Precise whether bones should be used or not (override mesh info)
  38971. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38972. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38973. * @returns false if defines are considered not dirty and have not been checked
  38974. */
  38975. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38976. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38977. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38978. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38979. return false;
  38980. }
  38981. defines._normals = defines._needNormals;
  38982. defines._uvs = defines._needUVs;
  38983. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38984. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38985. defines["TANGENT"] = true;
  38986. }
  38987. if (defines._needUVs) {
  38988. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38989. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38990. }
  38991. else {
  38992. defines["UV1"] = false;
  38993. defines["UV2"] = false;
  38994. }
  38995. if (useVertexColor) {
  38996. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38997. defines["VERTEXCOLOR"] = hasVertexColors;
  38998. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38999. }
  39000. if (useBones) {
  39001. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  39002. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  39003. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  39004. }
  39005. else {
  39006. defines["NUM_BONE_INFLUENCERS"] = 0;
  39007. defines["BonesPerMesh"] = 0;
  39008. }
  39009. }
  39010. if (useMorphTargets) {
  39011. var manager = mesh.morphTargetManager;
  39012. if (manager) {
  39013. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  39014. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  39015. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  39016. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  39017. }
  39018. else {
  39019. defines["MORPHTARGETS_TANGENT"] = false;
  39020. defines["MORPHTARGETS_NORMAL"] = false;
  39021. defines["MORPHTARGETS"] = false;
  39022. defines["NUM_MORPH_INFLUENCERS"] = 0;
  39023. }
  39024. }
  39025. return true;
  39026. };
  39027. /**
  39028. * Prepares the defines related to the light information passed in parameter
  39029. * @param scene The scene we are intending to draw
  39030. * @param mesh The mesh the effect is compiling for
  39031. * @param defines The defines to update
  39032. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  39033. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  39034. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  39035. * @returns true if normals will be required for the rest of the effect
  39036. */
  39037. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  39038. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39039. if (disableLighting === void 0) { disableLighting = false; }
  39040. if (!defines._areLightsDirty) {
  39041. return defines._needNormals;
  39042. }
  39043. var lightIndex = 0;
  39044. var needNormals = false;
  39045. var needRebuild = false;
  39046. var lightmapMode = false;
  39047. var shadowEnabled = false;
  39048. var specularEnabled = false;
  39049. if (scene.lightsEnabled && !disableLighting) {
  39050. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  39051. var light = _a[_i];
  39052. needNormals = true;
  39053. if (defines["LIGHT" + lightIndex] === undefined) {
  39054. needRebuild = true;
  39055. }
  39056. defines["LIGHT" + lightIndex] = true;
  39057. defines["SPOTLIGHT" + lightIndex] = false;
  39058. defines["HEMILIGHT" + lightIndex] = false;
  39059. defines["POINTLIGHT" + lightIndex] = false;
  39060. defines["DIRLIGHT" + lightIndex] = false;
  39061. var type;
  39062. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  39063. type = "SPOTLIGHT" + lightIndex;
  39064. var spotLight = light;
  39065. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  39066. }
  39067. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  39068. type = "HEMILIGHT" + lightIndex;
  39069. }
  39070. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  39071. type = "POINTLIGHT" + lightIndex;
  39072. }
  39073. else {
  39074. type = "DIRLIGHT" + lightIndex;
  39075. }
  39076. defines[type] = true;
  39077. // Specular
  39078. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  39079. specularEnabled = true;
  39080. }
  39081. // Shadows
  39082. defines["SHADOW" + lightIndex] = false;
  39083. defines["SHADOWPCF" + lightIndex] = false;
  39084. defines["SHADOWPCSS" + lightIndex] = false;
  39085. defines["SHADOWPOISSON" + lightIndex] = false;
  39086. defines["SHADOWESM" + lightIndex] = false;
  39087. defines["SHADOWCUBE" + lightIndex] = false;
  39088. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  39089. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  39090. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  39091. var shadowGenerator = light.getShadowGenerator();
  39092. if (shadowGenerator) {
  39093. shadowEnabled = true;
  39094. shadowGenerator.prepareDefines(defines, lightIndex);
  39095. }
  39096. }
  39097. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  39098. lightmapMode = true;
  39099. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  39100. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  39101. }
  39102. else {
  39103. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  39104. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  39105. }
  39106. lightIndex++;
  39107. if (lightIndex === maxSimultaneousLights)
  39108. break;
  39109. }
  39110. }
  39111. defines["SPECULARTERM"] = specularEnabled;
  39112. defines["SHADOWS"] = shadowEnabled;
  39113. // Resetting all other lights if any
  39114. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  39115. if (defines["LIGHT" + index] !== undefined) {
  39116. defines["LIGHT" + index] = false;
  39117. defines["HEMILIGHT" + lightIndex] = false;
  39118. defines["POINTLIGHT" + lightIndex] = false;
  39119. defines["DIRLIGHT" + lightIndex] = false;
  39120. defines["SPOTLIGHT" + lightIndex] = false;
  39121. defines["SHADOW" + lightIndex] = false;
  39122. }
  39123. }
  39124. var caps = scene.getEngine().getCaps();
  39125. if (defines["SHADOWFLOAT"] === undefined) {
  39126. needRebuild = true;
  39127. }
  39128. defines["SHADOWFLOAT"] = shadowEnabled &&
  39129. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  39130. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  39131. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  39132. if (needRebuild) {
  39133. defines.rebuild();
  39134. }
  39135. return needNormals;
  39136. };
  39137. /**
  39138. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  39139. * that won t be acctive due to defines being turned off.
  39140. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  39141. * @param samplersList The samplers list
  39142. * @param defines The defines helping in the list generation
  39143. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  39144. */
  39145. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  39146. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39147. var uniformsList;
  39148. var uniformBuffersList = null;
  39149. if (uniformsListOrOptions.uniformsNames) {
  39150. var options = uniformsListOrOptions;
  39151. uniformsList = options.uniformsNames;
  39152. uniformBuffersList = options.uniformBuffersNames;
  39153. samplersList = options.samplers;
  39154. defines = options.defines;
  39155. maxSimultaneousLights = options.maxSimultaneousLights;
  39156. }
  39157. else {
  39158. uniformsList = uniformsListOrOptions;
  39159. if (!samplersList) {
  39160. samplersList = [];
  39161. }
  39162. }
  39163. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39164. if (!defines["LIGHT" + lightIndex]) {
  39165. break;
  39166. }
  39167. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  39168. if (uniformBuffersList) {
  39169. uniformBuffersList.push("Light" + lightIndex);
  39170. }
  39171. samplersList.push("shadowSampler" + lightIndex);
  39172. samplersList.push("depthSampler" + lightIndex);
  39173. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  39174. samplersList.push("projectionLightSampler" + lightIndex);
  39175. uniformsList.push("textureProjectionMatrix" + lightIndex);
  39176. }
  39177. }
  39178. if (defines["NUM_MORPH_INFLUENCERS"]) {
  39179. uniformsList.push("morphTargetInfluences");
  39180. }
  39181. };
  39182. /**
  39183. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  39184. * @param defines The defines to update while falling back
  39185. * @param fallbacks The authorized effect fallbacks
  39186. * @param maxSimultaneousLights The maximum number of lights allowed
  39187. * @param rank the current rank of the Effect
  39188. * @returns The newly affected rank
  39189. */
  39190. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  39191. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39192. if (rank === void 0) { rank = 0; }
  39193. var lightFallbackRank = 0;
  39194. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39195. if (!defines["LIGHT" + lightIndex]) {
  39196. break;
  39197. }
  39198. if (lightIndex > 0) {
  39199. lightFallbackRank = rank + lightIndex;
  39200. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  39201. }
  39202. if (!defines["SHADOWS"]) {
  39203. if (defines["SHADOW" + lightIndex]) {
  39204. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  39205. }
  39206. if (defines["SHADOWPCF" + lightIndex]) {
  39207. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  39208. }
  39209. if (defines["SHADOWPCSS" + lightIndex]) {
  39210. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  39211. }
  39212. if (defines["SHADOWPOISSON" + lightIndex]) {
  39213. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  39214. }
  39215. if (defines["SHADOWESM" + lightIndex]) {
  39216. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  39217. }
  39218. }
  39219. }
  39220. return lightFallbackRank++;
  39221. };
  39222. /**
  39223. * Prepares the list of attributes required for morph targets according to the effect defines.
  39224. * @param attribs The current list of supported attribs
  39225. * @param mesh The mesh to prepare the morph targets attributes for
  39226. * @param defines The current Defines of the effect
  39227. */
  39228. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  39229. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  39230. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  39231. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  39232. var manager = mesh.morphTargetManager;
  39233. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  39234. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  39235. for (var index = 0; index < influencers; index++) {
  39236. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  39237. if (normal) {
  39238. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  39239. }
  39240. if (tangent) {
  39241. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  39242. }
  39243. if (attribs.length > maxAttributesCount) {
  39244. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  39245. }
  39246. }
  39247. }
  39248. };
  39249. /**
  39250. * Prepares the list of attributes required for bones according to the effect defines.
  39251. * @param attribs The current list of supported attribs
  39252. * @param mesh The mesh to prepare the bones attributes for
  39253. * @param defines The current Defines of the effect
  39254. * @param fallbacks The current efffect fallback strategy
  39255. */
  39256. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  39257. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  39258. fallbacks.addCPUSkinningFallback(0, mesh);
  39259. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39260. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39261. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  39262. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39263. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39264. }
  39265. }
  39266. };
  39267. /**
  39268. * Prepares the list of attributes required for instances according to the effect defines.
  39269. * @param attribs The current list of supported attribs
  39270. * @param defines The current Defines of the effect
  39271. */
  39272. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  39273. if (defines["INSTANCES"]) {
  39274. attribs.push("world0");
  39275. attribs.push("world1");
  39276. attribs.push("world2");
  39277. attribs.push("world3");
  39278. }
  39279. };
  39280. /**
  39281. * Binds the light shadow information to the effect for the given mesh.
  39282. * @param light The light containing the generator
  39283. * @param scene The scene the lights belongs to
  39284. * @param mesh The mesh we are binding the information to render
  39285. * @param lightIndex The light index in the effect used to render the mesh
  39286. * @param effect The effect we are binding the data to
  39287. */
  39288. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  39289. if (light.shadowEnabled && mesh.receiveShadows) {
  39290. var shadowGenerator = light.getShadowGenerator();
  39291. if (shadowGenerator) {
  39292. shadowGenerator.bindShadowLight(lightIndex, effect);
  39293. }
  39294. }
  39295. };
  39296. /**
  39297. * Binds the light information to the effect.
  39298. * @param light The light containing the generator
  39299. * @param effect The effect we are binding the data to
  39300. * @param lightIndex The light index in the effect used to render
  39301. */
  39302. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  39303. light.transferToEffect(effect, lightIndex + "");
  39304. };
  39305. /**
  39306. * Binds the lights information from the scene to the effect for the given mesh.
  39307. * @param scene The scene the lights belongs to
  39308. * @param mesh The mesh we are binding the information to render
  39309. * @param effect The effect we are binding the data to
  39310. * @param defines The generated defines for the effect
  39311. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  39312. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  39313. */
  39314. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  39315. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39316. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  39317. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  39318. for (var i = 0; i < len; i++) {
  39319. var light = mesh._lightSources[i];
  39320. var iAsString = i.toString();
  39321. var scaledIntensity = light.getScaledIntensity();
  39322. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  39323. MaterialHelper.BindLightProperties(light, effect, i);
  39324. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  39325. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  39326. if (defines["SPECULARTERM"]) {
  39327. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  39328. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  39329. }
  39330. // Shadows
  39331. if (scene.shadowsEnabled) {
  39332. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  39333. }
  39334. light._uniformBuffer.update();
  39335. }
  39336. };
  39337. /**
  39338. * Binds the fog information from the scene to the effect for the given mesh.
  39339. * @param scene The scene the lights belongs to
  39340. * @param mesh The mesh we are binding the information to render
  39341. * @param effect The effect we are binding the data to
  39342. */
  39343. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  39344. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  39345. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  39346. effect.setColor3("vFogColor", scene.fogColor);
  39347. }
  39348. };
  39349. /**
  39350. * Binds the bones information from the mesh to the effect.
  39351. * @param mesh The mesh we are binding the information to render
  39352. * @param effect The effect we are binding the data to
  39353. */
  39354. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  39355. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  39356. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  39357. if (matrices && effect) {
  39358. effect.setMatrices("mBones", matrices);
  39359. }
  39360. }
  39361. };
  39362. /**
  39363. * Binds the morph targets information from the mesh to the effect.
  39364. * @param abstractMesh The mesh we are binding the information to render
  39365. * @param effect The effect we are binding the data to
  39366. */
  39367. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  39368. var manager = abstractMesh.morphTargetManager;
  39369. if (!abstractMesh || !manager) {
  39370. return;
  39371. }
  39372. effect.setFloatArray("morphTargetInfluences", manager.influences);
  39373. };
  39374. /**
  39375. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  39376. * @param defines The generated defines used in the effect
  39377. * @param effect The effect we are binding the data to
  39378. * @param scene The scene we are willing to render with logarithmic scale for
  39379. */
  39380. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  39381. if (defines["LOGARITHMICDEPTH"]) {
  39382. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  39383. }
  39384. };
  39385. /**
  39386. * Binds the clip plane information from the scene to the effect.
  39387. * @param scene The scene the clip plane information are extracted from
  39388. * @param effect The effect we are binding the data to
  39389. */
  39390. MaterialHelper.BindClipPlane = function (effect, scene) {
  39391. if (scene.clipPlane) {
  39392. var clipPlane = scene.clipPlane;
  39393. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  39394. }
  39395. };
  39396. return MaterialHelper;
  39397. }());
  39398. BABYLON.MaterialHelper = MaterialHelper;
  39399. })(BABYLON || (BABYLON = {}));
  39400. //# sourceMappingURL=babylon.materialHelper.js.map
  39401. "use strict";
  39402. var BABYLON;
  39403. (function (BABYLON) {
  39404. var PushMaterial = /** @class */ (function (_super) {
  39405. __extends(PushMaterial, _super);
  39406. function PushMaterial(name, scene) {
  39407. var _this = _super.call(this, name, scene) || this;
  39408. _this._normalMatrix = new BABYLON.Matrix();
  39409. _this.storeEffectOnSubMeshes = true;
  39410. return _this;
  39411. }
  39412. PushMaterial.prototype.getEffect = function () {
  39413. return this._activeEffect;
  39414. };
  39415. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  39416. if (!mesh) {
  39417. return false;
  39418. }
  39419. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  39420. return true;
  39421. }
  39422. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  39423. };
  39424. /**
  39425. * Binds the given world matrix to the active effect
  39426. *
  39427. * @param world the matrix to bind
  39428. */
  39429. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39430. this._activeEffect.setMatrix("world", world);
  39431. };
  39432. /**
  39433. * Binds the given normal matrix to the active effect
  39434. *
  39435. * @param normalMatrix the matrix to bind
  39436. */
  39437. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  39438. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  39439. };
  39440. PushMaterial.prototype.bind = function (world, mesh) {
  39441. if (!mesh) {
  39442. return;
  39443. }
  39444. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  39445. };
  39446. PushMaterial.prototype._afterBind = function (mesh, effect) {
  39447. if (effect === void 0) { effect = null; }
  39448. _super.prototype._afterBind.call(this, mesh);
  39449. this.getScene()._cachedEffect = effect;
  39450. };
  39451. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  39452. if (visibility === void 0) { visibility = 1; }
  39453. return scene.isCachedMaterialInvalid(this, effect, visibility);
  39454. };
  39455. return PushMaterial;
  39456. }(BABYLON.Material));
  39457. BABYLON.PushMaterial = PushMaterial;
  39458. })(BABYLON || (BABYLON = {}));
  39459. //# sourceMappingURL=babylon.pushMaterial.js.map
  39460. "use strict";
  39461. var BABYLON;
  39462. (function (BABYLON) {
  39463. /** @ignore */
  39464. var StandardMaterialDefines = /** @class */ (function (_super) {
  39465. __extends(StandardMaterialDefines, _super);
  39466. function StandardMaterialDefines() {
  39467. var _this = _super.call(this) || this;
  39468. _this.MAINUV1 = false;
  39469. _this.MAINUV2 = false;
  39470. _this.DIFFUSE = false;
  39471. _this.DIFFUSEDIRECTUV = 0;
  39472. _this.AMBIENT = false;
  39473. _this.AMBIENTDIRECTUV = 0;
  39474. _this.OPACITY = false;
  39475. _this.OPACITYDIRECTUV = 0;
  39476. _this.OPACITYRGB = false;
  39477. _this.REFLECTION = false;
  39478. _this.EMISSIVE = false;
  39479. _this.EMISSIVEDIRECTUV = 0;
  39480. _this.SPECULAR = false;
  39481. _this.SPECULARDIRECTUV = 0;
  39482. _this.BUMP = false;
  39483. _this.BUMPDIRECTUV = 0;
  39484. _this.PARALLAX = false;
  39485. _this.PARALLAXOCCLUSION = false;
  39486. _this.SPECULAROVERALPHA = false;
  39487. _this.CLIPPLANE = false;
  39488. _this.ALPHATEST = false;
  39489. _this.DEPTHPREPASS = false;
  39490. _this.ALPHAFROMDIFFUSE = false;
  39491. _this.POINTSIZE = false;
  39492. _this.FOG = false;
  39493. _this.SPECULARTERM = false;
  39494. _this.DIFFUSEFRESNEL = false;
  39495. _this.OPACITYFRESNEL = false;
  39496. _this.REFLECTIONFRESNEL = false;
  39497. _this.REFRACTIONFRESNEL = false;
  39498. _this.EMISSIVEFRESNEL = false;
  39499. _this.FRESNEL = false;
  39500. _this.NORMAL = false;
  39501. _this.UV1 = false;
  39502. _this.UV2 = false;
  39503. _this.VERTEXCOLOR = false;
  39504. _this.VERTEXALPHA = false;
  39505. _this.NUM_BONE_INFLUENCERS = 0;
  39506. _this.BonesPerMesh = 0;
  39507. _this.INSTANCES = false;
  39508. _this.GLOSSINESS = false;
  39509. _this.ROUGHNESS = false;
  39510. _this.EMISSIVEASILLUMINATION = false;
  39511. _this.LINKEMISSIVEWITHDIFFUSE = false;
  39512. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  39513. _this.LIGHTMAP = false;
  39514. _this.LIGHTMAPDIRECTUV = 0;
  39515. _this.OBJECTSPACE_NORMALMAP = false;
  39516. _this.USELIGHTMAPASSHADOWMAP = false;
  39517. _this.REFLECTIONMAP_3D = false;
  39518. _this.REFLECTIONMAP_SPHERICAL = false;
  39519. _this.REFLECTIONMAP_PLANAR = false;
  39520. _this.REFLECTIONMAP_CUBIC = false;
  39521. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39522. _this.REFLECTIONMAP_PROJECTION = false;
  39523. _this.REFLECTIONMAP_SKYBOX = false;
  39524. _this.REFLECTIONMAP_EXPLICIT = false;
  39525. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39526. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39527. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39528. _this.INVERTCUBICMAP = false;
  39529. _this.LOGARITHMICDEPTH = false;
  39530. _this.REFRACTION = false;
  39531. _this.REFRACTIONMAP_3D = false;
  39532. _this.REFLECTIONOVERALPHA = false;
  39533. _this.TWOSIDEDLIGHTING = false;
  39534. _this.SHADOWFLOAT = false;
  39535. _this.MORPHTARGETS = false;
  39536. _this.MORPHTARGETS_NORMAL = false;
  39537. _this.MORPHTARGETS_TANGENT = false;
  39538. _this.NUM_MORPH_INFLUENCERS = 0;
  39539. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  39540. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  39541. _this.IMAGEPROCESSING = false;
  39542. _this.VIGNETTE = false;
  39543. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39544. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39545. _this.TONEMAPPING = false;
  39546. _this.CONTRAST = false;
  39547. _this.COLORCURVES = false;
  39548. _this.COLORGRADING = false;
  39549. _this.COLORGRADING3D = false;
  39550. _this.SAMPLER3DGREENDEPTH = false;
  39551. _this.SAMPLER3DBGRMAP = false;
  39552. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39553. _this.EXPOSURE = false;
  39554. _this.GRAIN = false;
  39555. _this.rebuild();
  39556. return _this;
  39557. }
  39558. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  39559. var modes = [
  39560. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  39561. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  39562. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  39563. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  39564. ];
  39565. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  39566. var mode = modes_1[_i];
  39567. this[mode] = (mode === modeToEnable);
  39568. }
  39569. };
  39570. return StandardMaterialDefines;
  39571. }(BABYLON.MaterialDefines));
  39572. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  39573. var StandardMaterial = /** @class */ (function (_super) {
  39574. __extends(StandardMaterial, _super);
  39575. function StandardMaterial(name, scene) {
  39576. var _this = _super.call(this, name, scene) || this;
  39577. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39578. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  39579. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  39580. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39581. _this.specularPower = 64;
  39582. _this._useAlphaFromDiffuseTexture = false;
  39583. _this._useEmissiveAsIllumination = false;
  39584. _this._linkEmissiveWithDiffuse = false;
  39585. _this._useSpecularOverAlpha = false;
  39586. _this._useReflectionOverAlpha = false;
  39587. _this._disableLighting = false;
  39588. _this._useObjectSpaceNormalMap = false;
  39589. _this._useParallax = false;
  39590. _this._useParallaxOcclusion = false;
  39591. _this.parallaxScaleBias = 0.05;
  39592. _this._roughness = 0;
  39593. _this.indexOfRefraction = 0.98;
  39594. _this.invertRefractionY = true;
  39595. _this._useLightmapAsShadowmap = false;
  39596. _this._useReflectionFresnelFromSpecular = false;
  39597. _this._useGlossinessFromSpecularMapAlpha = false;
  39598. _this._maxSimultaneousLights = 4;
  39599. /**
  39600. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39601. */
  39602. _this._invertNormalMapX = false;
  39603. /**
  39604. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39605. */
  39606. _this._invertNormalMapY = false;
  39607. /**
  39608. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39609. */
  39610. _this._twoSidedLighting = false;
  39611. _this._renderTargets = new BABYLON.SmartArray(16);
  39612. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  39613. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39614. // Setup the default processing configuration to the scene.
  39615. _this._attachImageProcessingConfiguration(null);
  39616. _this.getRenderTargetTextures = function () {
  39617. _this._renderTargets.reset();
  39618. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39619. _this._renderTargets.push(_this._reflectionTexture);
  39620. }
  39621. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39622. _this._renderTargets.push(_this._refractionTexture);
  39623. }
  39624. return _this._renderTargets;
  39625. };
  39626. return _this;
  39627. }
  39628. ;
  39629. ;
  39630. ;
  39631. ;
  39632. ;
  39633. ;
  39634. ;
  39635. ;
  39636. ;
  39637. ;
  39638. ;
  39639. ;
  39640. ;
  39641. ;
  39642. ;
  39643. ;
  39644. ;
  39645. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  39646. /**
  39647. * Gets the image processing configuration used either in this material.
  39648. */
  39649. get: function () {
  39650. return this._imageProcessingConfiguration;
  39651. },
  39652. /**
  39653. * Sets the Default image processing configuration used either in the this material.
  39654. *
  39655. * If sets to null, the scene one is in use.
  39656. */
  39657. set: function (value) {
  39658. this._attachImageProcessingConfiguration(value);
  39659. // Ensure the effect will be rebuilt.
  39660. this._markAllSubMeshesAsTexturesDirty();
  39661. },
  39662. enumerable: true,
  39663. configurable: true
  39664. });
  39665. /**
  39666. * Attaches a new image processing configuration to the Standard Material.
  39667. * @param configuration
  39668. */
  39669. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39670. var _this = this;
  39671. if (configuration === this._imageProcessingConfiguration) {
  39672. return;
  39673. }
  39674. // Detaches observer.
  39675. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39676. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39677. }
  39678. // Pick the scene configuration if needed.
  39679. if (!configuration) {
  39680. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39681. }
  39682. else {
  39683. this._imageProcessingConfiguration = configuration;
  39684. }
  39685. // Attaches observer.
  39686. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39687. _this._markAllSubMeshesAsImageProcessingDirty();
  39688. });
  39689. };
  39690. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  39691. /**
  39692. * Gets wether the color curves effect is enabled.
  39693. */
  39694. get: function () {
  39695. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39696. },
  39697. /**
  39698. * Sets wether the color curves effect is enabled.
  39699. */
  39700. set: function (value) {
  39701. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39702. },
  39703. enumerable: true,
  39704. configurable: true
  39705. });
  39706. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39707. /**
  39708. * Gets wether the color grading effect is enabled.
  39709. */
  39710. get: function () {
  39711. return this.imageProcessingConfiguration.colorGradingEnabled;
  39712. },
  39713. /**
  39714. * Gets wether the color grading effect is enabled.
  39715. */
  39716. set: function (value) {
  39717. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39718. },
  39719. enumerable: true,
  39720. configurable: true
  39721. });
  39722. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39723. /**
  39724. * Gets wether tonemapping is enabled or not.
  39725. */
  39726. get: function () {
  39727. return this._imageProcessingConfiguration.toneMappingEnabled;
  39728. },
  39729. /**
  39730. * Sets wether tonemapping is enabled or not
  39731. */
  39732. set: function (value) {
  39733. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39734. },
  39735. enumerable: true,
  39736. configurable: true
  39737. });
  39738. ;
  39739. ;
  39740. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39741. /**
  39742. * The camera exposure used on this material.
  39743. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39744. * This corresponds to a photographic exposure.
  39745. */
  39746. get: function () {
  39747. return this._imageProcessingConfiguration.exposure;
  39748. },
  39749. /**
  39750. * The camera exposure used on this material.
  39751. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39752. * This corresponds to a photographic exposure.
  39753. */
  39754. set: function (value) {
  39755. this._imageProcessingConfiguration.exposure = value;
  39756. },
  39757. enumerable: true,
  39758. configurable: true
  39759. });
  39760. ;
  39761. ;
  39762. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39763. /**
  39764. * Gets The camera contrast used on this material.
  39765. */
  39766. get: function () {
  39767. return this._imageProcessingConfiguration.contrast;
  39768. },
  39769. /**
  39770. * Sets The camera contrast used on this material.
  39771. */
  39772. set: function (value) {
  39773. this._imageProcessingConfiguration.contrast = value;
  39774. },
  39775. enumerable: true,
  39776. configurable: true
  39777. });
  39778. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39779. /**
  39780. * Gets the Color Grading 2D Lookup Texture.
  39781. */
  39782. get: function () {
  39783. return this._imageProcessingConfiguration.colorGradingTexture;
  39784. },
  39785. /**
  39786. * Sets the Color Grading 2D Lookup Texture.
  39787. */
  39788. set: function (value) {
  39789. this._imageProcessingConfiguration.colorGradingTexture = value;
  39790. },
  39791. enumerable: true,
  39792. configurable: true
  39793. });
  39794. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39795. /**
  39796. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39797. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39798. * 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;
  39799. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39800. */
  39801. get: function () {
  39802. return this._imageProcessingConfiguration.colorCurves;
  39803. },
  39804. /**
  39805. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39806. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39807. * 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;
  39808. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39809. */
  39810. set: function (value) {
  39811. this._imageProcessingConfiguration.colorCurves = value;
  39812. },
  39813. enumerable: true,
  39814. configurable: true
  39815. });
  39816. StandardMaterial.prototype.getClassName = function () {
  39817. return "StandardMaterial";
  39818. };
  39819. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39820. get: function () {
  39821. return this._useLogarithmicDepth;
  39822. },
  39823. set: function (value) {
  39824. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39825. this._markAllSubMeshesAsMiscDirty();
  39826. },
  39827. enumerable: true,
  39828. configurable: true
  39829. });
  39830. StandardMaterial.prototype.needAlphaBlending = function () {
  39831. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39832. };
  39833. StandardMaterial.prototype.needAlphaTesting = function () {
  39834. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39835. };
  39836. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39837. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39838. };
  39839. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39840. return this._diffuseTexture;
  39841. };
  39842. /**
  39843. * Child classes can use it to update shaders
  39844. */
  39845. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39846. if (useInstances === void 0) { useInstances = false; }
  39847. if (subMesh.effect && this.isFrozen) {
  39848. if (this._wasPreviouslyReady && subMesh.effect) {
  39849. return true;
  39850. }
  39851. }
  39852. if (!subMesh._materialDefines) {
  39853. subMesh._materialDefines = new StandardMaterialDefines();
  39854. }
  39855. var scene = this.getScene();
  39856. var defines = subMesh._materialDefines;
  39857. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39858. if (defines._renderId === scene.getRenderId()) {
  39859. return true;
  39860. }
  39861. }
  39862. var engine = scene.getEngine();
  39863. // Lights
  39864. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39865. // Textures
  39866. if (defines._areTexturesDirty) {
  39867. defines._needUVs = false;
  39868. defines.MAINUV1 = false;
  39869. defines.MAINUV2 = false;
  39870. if (scene.texturesEnabled) {
  39871. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39872. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39873. return false;
  39874. }
  39875. else {
  39876. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39877. }
  39878. }
  39879. else {
  39880. defines.DIFFUSE = false;
  39881. }
  39882. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39883. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39884. return false;
  39885. }
  39886. else {
  39887. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39888. }
  39889. }
  39890. else {
  39891. defines.AMBIENT = false;
  39892. }
  39893. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39894. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39895. return false;
  39896. }
  39897. else {
  39898. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39899. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39900. }
  39901. }
  39902. else {
  39903. defines.OPACITY = false;
  39904. }
  39905. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39906. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39907. return false;
  39908. }
  39909. else {
  39910. defines._needNormals = true;
  39911. defines.REFLECTION = true;
  39912. defines.ROUGHNESS = (this._roughness > 0);
  39913. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39914. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39915. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39916. switch (this._reflectionTexture.coordinatesMode) {
  39917. case BABYLON.Texture.CUBIC_MODE:
  39918. case BABYLON.Texture.INVCUBIC_MODE:
  39919. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39920. break;
  39921. case BABYLON.Texture.EXPLICIT_MODE:
  39922. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39923. break;
  39924. case BABYLON.Texture.PLANAR_MODE:
  39925. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39926. break;
  39927. case BABYLON.Texture.PROJECTION_MODE:
  39928. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39929. break;
  39930. case BABYLON.Texture.SKYBOX_MODE:
  39931. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39932. break;
  39933. case BABYLON.Texture.SPHERICAL_MODE:
  39934. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39935. break;
  39936. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39937. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39938. break;
  39939. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39940. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39941. break;
  39942. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39943. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39944. break;
  39945. }
  39946. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39947. }
  39948. }
  39949. else {
  39950. defines.REFLECTION = false;
  39951. }
  39952. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39953. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39954. return false;
  39955. }
  39956. else {
  39957. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39958. }
  39959. }
  39960. else {
  39961. defines.EMISSIVE = false;
  39962. }
  39963. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39964. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39965. return false;
  39966. }
  39967. else {
  39968. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39969. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39970. }
  39971. }
  39972. else {
  39973. defines.LIGHTMAP = false;
  39974. }
  39975. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39976. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39977. return false;
  39978. }
  39979. else {
  39980. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39981. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39982. }
  39983. }
  39984. else {
  39985. defines.SPECULAR = false;
  39986. }
  39987. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39988. // Bump texure can not be not blocking.
  39989. if (!this._bumpTexture.isReady()) {
  39990. return false;
  39991. }
  39992. else {
  39993. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39994. defines.PARALLAX = this._useParallax;
  39995. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39996. }
  39997. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39998. }
  39999. else {
  40000. defines.BUMP = false;
  40001. }
  40002. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40003. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  40004. return false;
  40005. }
  40006. else {
  40007. defines._needUVs = true;
  40008. defines.REFRACTION = true;
  40009. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  40010. }
  40011. }
  40012. else {
  40013. defines.REFRACTION = false;
  40014. }
  40015. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  40016. }
  40017. else {
  40018. defines.DIFFUSE = false;
  40019. defines.AMBIENT = false;
  40020. defines.OPACITY = false;
  40021. defines.REFLECTION = false;
  40022. defines.EMISSIVE = false;
  40023. defines.LIGHTMAP = false;
  40024. defines.BUMP = false;
  40025. defines.REFRACTION = false;
  40026. }
  40027. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  40028. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  40029. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  40030. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  40031. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  40032. }
  40033. if (defines._areImageProcessingDirty) {
  40034. if (!this._imageProcessingConfiguration.isReady()) {
  40035. return false;
  40036. }
  40037. this._imageProcessingConfiguration.prepareDefines(defines);
  40038. }
  40039. if (defines._areFresnelDirty) {
  40040. if (StandardMaterial.FresnelEnabled) {
  40041. // Fresnel
  40042. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  40043. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  40044. this._reflectionFresnelParameters) {
  40045. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  40046. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  40047. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  40048. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  40049. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  40050. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  40051. defines._needNormals = true;
  40052. defines.FRESNEL = true;
  40053. }
  40054. }
  40055. else {
  40056. defines.FRESNEL = false;
  40057. }
  40058. }
  40059. // Misc.
  40060. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  40061. // Attribs
  40062. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  40063. // Values that need to be evaluated on every frame
  40064. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  40065. // Get correct effect
  40066. if (defines.isDirty) {
  40067. defines.markAsProcessed();
  40068. scene.resetCachedMaterial();
  40069. // Fallbacks
  40070. var fallbacks = new BABYLON.EffectFallbacks();
  40071. if (defines.REFLECTION) {
  40072. fallbacks.addFallback(0, "REFLECTION");
  40073. }
  40074. if (defines.SPECULAR) {
  40075. fallbacks.addFallback(0, "SPECULAR");
  40076. }
  40077. if (defines.BUMP) {
  40078. fallbacks.addFallback(0, "BUMP");
  40079. }
  40080. if (defines.PARALLAX) {
  40081. fallbacks.addFallback(1, "PARALLAX");
  40082. }
  40083. if (defines.PARALLAXOCCLUSION) {
  40084. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  40085. }
  40086. if (defines.SPECULAROVERALPHA) {
  40087. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  40088. }
  40089. if (defines.FOG) {
  40090. fallbacks.addFallback(1, "FOG");
  40091. }
  40092. if (defines.POINTSIZE) {
  40093. fallbacks.addFallback(0, "POINTSIZE");
  40094. }
  40095. if (defines.LOGARITHMICDEPTH) {
  40096. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  40097. }
  40098. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  40099. if (defines.SPECULARTERM) {
  40100. fallbacks.addFallback(0, "SPECULARTERM");
  40101. }
  40102. if (defines.DIFFUSEFRESNEL) {
  40103. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  40104. }
  40105. if (defines.OPACITYFRESNEL) {
  40106. fallbacks.addFallback(2, "OPACITYFRESNEL");
  40107. }
  40108. if (defines.REFLECTIONFRESNEL) {
  40109. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  40110. }
  40111. if (defines.EMISSIVEFRESNEL) {
  40112. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  40113. }
  40114. if (defines.FRESNEL) {
  40115. fallbacks.addFallback(4, "FRESNEL");
  40116. }
  40117. //Attributes
  40118. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40119. if (defines.NORMAL) {
  40120. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40121. }
  40122. if (defines.UV1) {
  40123. attribs.push(BABYLON.VertexBuffer.UVKind);
  40124. }
  40125. if (defines.UV2) {
  40126. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40127. }
  40128. if (defines.VERTEXCOLOR) {
  40129. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40130. }
  40131. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40132. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40133. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40134. var shaderName = "default";
  40135. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  40136. "vFogInfos", "vFogColor", "pointSize",
  40137. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40138. "mBones",
  40139. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  40140. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  40141. "vReflectionPosition", "vReflectionSize",
  40142. "logarithmicDepthConstant", "vTangentSpaceParams"
  40143. ];
  40144. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  40145. var uniformBuffers = ["Material", "Scene"];
  40146. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40147. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40148. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40149. uniformsNames: uniforms,
  40150. uniformBuffersNames: uniformBuffers,
  40151. samplers: samplers,
  40152. defines: defines,
  40153. maxSimultaneousLights: this._maxSimultaneousLights
  40154. });
  40155. if (this.customShaderNameResolve) {
  40156. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  40157. }
  40158. var join = defines.toString();
  40159. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  40160. attributes: attribs,
  40161. uniformsNames: uniforms,
  40162. uniformBuffersNames: uniformBuffers,
  40163. samplers: samplers,
  40164. defines: join,
  40165. fallbacks: fallbacks,
  40166. onCompiled: this.onCompiled,
  40167. onError: this.onError,
  40168. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40169. }, engine), defines);
  40170. this.buildUniformLayout();
  40171. }
  40172. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40173. return false;
  40174. }
  40175. defines._renderId = scene.getRenderId();
  40176. this._wasPreviouslyReady = true;
  40177. return true;
  40178. };
  40179. StandardMaterial.prototype.buildUniformLayout = function () {
  40180. // Order is important !
  40181. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  40182. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  40183. this._uniformBuffer.addUniform("opacityParts", 4);
  40184. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  40185. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  40186. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  40187. this._uniformBuffer.addUniform("refractionRightColor", 4);
  40188. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  40189. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  40190. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  40191. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  40192. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40193. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40194. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  40195. this._uniformBuffer.addUniform("vReflectionSize", 3);
  40196. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40197. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40198. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  40199. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40200. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  40201. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40202. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40203. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40204. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40205. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40206. this._uniformBuffer.addUniform("specularMatrix", 16);
  40207. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40208. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  40209. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40210. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40211. this._uniformBuffer.addUniform("vSpecularColor", 4);
  40212. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40213. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  40214. this._uniformBuffer.addUniform("pointSize", 1);
  40215. this._uniformBuffer.create();
  40216. };
  40217. StandardMaterial.prototype.unbind = function () {
  40218. if (this._activeEffect) {
  40219. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40220. this._activeEffect.setTexture("reflection2DSampler", null);
  40221. }
  40222. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40223. this._activeEffect.setTexture("refraction2DSampler", null);
  40224. }
  40225. }
  40226. _super.prototype.unbind.call(this);
  40227. };
  40228. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40229. var scene = this.getScene();
  40230. var defines = subMesh._materialDefines;
  40231. if (!defines) {
  40232. return;
  40233. }
  40234. var effect = subMesh.effect;
  40235. if (!effect) {
  40236. return;
  40237. }
  40238. this._activeEffect = effect;
  40239. // Matrices
  40240. this.bindOnlyWorldMatrix(world);
  40241. // Normal Matrix
  40242. if (defines.OBJECTSPACE_NORMALMAP) {
  40243. world.toNormalMatrix(this._normalMatrix);
  40244. this.bindOnlyNormalMatrix(this._normalMatrix);
  40245. }
  40246. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40247. // Bones
  40248. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  40249. if (mustRebind) {
  40250. this._uniformBuffer.bindToEffect(effect, "Material");
  40251. this.bindViewProjection(effect);
  40252. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40253. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  40254. // Fresnel
  40255. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  40256. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  40257. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  40258. }
  40259. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  40260. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  40261. }
  40262. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  40263. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  40264. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  40265. }
  40266. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  40267. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  40268. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  40269. }
  40270. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  40271. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  40272. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  40273. }
  40274. }
  40275. // Textures
  40276. if (scene.texturesEnabled) {
  40277. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40278. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  40279. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  40280. }
  40281. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40282. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  40283. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40284. }
  40285. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40286. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40287. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40288. }
  40289. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40290. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  40291. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  40292. if (this._reflectionTexture.boundingBoxSize) {
  40293. var cubeTexture = this._reflectionTexture;
  40294. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  40295. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  40296. }
  40297. }
  40298. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40299. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  40300. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  40301. }
  40302. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40303. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  40304. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  40305. }
  40306. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40307. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  40308. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  40309. }
  40310. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40311. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  40312. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  40313. if (scene._mirroredCameraPosition) {
  40314. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  40315. }
  40316. else {
  40317. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  40318. }
  40319. }
  40320. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40321. var depth = 1.0;
  40322. if (!this._refractionTexture.isCube) {
  40323. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  40324. if (this._refractionTexture.depth) {
  40325. depth = this._refractionTexture.depth;
  40326. }
  40327. }
  40328. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  40329. }
  40330. }
  40331. // Point size
  40332. if (this.pointsCloud) {
  40333. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  40334. }
  40335. if (defines.SPECULARTERM) {
  40336. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  40337. }
  40338. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  40339. // Diffuse
  40340. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  40341. }
  40342. // Textures
  40343. if (scene.texturesEnabled) {
  40344. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40345. effect.setTexture("diffuseSampler", this._diffuseTexture);
  40346. }
  40347. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40348. effect.setTexture("ambientSampler", this._ambientTexture);
  40349. }
  40350. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40351. effect.setTexture("opacitySampler", this._opacityTexture);
  40352. }
  40353. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40354. if (this._reflectionTexture.isCube) {
  40355. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  40356. }
  40357. else {
  40358. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  40359. }
  40360. }
  40361. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40362. effect.setTexture("emissiveSampler", this._emissiveTexture);
  40363. }
  40364. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40365. effect.setTexture("lightmapSampler", this._lightmapTexture);
  40366. }
  40367. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40368. effect.setTexture("specularSampler", this._specularTexture);
  40369. }
  40370. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40371. effect.setTexture("bumpSampler", this._bumpTexture);
  40372. }
  40373. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40374. var depth = 1.0;
  40375. if (this._refractionTexture.isCube) {
  40376. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  40377. }
  40378. else {
  40379. effect.setTexture("refraction2DSampler", this._refractionTexture);
  40380. }
  40381. }
  40382. }
  40383. // Clip plane
  40384. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  40385. // Colors
  40386. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  40387. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  40388. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  40389. }
  40390. if (mustRebind || !this.isFrozen) {
  40391. // Lights
  40392. if (scene.lightsEnabled && !this._disableLighting) {
  40393. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  40394. }
  40395. // View
  40396. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  40397. this.bindView(effect);
  40398. }
  40399. // Fog
  40400. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  40401. // Morph targets
  40402. if (defines.NUM_MORPH_INFLUENCERS) {
  40403. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  40404. }
  40405. // Log. depth
  40406. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  40407. // image processing
  40408. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  40409. this._imageProcessingConfiguration.bind(this._activeEffect);
  40410. }
  40411. }
  40412. this._uniformBuffer.update();
  40413. this._afterBind(mesh, this._activeEffect);
  40414. };
  40415. StandardMaterial.prototype.getAnimatables = function () {
  40416. var results = [];
  40417. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  40418. results.push(this._diffuseTexture);
  40419. }
  40420. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  40421. results.push(this._ambientTexture);
  40422. }
  40423. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  40424. results.push(this._opacityTexture);
  40425. }
  40426. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  40427. results.push(this._reflectionTexture);
  40428. }
  40429. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  40430. results.push(this._emissiveTexture);
  40431. }
  40432. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  40433. results.push(this._specularTexture);
  40434. }
  40435. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  40436. results.push(this._bumpTexture);
  40437. }
  40438. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  40439. results.push(this._lightmapTexture);
  40440. }
  40441. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  40442. results.push(this._refractionTexture);
  40443. }
  40444. return results;
  40445. };
  40446. StandardMaterial.prototype.getActiveTextures = function () {
  40447. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40448. if (this._diffuseTexture) {
  40449. activeTextures.push(this._diffuseTexture);
  40450. }
  40451. if (this._ambientTexture) {
  40452. activeTextures.push(this._ambientTexture);
  40453. }
  40454. if (this._opacityTexture) {
  40455. activeTextures.push(this._opacityTexture);
  40456. }
  40457. if (this._reflectionTexture) {
  40458. activeTextures.push(this._reflectionTexture);
  40459. }
  40460. if (this._emissiveTexture) {
  40461. activeTextures.push(this._emissiveTexture);
  40462. }
  40463. if (this._specularTexture) {
  40464. activeTextures.push(this._specularTexture);
  40465. }
  40466. if (this._bumpTexture) {
  40467. activeTextures.push(this._bumpTexture);
  40468. }
  40469. if (this._lightmapTexture) {
  40470. activeTextures.push(this._lightmapTexture);
  40471. }
  40472. if (this._refractionTexture) {
  40473. activeTextures.push(this._refractionTexture);
  40474. }
  40475. return activeTextures;
  40476. };
  40477. StandardMaterial.prototype.hasTexture = function (texture) {
  40478. if (_super.prototype.hasTexture.call(this, texture)) {
  40479. return true;
  40480. }
  40481. if (this._diffuseTexture === texture) {
  40482. return true;
  40483. }
  40484. if (this._ambientTexture === texture) {
  40485. return true;
  40486. }
  40487. if (this._opacityTexture === texture) {
  40488. return true;
  40489. }
  40490. if (this._reflectionTexture === texture) {
  40491. return true;
  40492. }
  40493. if (this._emissiveTexture === texture) {
  40494. return true;
  40495. }
  40496. if (this._specularTexture === texture) {
  40497. return true;
  40498. }
  40499. if (this._bumpTexture === texture) {
  40500. return true;
  40501. }
  40502. if (this._lightmapTexture === texture) {
  40503. return true;
  40504. }
  40505. if (this._refractionTexture === texture) {
  40506. return true;
  40507. }
  40508. return false;
  40509. };
  40510. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40511. if (forceDisposeTextures) {
  40512. if (this._diffuseTexture) {
  40513. this._diffuseTexture.dispose();
  40514. }
  40515. if (this._ambientTexture) {
  40516. this._ambientTexture.dispose();
  40517. }
  40518. if (this._opacityTexture) {
  40519. this._opacityTexture.dispose();
  40520. }
  40521. if (this._reflectionTexture) {
  40522. this._reflectionTexture.dispose();
  40523. }
  40524. if (this._emissiveTexture) {
  40525. this._emissiveTexture.dispose();
  40526. }
  40527. if (this._specularTexture) {
  40528. this._specularTexture.dispose();
  40529. }
  40530. if (this._bumpTexture) {
  40531. this._bumpTexture.dispose();
  40532. }
  40533. if (this._lightmapTexture) {
  40534. this._lightmapTexture.dispose();
  40535. }
  40536. if (this._refractionTexture) {
  40537. this._refractionTexture.dispose();
  40538. }
  40539. }
  40540. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40541. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40542. }
  40543. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40544. };
  40545. StandardMaterial.prototype.clone = function (name) {
  40546. var _this = this;
  40547. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  40548. result.name = name;
  40549. result.id = name;
  40550. return result;
  40551. };
  40552. StandardMaterial.prototype.serialize = function () {
  40553. return BABYLON.SerializationHelper.Serialize(this);
  40554. };
  40555. // Statics
  40556. StandardMaterial.Parse = function (source, scene, rootUrl) {
  40557. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  40558. };
  40559. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  40560. get: function () {
  40561. return StandardMaterial._DiffuseTextureEnabled;
  40562. },
  40563. set: function (value) {
  40564. if (StandardMaterial._DiffuseTextureEnabled === value) {
  40565. return;
  40566. }
  40567. StandardMaterial._DiffuseTextureEnabled = value;
  40568. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40569. },
  40570. enumerable: true,
  40571. configurable: true
  40572. });
  40573. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  40574. get: function () {
  40575. return StandardMaterial._AmbientTextureEnabled;
  40576. },
  40577. set: function (value) {
  40578. if (StandardMaterial._AmbientTextureEnabled === value) {
  40579. return;
  40580. }
  40581. StandardMaterial._AmbientTextureEnabled = value;
  40582. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40583. },
  40584. enumerable: true,
  40585. configurable: true
  40586. });
  40587. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  40588. get: function () {
  40589. return StandardMaterial._OpacityTextureEnabled;
  40590. },
  40591. set: function (value) {
  40592. if (StandardMaterial._OpacityTextureEnabled === value) {
  40593. return;
  40594. }
  40595. StandardMaterial._OpacityTextureEnabled = value;
  40596. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40597. },
  40598. enumerable: true,
  40599. configurable: true
  40600. });
  40601. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  40602. get: function () {
  40603. return StandardMaterial._ReflectionTextureEnabled;
  40604. },
  40605. set: function (value) {
  40606. if (StandardMaterial._ReflectionTextureEnabled === value) {
  40607. return;
  40608. }
  40609. StandardMaterial._ReflectionTextureEnabled = value;
  40610. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40611. },
  40612. enumerable: true,
  40613. configurable: true
  40614. });
  40615. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  40616. get: function () {
  40617. return StandardMaterial._EmissiveTextureEnabled;
  40618. },
  40619. set: function (value) {
  40620. if (StandardMaterial._EmissiveTextureEnabled === value) {
  40621. return;
  40622. }
  40623. StandardMaterial._EmissiveTextureEnabled = value;
  40624. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40625. },
  40626. enumerable: true,
  40627. configurable: true
  40628. });
  40629. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  40630. get: function () {
  40631. return StandardMaterial._SpecularTextureEnabled;
  40632. },
  40633. set: function (value) {
  40634. if (StandardMaterial._SpecularTextureEnabled === value) {
  40635. return;
  40636. }
  40637. StandardMaterial._SpecularTextureEnabled = value;
  40638. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40639. },
  40640. enumerable: true,
  40641. configurable: true
  40642. });
  40643. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  40644. get: function () {
  40645. return StandardMaterial._BumpTextureEnabled;
  40646. },
  40647. set: function (value) {
  40648. if (StandardMaterial._BumpTextureEnabled === value) {
  40649. return;
  40650. }
  40651. StandardMaterial._BumpTextureEnabled = value;
  40652. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40653. },
  40654. enumerable: true,
  40655. configurable: true
  40656. });
  40657. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  40658. get: function () {
  40659. return StandardMaterial._LightmapTextureEnabled;
  40660. },
  40661. set: function (value) {
  40662. if (StandardMaterial._LightmapTextureEnabled === value) {
  40663. return;
  40664. }
  40665. StandardMaterial._LightmapTextureEnabled = value;
  40666. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40667. },
  40668. enumerable: true,
  40669. configurable: true
  40670. });
  40671. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  40672. get: function () {
  40673. return StandardMaterial._RefractionTextureEnabled;
  40674. },
  40675. set: function (value) {
  40676. if (StandardMaterial._RefractionTextureEnabled === value) {
  40677. return;
  40678. }
  40679. StandardMaterial._RefractionTextureEnabled = value;
  40680. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40681. },
  40682. enumerable: true,
  40683. configurable: true
  40684. });
  40685. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  40686. get: function () {
  40687. return StandardMaterial._ColorGradingTextureEnabled;
  40688. },
  40689. set: function (value) {
  40690. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  40691. return;
  40692. }
  40693. StandardMaterial._ColorGradingTextureEnabled = value;
  40694. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40695. },
  40696. enumerable: true,
  40697. configurable: true
  40698. });
  40699. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  40700. get: function () {
  40701. return StandardMaterial._FresnelEnabled;
  40702. },
  40703. set: function (value) {
  40704. if (StandardMaterial._FresnelEnabled === value) {
  40705. return;
  40706. }
  40707. StandardMaterial._FresnelEnabled = value;
  40708. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40709. },
  40710. enumerable: true,
  40711. configurable: true
  40712. });
  40713. // Flags used to enable or disable a type of texture for all Standard Materials
  40714. StandardMaterial._DiffuseTextureEnabled = true;
  40715. StandardMaterial._AmbientTextureEnabled = true;
  40716. StandardMaterial._OpacityTextureEnabled = true;
  40717. StandardMaterial._ReflectionTextureEnabled = true;
  40718. StandardMaterial._EmissiveTextureEnabled = true;
  40719. StandardMaterial._SpecularTextureEnabled = true;
  40720. StandardMaterial._BumpTextureEnabled = true;
  40721. StandardMaterial._LightmapTextureEnabled = true;
  40722. StandardMaterial._RefractionTextureEnabled = true;
  40723. StandardMaterial._ColorGradingTextureEnabled = true;
  40724. StandardMaterial._FresnelEnabled = true;
  40725. __decorate([
  40726. BABYLON.serializeAsTexture("diffuseTexture")
  40727. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40728. __decorate([
  40729. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40730. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40731. __decorate([
  40732. BABYLON.serializeAsTexture("ambientTexture")
  40733. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40734. __decorate([
  40735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40736. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40737. __decorate([
  40738. BABYLON.serializeAsTexture("opacityTexture")
  40739. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40740. __decorate([
  40741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40742. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40743. __decorate([
  40744. BABYLON.serializeAsTexture("reflectionTexture")
  40745. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40746. __decorate([
  40747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40748. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40749. __decorate([
  40750. BABYLON.serializeAsTexture("emissiveTexture")
  40751. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40752. __decorate([
  40753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40754. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40755. __decorate([
  40756. BABYLON.serializeAsTexture("specularTexture")
  40757. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40758. __decorate([
  40759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40760. ], StandardMaterial.prototype, "specularTexture", void 0);
  40761. __decorate([
  40762. BABYLON.serializeAsTexture("bumpTexture")
  40763. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40764. __decorate([
  40765. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40766. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40767. __decorate([
  40768. BABYLON.serializeAsTexture("lightmapTexture")
  40769. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40770. __decorate([
  40771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40772. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40773. __decorate([
  40774. BABYLON.serializeAsTexture("refractionTexture")
  40775. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40776. __decorate([
  40777. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40778. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40779. __decorate([
  40780. BABYLON.serializeAsColor3("ambient")
  40781. ], StandardMaterial.prototype, "ambientColor", void 0);
  40782. __decorate([
  40783. BABYLON.serializeAsColor3("diffuse")
  40784. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40785. __decorate([
  40786. BABYLON.serializeAsColor3("specular")
  40787. ], StandardMaterial.prototype, "specularColor", void 0);
  40788. __decorate([
  40789. BABYLON.serializeAsColor3("emissive")
  40790. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40791. __decorate([
  40792. BABYLON.serialize()
  40793. ], StandardMaterial.prototype, "specularPower", void 0);
  40794. __decorate([
  40795. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40796. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40797. __decorate([
  40798. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40799. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40800. __decorate([
  40801. BABYLON.serialize("useEmissiveAsIllumination")
  40802. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40803. __decorate([
  40804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40805. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40806. __decorate([
  40807. BABYLON.serialize("linkEmissiveWithDiffuse")
  40808. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40809. __decorate([
  40810. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40811. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40812. __decorate([
  40813. BABYLON.serialize("useSpecularOverAlpha")
  40814. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40815. __decorate([
  40816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40817. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40818. __decorate([
  40819. BABYLON.serialize("useReflectionOverAlpha")
  40820. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40821. __decorate([
  40822. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40823. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40824. __decorate([
  40825. BABYLON.serialize("disableLighting")
  40826. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40827. __decorate([
  40828. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40829. ], StandardMaterial.prototype, "disableLighting", void 0);
  40830. __decorate([
  40831. BABYLON.serialize("useObjectSpaceNormalMap")
  40832. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40833. __decorate([
  40834. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40835. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40836. __decorate([
  40837. BABYLON.serialize("useParallax")
  40838. ], StandardMaterial.prototype, "_useParallax", void 0);
  40839. __decorate([
  40840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40841. ], StandardMaterial.prototype, "useParallax", void 0);
  40842. __decorate([
  40843. BABYLON.serialize("useParallaxOcclusion")
  40844. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40845. __decorate([
  40846. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40847. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40848. __decorate([
  40849. BABYLON.serialize()
  40850. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40851. __decorate([
  40852. BABYLON.serialize("roughness")
  40853. ], StandardMaterial.prototype, "_roughness", void 0);
  40854. __decorate([
  40855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40856. ], StandardMaterial.prototype, "roughness", void 0);
  40857. __decorate([
  40858. BABYLON.serialize()
  40859. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40860. __decorate([
  40861. BABYLON.serialize()
  40862. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40863. __decorate([
  40864. BABYLON.serialize("useLightmapAsShadowmap")
  40865. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40866. __decorate([
  40867. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40868. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40869. __decorate([
  40870. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40871. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40872. __decorate([
  40873. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40874. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40875. __decorate([
  40876. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40877. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40878. __decorate([
  40879. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40880. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40881. __decorate([
  40882. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40883. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40884. __decorate([
  40885. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40886. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40887. __decorate([
  40888. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40889. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40890. __decorate([
  40891. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40892. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40893. __decorate([
  40894. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40895. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40896. __decorate([
  40897. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40898. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40899. __decorate([
  40900. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40901. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40902. __decorate([
  40903. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40904. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40905. __decorate([
  40906. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40907. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40908. __decorate([
  40909. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40910. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40911. __decorate([
  40912. BABYLON.serialize("maxSimultaneousLights")
  40913. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40914. __decorate([
  40915. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40916. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40917. __decorate([
  40918. BABYLON.serialize("invertNormalMapX")
  40919. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40920. __decorate([
  40921. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40922. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40923. __decorate([
  40924. BABYLON.serialize("invertNormalMapY")
  40925. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40926. __decorate([
  40927. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40928. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40929. __decorate([
  40930. BABYLON.serialize("twoSidedLighting")
  40931. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40932. __decorate([
  40933. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40934. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40935. __decorate([
  40936. BABYLON.serialize()
  40937. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40938. return StandardMaterial;
  40939. }(BABYLON.PushMaterial));
  40940. BABYLON.StandardMaterial = StandardMaterial;
  40941. })(BABYLON || (BABYLON = {}));
  40942. //# sourceMappingURL=babylon.standardMaterial.js.map
  40943. "use strict";
  40944. var BABYLON;
  40945. (function (BABYLON) {
  40946. /**
  40947. * Manages the defines for the PBR Material.
  40948. */
  40949. var PBRMaterialDefines = /** @class */ (function (_super) {
  40950. __extends(PBRMaterialDefines, _super);
  40951. /**
  40952. * Initializes the PBR Material defines.
  40953. */
  40954. function PBRMaterialDefines() {
  40955. var _this = _super.call(this) || this;
  40956. _this.PBR = true;
  40957. _this.MAINUV1 = false;
  40958. _this.MAINUV2 = false;
  40959. _this.UV1 = false;
  40960. _this.UV2 = false;
  40961. _this.ALBEDO = false;
  40962. _this.ALBEDODIRECTUV = 0;
  40963. _this.VERTEXCOLOR = false;
  40964. _this.AMBIENT = false;
  40965. _this.AMBIENTDIRECTUV = 0;
  40966. _this.AMBIENTINGRAYSCALE = false;
  40967. _this.OPACITY = false;
  40968. _this.VERTEXALPHA = false;
  40969. _this.OPACITYDIRECTUV = 0;
  40970. _this.OPACITYRGB = false;
  40971. _this.ALPHATEST = false;
  40972. _this.DEPTHPREPASS = false;
  40973. _this.ALPHABLEND = false;
  40974. _this.ALPHAFROMALBEDO = false;
  40975. _this.ALPHATESTVALUE = "0.5";
  40976. _this.SPECULAROVERALPHA = false;
  40977. _this.RADIANCEOVERALPHA = false;
  40978. _this.ALPHAFRESNEL = false;
  40979. _this.LINEARALPHAFRESNEL = false;
  40980. _this.PREMULTIPLYALPHA = false;
  40981. _this.EMISSIVE = false;
  40982. _this.EMISSIVEDIRECTUV = 0;
  40983. _this.REFLECTIVITY = false;
  40984. _this.REFLECTIVITYDIRECTUV = 0;
  40985. _this.SPECULARTERM = false;
  40986. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40987. _this.MICROSURFACEAUTOMATIC = false;
  40988. _this.LODBASEDMICROSFURACE = false;
  40989. _this.MICROSURFACEMAP = false;
  40990. _this.MICROSURFACEMAPDIRECTUV = 0;
  40991. _this.METALLICWORKFLOW = false;
  40992. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40993. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40994. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40995. _this.AOSTOREINMETALMAPRED = false;
  40996. _this.ENVIRONMENTBRDF = false;
  40997. _this.NORMAL = false;
  40998. _this.TANGENT = false;
  40999. _this.BUMP = false;
  41000. _this.BUMPDIRECTUV = 0;
  41001. _this.OBJECTSPACE_NORMALMAP = false;
  41002. _this.PARALLAX = false;
  41003. _this.PARALLAXOCCLUSION = false;
  41004. _this.NORMALXYSCALE = true;
  41005. _this.LIGHTMAP = false;
  41006. _this.LIGHTMAPDIRECTUV = 0;
  41007. _this.USELIGHTMAPASSHADOWMAP = false;
  41008. _this.GAMMALIGHTMAP = false;
  41009. _this.REFLECTION = false;
  41010. _this.REFLECTIONMAP_3D = false;
  41011. _this.REFLECTIONMAP_SPHERICAL = false;
  41012. _this.REFLECTIONMAP_PLANAR = false;
  41013. _this.REFLECTIONMAP_CUBIC = false;
  41014. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41015. _this.REFLECTIONMAP_PROJECTION = false;
  41016. _this.REFLECTIONMAP_SKYBOX = false;
  41017. _this.REFLECTIONMAP_EXPLICIT = false;
  41018. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41019. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41020. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41021. _this.INVERTCUBICMAP = false;
  41022. _this.USESPHERICALFROMREFLECTIONMAP = false;
  41023. _this.USESPHERICALINVERTEX = false;
  41024. _this.REFLECTIONMAP_OPPOSITEZ = false;
  41025. _this.LODINREFLECTIONALPHA = false;
  41026. _this.GAMMAREFLECTION = false;
  41027. _this.RADIANCEOCCLUSION = false;
  41028. _this.HORIZONOCCLUSION = false;
  41029. _this.REFRACTION = false;
  41030. _this.REFRACTIONMAP_3D = false;
  41031. _this.REFRACTIONMAP_OPPOSITEZ = false;
  41032. _this.LODINREFRACTIONALPHA = false;
  41033. _this.GAMMAREFRACTION = false;
  41034. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  41035. _this.INSTANCES = false;
  41036. _this.NUM_BONE_INFLUENCERS = 0;
  41037. _this.BonesPerMesh = 0;
  41038. _this.NONUNIFORMSCALING = false;
  41039. _this.MORPHTARGETS = false;
  41040. _this.MORPHTARGETS_NORMAL = false;
  41041. _this.MORPHTARGETS_TANGENT = false;
  41042. _this.NUM_MORPH_INFLUENCERS = 0;
  41043. _this.IMAGEPROCESSING = false;
  41044. _this.VIGNETTE = false;
  41045. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41046. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41047. _this.TONEMAPPING = false;
  41048. _this.CONTRAST = false;
  41049. _this.COLORCURVES = false;
  41050. _this.COLORGRADING = false;
  41051. _this.COLORGRADING3D = false;
  41052. _this.SAMPLER3DGREENDEPTH = false;
  41053. _this.SAMPLER3DBGRMAP = false;
  41054. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41055. _this.EXPOSURE = false;
  41056. _this.GRAIN = false;
  41057. _this.USEPHYSICALLIGHTFALLOFF = false;
  41058. _this.TWOSIDEDLIGHTING = false;
  41059. _this.SHADOWFLOAT = false;
  41060. _this.CLIPPLANE = false;
  41061. _this.POINTSIZE = false;
  41062. _this.FOG = false;
  41063. _this.LOGARITHMICDEPTH = false;
  41064. _this.FORCENORMALFORWARD = false;
  41065. _this.UNLIT = false;
  41066. _this.rebuild();
  41067. return _this;
  41068. }
  41069. /**
  41070. * Resets the PBR Material defines.
  41071. */
  41072. PBRMaterialDefines.prototype.reset = function () {
  41073. _super.prototype.reset.call(this);
  41074. this.ALPHATESTVALUE = "0.5";
  41075. this.PBR = true;
  41076. };
  41077. return PBRMaterialDefines;
  41078. }(BABYLON.MaterialDefines));
  41079. /**
  41080. * The Physically based material base class of BJS.
  41081. *
  41082. * This offers the main features of a standard PBR material.
  41083. * For more information, please refer to the documentation :
  41084. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41085. */
  41086. var PBRBaseMaterial = /** @class */ (function (_super) {
  41087. __extends(PBRBaseMaterial, _super);
  41088. /**
  41089. * Instantiates a new PBRMaterial instance.
  41090. *
  41091. * @param name The material name
  41092. * @param scene The scene the material will be use in.
  41093. */
  41094. function PBRBaseMaterial(name, scene) {
  41095. var _this = _super.call(this, name, scene) || this;
  41096. /**
  41097. * Intensity of the direct lights e.g. the four lights available in your scene.
  41098. * This impacts both the direct diffuse and specular highlights.
  41099. */
  41100. _this._directIntensity = 1.0;
  41101. /**
  41102. * Intensity of the emissive part of the material.
  41103. * This helps controlling the emissive effect without modifying the emissive color.
  41104. */
  41105. _this._emissiveIntensity = 1.0;
  41106. /**
  41107. * Intensity of the environment e.g. how much the environment will light the object
  41108. * either through harmonics for rough material or through the refelction for shiny ones.
  41109. */
  41110. _this._environmentIntensity = 1.0;
  41111. /**
  41112. * This is a special control allowing the reduction of the specular highlights coming from the
  41113. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41114. */
  41115. _this._specularIntensity = 1.0;
  41116. /**
  41117. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  41118. */
  41119. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  41120. /**
  41121. * Debug Control allowing disabling the bump map on this material.
  41122. */
  41123. _this._disableBumpMap = false;
  41124. /**
  41125. * AKA Occlusion Texture Intensity in other nomenclature.
  41126. */
  41127. _this._ambientTextureStrength = 1.0;
  41128. /**
  41129. * The color of a material in ambient lighting.
  41130. */
  41131. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  41132. /**
  41133. * AKA Diffuse Color in other nomenclature.
  41134. */
  41135. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  41136. /**
  41137. * AKA Specular Color in other nomenclature.
  41138. */
  41139. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41140. /**
  41141. * The color applied when light is reflected from a material.
  41142. */
  41143. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  41144. /**
  41145. * The color applied when light is emitted from a material.
  41146. */
  41147. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  41148. /**
  41149. * AKA Glossiness in other nomenclature.
  41150. */
  41151. _this._microSurface = 0.9;
  41152. /**
  41153. * source material index of refraction (IOR)' / 'destination material IOR.
  41154. */
  41155. _this._indexOfRefraction = 0.66;
  41156. /**
  41157. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41158. */
  41159. _this._invertRefractionY = false;
  41160. /**
  41161. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41162. * Materials half opaque for instance using refraction could benefit from this control.
  41163. */
  41164. _this._linkRefractionWithTransparency = false;
  41165. /**
  41166. * Specifies that the material will use the light map as a show map.
  41167. */
  41168. _this._useLightmapAsShadowmap = false;
  41169. /**
  41170. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41171. * makes the reflect vector face the model (under horizon).
  41172. */
  41173. _this._useHorizonOcclusion = true;
  41174. /**
  41175. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41176. * too much the area relying on ambient texture to define their ambient occlusion.
  41177. */
  41178. _this._useRadianceOcclusion = true;
  41179. /**
  41180. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41181. */
  41182. _this._useAlphaFromAlbedoTexture = false;
  41183. /**
  41184. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41185. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41186. */
  41187. _this._useSpecularOverAlpha = true;
  41188. /**
  41189. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41190. */
  41191. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  41192. /**
  41193. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41194. */
  41195. _this._useRoughnessFromMetallicTextureAlpha = true;
  41196. /**
  41197. * Specifies if the metallic texture contains the roughness information in its green channel.
  41198. */
  41199. _this._useRoughnessFromMetallicTextureGreen = false;
  41200. /**
  41201. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41202. */
  41203. _this._useMetallnessFromMetallicTextureBlue = false;
  41204. /**
  41205. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41206. */
  41207. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  41208. /**
  41209. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41210. */
  41211. _this._useAmbientInGrayScale = false;
  41212. /**
  41213. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41214. * The material will try to infer what glossiness each pixel should be.
  41215. */
  41216. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  41217. /**
  41218. * BJS is using an harcoded light falloff based on a manually sets up range.
  41219. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41220. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41221. */
  41222. _this._usePhysicalLightFalloff = true;
  41223. /**
  41224. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41225. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41226. */
  41227. _this._useRadianceOverAlpha = true;
  41228. /**
  41229. * Allows using an object space normal map (instead of tangent space).
  41230. */
  41231. _this._useObjectSpaceNormalMap = false;
  41232. /**
  41233. * Allows using the bump map in parallax mode.
  41234. */
  41235. _this._useParallax = false;
  41236. /**
  41237. * Allows using the bump map in parallax occlusion mode.
  41238. */
  41239. _this._useParallaxOcclusion = false;
  41240. /**
  41241. * Controls the scale bias of the parallax mode.
  41242. */
  41243. _this._parallaxScaleBias = 0.05;
  41244. /**
  41245. * If sets to true, disables all the lights affecting the material.
  41246. */
  41247. _this._disableLighting = false;
  41248. /**
  41249. * Number of Simultaneous lights allowed on the material.
  41250. */
  41251. _this._maxSimultaneousLights = 4;
  41252. /**
  41253. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  41254. */
  41255. _this._invertNormalMapX = false;
  41256. /**
  41257. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  41258. */
  41259. _this._invertNormalMapY = false;
  41260. /**
  41261. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41262. */
  41263. _this._twoSidedLighting = false;
  41264. /**
  41265. * Defines the alpha limits in alpha test mode.
  41266. */
  41267. _this._alphaCutOff = 0.4;
  41268. /**
  41269. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41270. */
  41271. _this._forceAlphaTest = false;
  41272. /**
  41273. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41274. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41275. */
  41276. _this._useAlphaFresnel = false;
  41277. /**
  41278. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41279. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41280. */
  41281. _this._useLinearAlphaFresnel = false;
  41282. /**
  41283. * The transparency mode of the material.
  41284. */
  41285. _this._transparencyMode = null;
  41286. /**
  41287. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  41288. * from cos thetav and roughness:
  41289. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  41290. */
  41291. _this._environmentBRDFTexture = null;
  41292. /**
  41293. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41294. */
  41295. _this._forceIrradianceInFragment = false;
  41296. /**
  41297. * Force normal to face away from face.
  41298. */
  41299. _this._forceNormalForward = false;
  41300. /**
  41301. * Stores the available render targets.
  41302. */
  41303. _this._renderTargets = new BABYLON.SmartArray(16);
  41304. /**
  41305. * Sets the global ambient color for the material used in lighting calculations.
  41306. */
  41307. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41308. /**
  41309. * If set to true, no lighting calculations will be applied.
  41310. */
  41311. _this._unlit = false;
  41312. // Setup the default processing configuration to the scene.
  41313. _this._attachImageProcessingConfiguration(null);
  41314. _this.getRenderTargetTextures = function () {
  41315. _this._renderTargets.reset();
  41316. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41317. _this._renderTargets.push(_this._reflectionTexture);
  41318. }
  41319. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41320. _this._renderTargets.push(_this._refractionTexture);
  41321. }
  41322. return _this._renderTargets;
  41323. };
  41324. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41325. return _this;
  41326. }
  41327. /**
  41328. * Attaches a new image processing configuration to the PBR Material.
  41329. * @param configuration
  41330. */
  41331. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41332. var _this = this;
  41333. if (configuration === this._imageProcessingConfiguration) {
  41334. return;
  41335. }
  41336. // Detaches observer.
  41337. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41338. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41339. }
  41340. // Pick the scene configuration if needed.
  41341. if (!configuration) {
  41342. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41343. }
  41344. else {
  41345. this._imageProcessingConfiguration = configuration;
  41346. }
  41347. // Attaches observer.
  41348. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41349. _this._markAllSubMeshesAsImageProcessingDirty();
  41350. });
  41351. };
  41352. /**
  41353. * Gets the name of the material class.
  41354. */
  41355. PBRBaseMaterial.prototype.getClassName = function () {
  41356. return "PBRBaseMaterial";
  41357. };
  41358. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  41359. /**
  41360. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41361. */
  41362. get: function () {
  41363. return this._useLogarithmicDepth;
  41364. },
  41365. /**
  41366. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41367. */
  41368. set: function (value) {
  41369. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41370. },
  41371. enumerable: true,
  41372. configurable: true
  41373. });
  41374. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  41375. /**
  41376. * Gets the current transparency mode.
  41377. */
  41378. get: function () {
  41379. return this._transparencyMode;
  41380. },
  41381. /**
  41382. * Sets the transparency mode of the material.
  41383. */
  41384. set: function (value) {
  41385. if (this._transparencyMode === value) {
  41386. return;
  41387. }
  41388. this._transparencyMode = value;
  41389. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  41390. this._markAllSubMeshesAsTexturesAndMiscDirty();
  41391. },
  41392. enumerable: true,
  41393. configurable: true
  41394. });
  41395. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  41396. /**
  41397. * Returns true if alpha blending should be disabled.
  41398. */
  41399. get: function () {
  41400. return (this._linkRefractionWithTransparency ||
  41401. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  41402. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41403. },
  41404. enumerable: true,
  41405. configurable: true
  41406. });
  41407. /**
  41408. * Specifies whether or not this material should be rendered in alpha blend mode.
  41409. */
  41410. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  41411. if (this._disableAlphaBlending) {
  41412. return false;
  41413. }
  41414. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  41415. };
  41416. /**
  41417. * Specifies if the mesh will require alpha blending.
  41418. * @param mesh - BJS mesh.
  41419. */
  41420. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  41421. if (this._disableAlphaBlending) {
  41422. return false;
  41423. }
  41424. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  41425. };
  41426. /**
  41427. * Specifies whether or not this material should be rendered in alpha test mode.
  41428. */
  41429. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  41430. if (this._forceAlphaTest) {
  41431. return true;
  41432. }
  41433. if (this._linkRefractionWithTransparency) {
  41434. return false;
  41435. }
  41436. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41437. };
  41438. /**
  41439. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  41440. */
  41441. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  41442. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  41443. };
  41444. /**
  41445. * Gets the texture used for the alpha test.
  41446. */
  41447. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  41448. return this._albedoTexture;
  41449. };
  41450. /**
  41451. * Specifies that the submesh is ready to be used.
  41452. * @param mesh - BJS mesh.
  41453. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  41454. * @param useInstances - Specifies that instances should be used.
  41455. * @returns - boolean indicating that the submesh is ready or not.
  41456. */
  41457. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41458. if (subMesh.effect && this.isFrozen) {
  41459. if (this._wasPreviouslyReady) {
  41460. return true;
  41461. }
  41462. }
  41463. if (!subMesh._materialDefines) {
  41464. subMesh._materialDefines = new PBRMaterialDefines();
  41465. }
  41466. var defines = subMesh._materialDefines;
  41467. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41468. if (defines._renderId === this.getScene().getRenderId()) {
  41469. return true;
  41470. }
  41471. }
  41472. var scene = this.getScene();
  41473. var engine = scene.getEngine();
  41474. if (defines._areTexturesDirty) {
  41475. if (scene.texturesEnabled) {
  41476. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41477. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  41478. return false;
  41479. }
  41480. }
  41481. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41482. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41483. return false;
  41484. }
  41485. }
  41486. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41487. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41488. return false;
  41489. }
  41490. }
  41491. var reflectionTexture = this._getReflectionTexture();
  41492. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41493. if (!reflectionTexture.isReadyOrNotBlocking()) {
  41494. return false;
  41495. }
  41496. }
  41497. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41498. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41499. return false;
  41500. }
  41501. }
  41502. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41503. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41504. return false;
  41505. }
  41506. }
  41507. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41508. if (this._metallicTexture) {
  41509. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  41510. return false;
  41511. }
  41512. }
  41513. else if (this._reflectivityTexture) {
  41514. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  41515. return false;
  41516. }
  41517. }
  41518. if (this._microSurfaceTexture) {
  41519. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  41520. return false;
  41521. }
  41522. }
  41523. }
  41524. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41525. // Bump texture cannot be not blocking.
  41526. if (!this._bumpTexture.isReady()) {
  41527. return false;
  41528. }
  41529. }
  41530. var refractionTexture = this._getRefractionTexture();
  41531. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41532. if (!refractionTexture.isReadyOrNotBlocking()) {
  41533. return false;
  41534. }
  41535. }
  41536. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41537. // This is blocking.
  41538. if (!this._environmentBRDFTexture.isReady()) {
  41539. return false;
  41540. }
  41541. }
  41542. }
  41543. }
  41544. if (defines._areImageProcessingDirty) {
  41545. if (!this._imageProcessingConfiguration.isReady()) {
  41546. return false;
  41547. }
  41548. }
  41549. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41550. mesh.createNormals(true);
  41551. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  41552. }
  41553. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  41554. if (effect) {
  41555. scene.resetCachedMaterial();
  41556. subMesh.setEffect(effect, defines);
  41557. this.buildUniformLayout();
  41558. }
  41559. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41560. return false;
  41561. }
  41562. defines._renderId = scene.getRenderId();
  41563. this._wasPreviouslyReady = true;
  41564. return true;
  41565. };
  41566. /**
  41567. * Specifies if the material uses metallic roughness workflow.
  41568. * @returns boolean specifiying if the material uses metallic roughness workflow.
  41569. */
  41570. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  41571. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  41572. return true;
  41573. }
  41574. return false;
  41575. };
  41576. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  41577. if (onCompiled === void 0) { onCompiled = null; }
  41578. if (onError === void 0) { onError = null; }
  41579. if (useInstances === void 0) { useInstances = null; }
  41580. if (useClipPlane === void 0) { useClipPlane = null; }
  41581. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  41582. if (!defines.isDirty) {
  41583. return null;
  41584. }
  41585. defines.markAsProcessed();
  41586. var scene = this.getScene();
  41587. var engine = scene.getEngine();
  41588. // Fallbacks
  41589. var fallbacks = new BABYLON.EffectFallbacks();
  41590. var fallbackRank = 0;
  41591. if (defines.USESPHERICALINVERTEX) {
  41592. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  41593. }
  41594. if (defines.FOG) {
  41595. fallbacks.addFallback(fallbackRank, "FOG");
  41596. }
  41597. if (defines.POINTSIZE) {
  41598. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  41599. }
  41600. if (defines.LOGARITHMICDEPTH) {
  41601. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  41602. }
  41603. if (defines.PARALLAX) {
  41604. fallbacks.addFallback(fallbackRank, "PARALLAX");
  41605. }
  41606. if (defines.PARALLAXOCCLUSION) {
  41607. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  41608. }
  41609. if (defines.ENVIRONMENTBRDF) {
  41610. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  41611. }
  41612. if (defines.TANGENT) {
  41613. fallbacks.addFallback(fallbackRank++, "TANGENT");
  41614. }
  41615. if (defines.BUMP) {
  41616. fallbacks.addFallback(fallbackRank++, "BUMP");
  41617. }
  41618. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  41619. if (defines.SPECULARTERM) {
  41620. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  41621. }
  41622. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  41623. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  41624. }
  41625. if (defines.LIGHTMAP) {
  41626. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  41627. }
  41628. if (defines.NORMAL) {
  41629. fallbacks.addFallback(fallbackRank++, "NORMAL");
  41630. }
  41631. if (defines.AMBIENT) {
  41632. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  41633. }
  41634. if (defines.EMISSIVE) {
  41635. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  41636. }
  41637. if (defines.VERTEXCOLOR) {
  41638. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  41639. }
  41640. if (defines.NUM_BONE_INFLUENCERS > 0) {
  41641. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  41642. }
  41643. if (defines.MORPHTARGETS) {
  41644. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  41645. }
  41646. //Attributes
  41647. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41648. if (defines.NORMAL) {
  41649. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41650. }
  41651. if (defines.TANGENT) {
  41652. attribs.push(BABYLON.VertexBuffer.TangentKind);
  41653. }
  41654. if (defines.UV1) {
  41655. attribs.push(BABYLON.VertexBuffer.UVKind);
  41656. }
  41657. if (defines.UV2) {
  41658. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41659. }
  41660. if (defines.VERTEXCOLOR) {
  41661. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41662. }
  41663. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41664. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41665. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41666. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  41667. "vFogInfos", "vFogColor", "pointSize",
  41668. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  41669. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41670. "mBones",
  41671. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  41672. "vLightingIntensity",
  41673. "logarithmicDepthConstant",
  41674. "vSphericalX", "vSphericalY", "vSphericalZ",
  41675. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  41676. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  41677. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  41678. "vTangentSpaceParams"
  41679. ];
  41680. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  41681. "bumpSampler", "lightmapSampler", "opacitySampler",
  41682. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  41683. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  41684. "microSurfaceSampler", "environmentBrdfSampler"];
  41685. var uniformBuffers = ["Material", "Scene"];
  41686. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41687. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41688. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41689. uniformsNames: uniforms,
  41690. uniformBuffersNames: uniformBuffers,
  41691. samplers: samplers,
  41692. defines: defines,
  41693. maxSimultaneousLights: this._maxSimultaneousLights
  41694. });
  41695. var join = defines.toString();
  41696. return engine.createEffect("pbr", {
  41697. attributes: attribs,
  41698. uniformsNames: uniforms,
  41699. uniformBuffersNames: uniformBuffers,
  41700. samplers: samplers,
  41701. defines: join,
  41702. fallbacks: fallbacks,
  41703. onCompiled: onCompiled,
  41704. onError: onError,
  41705. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41706. }, engine);
  41707. };
  41708. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41709. if (useInstances === void 0) { useInstances = null; }
  41710. if (useClipPlane === void 0) { useClipPlane = null; }
  41711. var scene = this.getScene();
  41712. var engine = scene.getEngine();
  41713. // Lights
  41714. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41715. defines._needNormals = true;
  41716. // Textures
  41717. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41718. if (defines._areTexturesDirty) {
  41719. defines._needUVs = false;
  41720. if (scene.texturesEnabled) {
  41721. if (scene.getEngine().getCaps().textureLOD) {
  41722. defines.LODBASEDMICROSFURACE = true;
  41723. }
  41724. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41725. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41726. }
  41727. else {
  41728. defines.ALBEDO = false;
  41729. }
  41730. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41731. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41732. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41733. }
  41734. else {
  41735. defines.AMBIENT = false;
  41736. }
  41737. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41738. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41739. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41740. }
  41741. else {
  41742. defines.OPACITY = false;
  41743. }
  41744. var reflectionTexture = this._getReflectionTexture();
  41745. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41746. defines.REFLECTION = true;
  41747. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41748. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41749. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41750. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41751. defines.INVERTCUBICMAP = true;
  41752. }
  41753. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41754. switch (reflectionTexture.coordinatesMode) {
  41755. case BABYLON.Texture.CUBIC_MODE:
  41756. case BABYLON.Texture.INVCUBIC_MODE:
  41757. defines.REFLECTIONMAP_CUBIC = true;
  41758. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41759. break;
  41760. case BABYLON.Texture.EXPLICIT_MODE:
  41761. defines.REFLECTIONMAP_EXPLICIT = true;
  41762. break;
  41763. case BABYLON.Texture.PLANAR_MODE:
  41764. defines.REFLECTIONMAP_PLANAR = true;
  41765. break;
  41766. case BABYLON.Texture.PROJECTION_MODE:
  41767. defines.REFLECTIONMAP_PROJECTION = true;
  41768. break;
  41769. case BABYLON.Texture.SKYBOX_MODE:
  41770. defines.REFLECTIONMAP_SKYBOX = true;
  41771. break;
  41772. case BABYLON.Texture.SPHERICAL_MODE:
  41773. defines.REFLECTIONMAP_SPHERICAL = true;
  41774. break;
  41775. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41776. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41777. break;
  41778. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41779. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41780. break;
  41781. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41782. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41783. break;
  41784. }
  41785. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41786. if (reflectionTexture.sphericalPolynomial) {
  41787. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41788. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41789. defines.USESPHERICALINVERTEX = false;
  41790. }
  41791. else {
  41792. defines.USESPHERICALINVERTEX = true;
  41793. }
  41794. }
  41795. }
  41796. }
  41797. else {
  41798. defines.REFLECTION = false;
  41799. defines.REFLECTIONMAP_3D = false;
  41800. defines.REFLECTIONMAP_SPHERICAL = false;
  41801. defines.REFLECTIONMAP_PLANAR = false;
  41802. defines.REFLECTIONMAP_CUBIC = false;
  41803. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41804. defines.REFLECTIONMAP_PROJECTION = false;
  41805. defines.REFLECTIONMAP_SKYBOX = false;
  41806. defines.REFLECTIONMAP_EXPLICIT = false;
  41807. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41808. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41809. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41810. defines.INVERTCUBICMAP = false;
  41811. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41812. defines.USESPHERICALINVERTEX = false;
  41813. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41814. defines.LODINREFLECTIONALPHA = false;
  41815. defines.GAMMAREFLECTION = false;
  41816. }
  41817. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41818. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41819. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41820. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  41821. }
  41822. else {
  41823. defines.LIGHTMAP = false;
  41824. }
  41825. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41826. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41827. }
  41828. else {
  41829. defines.EMISSIVE = false;
  41830. }
  41831. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41832. if (this._metallicTexture) {
  41833. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41834. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41835. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41836. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41837. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41838. }
  41839. else if (this._reflectivityTexture) {
  41840. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41841. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41842. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41843. }
  41844. else {
  41845. defines.REFLECTIVITY = false;
  41846. }
  41847. if (this._microSurfaceTexture) {
  41848. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41849. }
  41850. else {
  41851. defines.MICROSURFACEMAP = false;
  41852. }
  41853. }
  41854. else {
  41855. defines.REFLECTIVITY = false;
  41856. defines.MICROSURFACEMAP = false;
  41857. }
  41858. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41859. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41860. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41861. defines.PARALLAX = true;
  41862. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41863. }
  41864. else {
  41865. defines.PARALLAX = false;
  41866. }
  41867. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41868. }
  41869. else {
  41870. defines.BUMP = false;
  41871. }
  41872. var refractionTexture = this._getRefractionTexture();
  41873. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41874. defines.REFRACTION = true;
  41875. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41876. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41877. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41878. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41879. if (this._linkRefractionWithTransparency) {
  41880. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41881. }
  41882. }
  41883. else {
  41884. defines.REFRACTION = false;
  41885. }
  41886. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41887. defines.ENVIRONMENTBRDF = true;
  41888. }
  41889. else {
  41890. defines.ENVIRONMENTBRDF = false;
  41891. }
  41892. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41893. defines.ALPHAFROMALBEDO = true;
  41894. }
  41895. else {
  41896. defines.ALPHAFROMALBEDO = false;
  41897. }
  41898. }
  41899. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41900. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41901. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41902. if (!this.backFaceCulling && this._twoSidedLighting) {
  41903. defines.TWOSIDEDLIGHTING = true;
  41904. }
  41905. else {
  41906. defines.TWOSIDEDLIGHTING = false;
  41907. }
  41908. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  41909. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41910. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41911. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41912. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41913. }
  41914. if (defines._areImageProcessingDirty) {
  41915. this._imageProcessingConfiguration.prepareDefines(defines);
  41916. }
  41917. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41918. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41919. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41920. // Misc.
  41921. if (defines._areMiscDirty) {
  41922. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41923. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41924. }
  41925. // Values that need to be evaluated on every frame
  41926. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41927. // Attribs
  41928. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41929. };
  41930. /**
  41931. * Force shader compilation
  41932. */
  41933. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41934. var _this = this;
  41935. var localOptions = __assign({ clipPlane: false }, options);
  41936. var defines = new PBRMaterialDefines();
  41937. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41938. if (effect.isReady()) {
  41939. if (onCompiled) {
  41940. onCompiled(this);
  41941. }
  41942. }
  41943. else {
  41944. effect.onCompileObservable.add(function () {
  41945. if (onCompiled) {
  41946. onCompiled(_this);
  41947. }
  41948. });
  41949. }
  41950. };
  41951. /**
  41952. * Initializes the uniform buffer layout for the shader.
  41953. */
  41954. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41955. // Order is important !
  41956. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41957. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41958. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41959. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41960. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41961. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41962. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41963. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41964. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41965. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41966. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41967. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41968. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41969. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41970. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41971. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41972. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41973. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41974. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41975. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41976. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41977. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41978. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41979. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41980. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41981. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41982. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41983. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41984. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41985. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41986. this._uniformBuffer.addUniform("pointSize", 1);
  41987. this._uniformBuffer.create();
  41988. };
  41989. /**
  41990. * Unbinds the textures.
  41991. */
  41992. PBRBaseMaterial.prototype.unbind = function () {
  41993. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41994. this._uniformBuffer.setTexture("reflectionSampler", null);
  41995. }
  41996. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41997. this._uniformBuffer.setTexture("refractionSampler", null);
  41998. }
  41999. _super.prototype.unbind.call(this);
  42000. };
  42001. /**
  42002. * Binds the submesh data.
  42003. * @param world - The world matrix.
  42004. * @param mesh - The BJS mesh.
  42005. * @param subMesh - A submesh of the BJS mesh.
  42006. */
  42007. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42008. var scene = this.getScene();
  42009. var defines = subMesh._materialDefines;
  42010. if (!defines) {
  42011. return;
  42012. }
  42013. var effect = subMesh.effect;
  42014. if (!effect) {
  42015. return;
  42016. }
  42017. this._activeEffect = effect;
  42018. // Matrices
  42019. this.bindOnlyWorldMatrix(world);
  42020. // Normal Matrix
  42021. if (defines.OBJECTSPACE_NORMALMAP) {
  42022. world.toNormalMatrix(this._normalMatrix);
  42023. this.bindOnlyNormalMatrix(this._normalMatrix);
  42024. }
  42025. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42026. // Bones
  42027. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  42028. var reflectionTexture = null;
  42029. if (mustRebind) {
  42030. this._uniformBuffer.bindToEffect(effect, "Material");
  42031. this.bindViewProjection(effect);
  42032. reflectionTexture = this._getReflectionTexture();
  42033. var refractionTexture = this._getRefractionTexture();
  42034. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42035. // Texture uniforms
  42036. if (scene.texturesEnabled) {
  42037. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  42038. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  42039. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  42040. }
  42041. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  42042. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  42043. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42044. }
  42045. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  42046. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42047. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42048. }
  42049. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42050. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  42051. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  42052. if (reflectionTexture.boundingBoxSize) {
  42053. var cubeTexture = reflectionTexture;
  42054. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42055. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42056. }
  42057. var polynomials = reflectionTexture.sphericalPolynomial;
  42058. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  42059. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  42060. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  42061. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  42062. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  42063. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  42064. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  42065. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  42066. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  42067. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  42068. }
  42069. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  42070. }
  42071. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42072. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42073. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42074. }
  42075. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42076. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42077. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42078. }
  42079. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42080. if (this._metallicTexture) {
  42081. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  42082. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  42083. }
  42084. else if (this._reflectivityTexture) {
  42085. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  42086. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  42087. }
  42088. if (this._microSurfaceTexture) {
  42089. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  42090. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  42091. }
  42092. }
  42093. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42094. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  42095. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42096. if (scene._mirroredCameraPosition) {
  42097. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42098. }
  42099. else {
  42100. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42101. }
  42102. }
  42103. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42104. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  42105. var depth = 1.0;
  42106. if (!refractionTexture.isCube) {
  42107. if (refractionTexture.depth) {
  42108. depth = refractionTexture.depth;
  42109. }
  42110. }
  42111. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  42112. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  42113. }
  42114. }
  42115. // Point size
  42116. if (this.pointsCloud) {
  42117. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42118. }
  42119. // Colors
  42120. if (defines.METALLICWORKFLOW) {
  42121. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  42122. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  42123. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  42124. }
  42125. else {
  42126. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  42127. }
  42128. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  42129. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  42130. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  42131. // Misc
  42132. this._lightingInfos.x = this._directIntensity;
  42133. this._lightingInfos.y = this._emissiveIntensity;
  42134. this._lightingInfos.z = this._environmentIntensity;
  42135. this._lightingInfos.w = this._specularIntensity;
  42136. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  42137. }
  42138. // Textures
  42139. if (scene.texturesEnabled) {
  42140. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  42141. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  42142. }
  42143. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  42144. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  42145. }
  42146. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  42147. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  42148. }
  42149. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42150. if (defines.LODBASEDMICROSFURACE) {
  42151. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  42152. }
  42153. else {
  42154. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  42155. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  42156. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  42157. }
  42158. }
  42159. if (defines.ENVIRONMENTBRDF) {
  42160. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  42161. }
  42162. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42163. if (defines.LODBASEDMICROSFURACE) {
  42164. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  42165. }
  42166. else {
  42167. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  42168. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  42169. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  42170. }
  42171. }
  42172. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42173. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  42174. }
  42175. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42176. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  42177. }
  42178. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42179. if (this._metallicTexture) {
  42180. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  42181. }
  42182. else if (this._reflectivityTexture) {
  42183. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  42184. }
  42185. if (this._microSurfaceTexture) {
  42186. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  42187. }
  42188. }
  42189. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42190. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  42191. }
  42192. }
  42193. // Clip plane
  42194. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  42195. // Colors
  42196. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  42197. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42198. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  42199. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  42200. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42201. }
  42202. if (mustRebind || !this.isFrozen) {
  42203. // Lights
  42204. if (scene.lightsEnabled && !this._disableLighting) {
  42205. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  42206. }
  42207. // View
  42208. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  42209. this.bindView(effect);
  42210. }
  42211. // Fog
  42212. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  42213. // Morph targets
  42214. if (defines.NUM_MORPH_INFLUENCERS) {
  42215. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  42216. }
  42217. // image processing
  42218. this._imageProcessingConfiguration.bind(this._activeEffect);
  42219. // Log. depth
  42220. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  42221. }
  42222. this._uniformBuffer.update();
  42223. this._afterBind(mesh);
  42224. };
  42225. /**
  42226. * Returns the animatable textures.
  42227. * @returns - Array of animatable textures.
  42228. */
  42229. PBRBaseMaterial.prototype.getAnimatables = function () {
  42230. var results = [];
  42231. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  42232. results.push(this._albedoTexture);
  42233. }
  42234. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42235. results.push(this._ambientTexture);
  42236. }
  42237. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42238. results.push(this._opacityTexture);
  42239. }
  42240. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42241. results.push(this._reflectionTexture);
  42242. }
  42243. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42244. results.push(this._emissiveTexture);
  42245. }
  42246. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  42247. results.push(this._metallicTexture);
  42248. }
  42249. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  42250. results.push(this._reflectivityTexture);
  42251. }
  42252. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42253. results.push(this._bumpTexture);
  42254. }
  42255. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42256. results.push(this._lightmapTexture);
  42257. }
  42258. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42259. results.push(this._refractionTexture);
  42260. }
  42261. return results;
  42262. };
  42263. /**
  42264. * Returns the texture used for reflections.
  42265. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  42266. */
  42267. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  42268. if (this._reflectionTexture) {
  42269. return this._reflectionTexture;
  42270. }
  42271. return this.getScene().environmentTexture;
  42272. };
  42273. /**
  42274. * Returns the texture used for refraction or null if none is used.
  42275. * @returns - Refection texture if present. If no refraction texture and refraction
  42276. * is linked with transparency, returns environment texture. Otherwise, returns null.
  42277. */
  42278. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  42279. if (this._refractionTexture) {
  42280. return this._refractionTexture;
  42281. }
  42282. if (this._linkRefractionWithTransparency) {
  42283. return this.getScene().environmentTexture;
  42284. }
  42285. return null;
  42286. };
  42287. /**
  42288. * Disposes the resources of the material.
  42289. * @param forceDisposeEffect - Forces the disposal of effects.
  42290. * @param forceDisposeTextures - Forces the disposal of all textures.
  42291. */
  42292. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42293. if (forceDisposeTextures) {
  42294. if (this._albedoTexture) {
  42295. this._albedoTexture.dispose();
  42296. }
  42297. if (this._ambientTexture) {
  42298. this._ambientTexture.dispose();
  42299. }
  42300. if (this._opacityTexture) {
  42301. this._opacityTexture.dispose();
  42302. }
  42303. if (this._reflectionTexture) {
  42304. this._reflectionTexture.dispose();
  42305. }
  42306. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  42307. this._environmentBRDFTexture.dispose();
  42308. }
  42309. if (this._emissiveTexture) {
  42310. this._emissiveTexture.dispose();
  42311. }
  42312. if (this._metallicTexture) {
  42313. this._metallicTexture.dispose();
  42314. }
  42315. if (this._reflectivityTexture) {
  42316. this._reflectivityTexture.dispose();
  42317. }
  42318. if (this._bumpTexture) {
  42319. this._bumpTexture.dispose();
  42320. }
  42321. if (this._lightmapTexture) {
  42322. this._lightmapTexture.dispose();
  42323. }
  42324. if (this._refractionTexture) {
  42325. this._refractionTexture.dispose();
  42326. }
  42327. }
  42328. this._renderTargets.dispose();
  42329. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42330. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42331. }
  42332. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42333. };
  42334. /**
  42335. * Stores the reflectivity values based on metallic roughness workflow.
  42336. */
  42337. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  42338. __decorate([
  42339. BABYLON.serializeAsImageProcessingConfiguration()
  42340. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  42341. __decorate([
  42342. BABYLON.serialize()
  42343. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  42344. __decorate([
  42345. BABYLON.serialize()
  42346. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  42347. return PBRBaseMaterial;
  42348. }(BABYLON.PushMaterial));
  42349. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  42350. })(BABYLON || (BABYLON = {}));
  42351. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  42352. "use strict";
  42353. var BABYLON;
  42354. (function (BABYLON) {
  42355. /**
  42356. * The Physically based simple base material of BJS.
  42357. *
  42358. * This enables better naming and convention enforcements on top of the pbrMaterial.
  42359. * It is used as the base class for both the specGloss and metalRough conventions.
  42360. */
  42361. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  42362. __extends(PBRBaseSimpleMaterial, _super);
  42363. /**
  42364. * Instantiates a new PBRMaterial instance.
  42365. *
  42366. * @param name The material name
  42367. * @param scene The scene the material will be use in.
  42368. */
  42369. function PBRBaseSimpleMaterial(name, scene) {
  42370. var _this = _super.call(this, name, scene) || this;
  42371. /**
  42372. * Number of Simultaneous lights allowed on the material.
  42373. */
  42374. _this.maxSimultaneousLights = 4;
  42375. /**
  42376. * If sets to true, disables all the lights affecting the material.
  42377. */
  42378. _this.disableLighting = false;
  42379. /**
  42380. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42381. */
  42382. _this.invertNormalMapX = false;
  42383. /**
  42384. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42385. */
  42386. _this.invertNormalMapY = false;
  42387. /**
  42388. * Emissivie color used to self-illuminate the model.
  42389. */
  42390. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42391. /**
  42392. * Occlusion Channel Strenght.
  42393. */
  42394. _this.occlusionStrength = 1.0;
  42395. _this.useLightmapAsShadowmap = false;
  42396. _this._useAlphaFromAlbedoTexture = true;
  42397. _this._useAmbientInGrayScale = true;
  42398. return _this;
  42399. }
  42400. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  42401. /**
  42402. * Gets the current double sided mode.
  42403. */
  42404. get: function () {
  42405. return this._twoSidedLighting;
  42406. },
  42407. /**
  42408. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42409. */
  42410. set: function (value) {
  42411. if (this._twoSidedLighting === value) {
  42412. return;
  42413. }
  42414. this._twoSidedLighting = value;
  42415. this.backFaceCulling = !value;
  42416. this._markAllSubMeshesAsTexturesDirty();
  42417. },
  42418. enumerable: true,
  42419. configurable: true
  42420. });
  42421. /**
  42422. * Return the active textures of the material.
  42423. */
  42424. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  42425. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42426. if (this.environmentTexture) {
  42427. activeTextures.push(this.environmentTexture);
  42428. }
  42429. if (this.normalTexture) {
  42430. activeTextures.push(this.normalTexture);
  42431. }
  42432. if (this.emissiveTexture) {
  42433. activeTextures.push(this.emissiveTexture);
  42434. }
  42435. if (this.occlusionTexture) {
  42436. activeTextures.push(this.occlusionTexture);
  42437. }
  42438. if (this.lightmapTexture) {
  42439. activeTextures.push(this.lightmapTexture);
  42440. }
  42441. return activeTextures;
  42442. };
  42443. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  42444. if (_super.prototype.hasTexture.call(this, texture)) {
  42445. return true;
  42446. }
  42447. if (this.lightmapTexture === texture) {
  42448. return true;
  42449. }
  42450. return false;
  42451. };
  42452. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  42453. return "PBRBaseSimpleMaterial";
  42454. };
  42455. __decorate([
  42456. BABYLON.serialize(),
  42457. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42458. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  42459. __decorate([
  42460. BABYLON.serialize(),
  42461. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42462. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  42463. __decorate([
  42464. BABYLON.serializeAsTexture(),
  42465. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  42466. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  42467. __decorate([
  42468. BABYLON.serialize(),
  42469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42470. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  42471. __decorate([
  42472. BABYLON.serialize(),
  42473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42474. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  42475. __decorate([
  42476. BABYLON.serializeAsTexture(),
  42477. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  42478. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  42479. __decorate([
  42480. BABYLON.serializeAsColor3("emissive"),
  42481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42482. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  42483. __decorate([
  42484. BABYLON.serializeAsTexture(),
  42485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42486. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  42487. __decorate([
  42488. BABYLON.serialize(),
  42489. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  42490. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  42491. __decorate([
  42492. BABYLON.serializeAsTexture(),
  42493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  42494. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  42495. __decorate([
  42496. BABYLON.serialize(),
  42497. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  42498. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  42499. __decorate([
  42500. BABYLON.serialize()
  42501. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  42502. __decorate([
  42503. BABYLON.serializeAsTexture(),
  42504. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42505. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  42506. __decorate([
  42507. BABYLON.serialize(),
  42508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42509. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42510. return PBRBaseSimpleMaterial;
  42511. }(BABYLON.PBRBaseMaterial));
  42512. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  42513. })(BABYLON || (BABYLON = {}));
  42514. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  42515. "use strict";
  42516. var BABYLON;
  42517. (function (BABYLON) {
  42518. /**
  42519. * The Physically based material of BJS.
  42520. *
  42521. * This offers the main features of a standard PBR material.
  42522. * For more information, please refer to the documentation :
  42523. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  42524. */
  42525. var PBRMaterial = /** @class */ (function (_super) {
  42526. __extends(PBRMaterial, _super);
  42527. /**
  42528. * Instantiates a new PBRMaterial instance.
  42529. *
  42530. * @param name The material name
  42531. * @param scene The scene the material will be use in.
  42532. */
  42533. function PBRMaterial(name, scene) {
  42534. var _this = _super.call(this, name, scene) || this;
  42535. /**
  42536. * Intensity of the direct lights e.g. the four lights available in your scene.
  42537. * This impacts both the direct diffuse and specular highlights.
  42538. */
  42539. _this.directIntensity = 1.0;
  42540. /**
  42541. * Intensity of the emissive part of the material.
  42542. * This helps controlling the emissive effect without modifying the emissive color.
  42543. */
  42544. _this.emissiveIntensity = 1.0;
  42545. /**
  42546. * Intensity of the environment e.g. how much the environment will light the object
  42547. * either through harmonics for rough material or through the refelction for shiny ones.
  42548. */
  42549. _this.environmentIntensity = 1.0;
  42550. /**
  42551. * This is a special control allowing the reduction of the specular highlights coming from the
  42552. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  42553. */
  42554. _this.specularIntensity = 1.0;
  42555. /**
  42556. * Debug Control allowing disabling the bump map on this material.
  42557. */
  42558. _this.disableBumpMap = false;
  42559. /**
  42560. * AKA Occlusion Texture Intensity in other nomenclature.
  42561. */
  42562. _this.ambientTextureStrength = 1.0;
  42563. /**
  42564. * The color of a material in ambient lighting.
  42565. */
  42566. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42567. /**
  42568. * AKA Diffuse Color in other nomenclature.
  42569. */
  42570. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  42571. /**
  42572. * AKA Specular Color in other nomenclature.
  42573. */
  42574. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  42575. /**
  42576. * The color reflected from the material.
  42577. */
  42578. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  42579. /**
  42580. * The color emitted from the material.
  42581. */
  42582. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42583. /**
  42584. * AKA Glossiness in other nomenclature.
  42585. */
  42586. _this.microSurface = 1.0;
  42587. /**
  42588. * source material index of refraction (IOR)' / 'destination material IOR.
  42589. */
  42590. _this.indexOfRefraction = 0.66;
  42591. /**
  42592. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  42593. */
  42594. _this.invertRefractionY = false;
  42595. /**
  42596. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  42597. * Materials half opaque for instance using refraction could benefit from this control.
  42598. */
  42599. _this.linkRefractionWithTransparency = false;
  42600. _this.useLightmapAsShadowmap = false;
  42601. /**
  42602. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  42603. */
  42604. _this.useAlphaFromAlbedoTexture = false;
  42605. /**
  42606. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  42607. */
  42608. _this.forceAlphaTest = false;
  42609. /**
  42610. * Defines the alpha limits in alpha test mode.
  42611. */
  42612. _this.alphaCutOff = 0.4;
  42613. /**
  42614. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  42615. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  42616. */
  42617. _this.useSpecularOverAlpha = true;
  42618. /**
  42619. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  42620. */
  42621. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  42622. /**
  42623. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  42624. */
  42625. _this.useRoughnessFromMetallicTextureAlpha = true;
  42626. /**
  42627. * Specifies if the metallic texture contains the roughness information in its green channel.
  42628. */
  42629. _this.useRoughnessFromMetallicTextureGreen = false;
  42630. /**
  42631. * Specifies if the metallic texture contains the metallness information in its blue channel.
  42632. */
  42633. _this.useMetallnessFromMetallicTextureBlue = false;
  42634. /**
  42635. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  42636. */
  42637. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  42638. /**
  42639. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  42640. */
  42641. _this.useAmbientInGrayScale = false;
  42642. /**
  42643. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  42644. * The material will try to infer what glossiness each pixel should be.
  42645. */
  42646. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  42647. /**
  42648. * BJS is using an harcoded light falloff based on a manually sets up range.
  42649. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  42650. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  42651. */
  42652. _this.usePhysicalLightFalloff = true;
  42653. /**
  42654. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  42655. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  42656. */
  42657. _this.useRadianceOverAlpha = true;
  42658. /**
  42659. * Allows using an object space normal map (instead of tangent space).
  42660. */
  42661. _this.useObjectSpaceNormalMap = false;
  42662. /**
  42663. * Allows using the bump map in parallax mode.
  42664. */
  42665. _this.useParallax = false;
  42666. /**
  42667. * Allows using the bump map in parallax occlusion mode.
  42668. */
  42669. _this.useParallaxOcclusion = false;
  42670. /**
  42671. * Controls the scale bias of the parallax mode.
  42672. */
  42673. _this.parallaxScaleBias = 0.05;
  42674. /**
  42675. * If sets to true, disables all the lights affecting the material.
  42676. */
  42677. _this.disableLighting = false;
  42678. /**
  42679. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  42680. */
  42681. _this.forceIrradianceInFragment = false;
  42682. /**
  42683. * Number of Simultaneous lights allowed on the material.
  42684. */
  42685. _this.maxSimultaneousLights = 4;
  42686. /**
  42687. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42688. */
  42689. _this.invertNormalMapX = false;
  42690. /**
  42691. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42692. */
  42693. _this.invertNormalMapY = false;
  42694. /**
  42695. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42696. */
  42697. _this.twoSidedLighting = false;
  42698. /**
  42699. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42700. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  42701. */
  42702. _this.useAlphaFresnel = false;
  42703. /**
  42704. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42705. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42706. */
  42707. _this.useLinearAlphaFresnel = false;
  42708. /**
  42709. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42710. * And/Or occlude the blended part.
  42711. */
  42712. _this.environmentBRDFTexture = null;
  42713. /**
  42714. * Force normal to face away from face.
  42715. */
  42716. _this.forceNormalForward = false;
  42717. /**
  42718. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42719. * makes the reflect vector face the model (under horizon).
  42720. */
  42721. _this.useHorizonOcclusion = true;
  42722. /**
  42723. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42724. * too much the area relying on ambient texture to define their ambient occlusion.
  42725. */
  42726. _this.useRadianceOcclusion = true;
  42727. /**
  42728. * If set to true, no lighting calculations will be applied.
  42729. */
  42730. _this.unlit = false;
  42731. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42732. return _this;
  42733. }
  42734. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42735. /**
  42736. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42737. */
  42738. get: function () {
  42739. return this._PBRMATERIAL_OPAQUE;
  42740. },
  42741. enumerable: true,
  42742. configurable: true
  42743. });
  42744. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42745. /**
  42746. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42747. */
  42748. get: function () {
  42749. return this._PBRMATERIAL_ALPHATEST;
  42750. },
  42751. enumerable: true,
  42752. configurable: true
  42753. });
  42754. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42755. /**
  42756. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42757. */
  42758. get: function () {
  42759. return this._PBRMATERIAL_ALPHABLEND;
  42760. },
  42761. enumerable: true,
  42762. configurable: true
  42763. });
  42764. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42765. /**
  42766. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42767. * They are also discarded below the alpha cutoff threshold to improve performances.
  42768. */
  42769. get: function () {
  42770. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42771. },
  42772. enumerable: true,
  42773. configurable: true
  42774. });
  42775. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42776. /**
  42777. * Gets the image processing configuration used either in this material.
  42778. */
  42779. get: function () {
  42780. return this._imageProcessingConfiguration;
  42781. },
  42782. /**
  42783. * Sets the Default image processing configuration used either in the this material.
  42784. *
  42785. * If sets to null, the scene one is in use.
  42786. */
  42787. set: function (value) {
  42788. this._attachImageProcessingConfiguration(value);
  42789. // Ensure the effect will be rebuilt.
  42790. this._markAllSubMeshesAsTexturesDirty();
  42791. },
  42792. enumerable: true,
  42793. configurable: true
  42794. });
  42795. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42796. /**
  42797. * Gets wether the color curves effect is enabled.
  42798. */
  42799. get: function () {
  42800. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42801. },
  42802. /**
  42803. * Sets wether the color curves effect is enabled.
  42804. */
  42805. set: function (value) {
  42806. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42807. },
  42808. enumerable: true,
  42809. configurable: true
  42810. });
  42811. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42812. /**
  42813. * Gets wether the color grading effect is enabled.
  42814. */
  42815. get: function () {
  42816. return this.imageProcessingConfiguration.colorGradingEnabled;
  42817. },
  42818. /**
  42819. * Gets wether the color grading effect is enabled.
  42820. */
  42821. set: function (value) {
  42822. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42823. },
  42824. enumerable: true,
  42825. configurable: true
  42826. });
  42827. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42828. /**
  42829. * Gets wether tonemapping is enabled or not.
  42830. */
  42831. get: function () {
  42832. return this._imageProcessingConfiguration.toneMappingEnabled;
  42833. },
  42834. /**
  42835. * Sets wether tonemapping is enabled or not
  42836. */
  42837. set: function (value) {
  42838. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42839. },
  42840. enumerable: true,
  42841. configurable: true
  42842. });
  42843. ;
  42844. ;
  42845. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42846. /**
  42847. * The camera exposure used on this material.
  42848. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42849. * This corresponds to a photographic exposure.
  42850. */
  42851. get: function () {
  42852. return this._imageProcessingConfiguration.exposure;
  42853. },
  42854. /**
  42855. * The camera exposure used on this material.
  42856. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42857. * This corresponds to a photographic exposure.
  42858. */
  42859. set: function (value) {
  42860. this._imageProcessingConfiguration.exposure = value;
  42861. },
  42862. enumerable: true,
  42863. configurable: true
  42864. });
  42865. ;
  42866. ;
  42867. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42868. /**
  42869. * Gets The camera contrast used on this material.
  42870. */
  42871. get: function () {
  42872. return this._imageProcessingConfiguration.contrast;
  42873. },
  42874. /**
  42875. * Sets The camera contrast used on this material.
  42876. */
  42877. set: function (value) {
  42878. this._imageProcessingConfiguration.contrast = value;
  42879. },
  42880. enumerable: true,
  42881. configurable: true
  42882. });
  42883. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42884. /**
  42885. * Gets the Color Grading 2D Lookup Texture.
  42886. */
  42887. get: function () {
  42888. return this._imageProcessingConfiguration.colorGradingTexture;
  42889. },
  42890. /**
  42891. * Sets the Color Grading 2D Lookup Texture.
  42892. */
  42893. set: function (value) {
  42894. this._imageProcessingConfiguration.colorGradingTexture = value;
  42895. },
  42896. enumerable: true,
  42897. configurable: true
  42898. });
  42899. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42900. /**
  42901. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42902. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42903. * 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;
  42904. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42905. */
  42906. get: function () {
  42907. return this._imageProcessingConfiguration.colorCurves;
  42908. },
  42909. /**
  42910. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42911. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42912. * 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;
  42913. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42914. */
  42915. set: function (value) {
  42916. this._imageProcessingConfiguration.colorCurves = value;
  42917. },
  42918. enumerable: true,
  42919. configurable: true
  42920. });
  42921. /**
  42922. * Returns the name of this material class.
  42923. */
  42924. PBRMaterial.prototype.getClassName = function () {
  42925. return "PBRMaterial";
  42926. };
  42927. /**
  42928. * Returns an array of the actively used textures.
  42929. * @returns - Array of BaseTextures
  42930. */
  42931. PBRMaterial.prototype.getActiveTextures = function () {
  42932. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42933. if (this._albedoTexture) {
  42934. activeTextures.push(this._albedoTexture);
  42935. }
  42936. if (this._ambientTexture) {
  42937. activeTextures.push(this._ambientTexture);
  42938. }
  42939. if (this._opacityTexture) {
  42940. activeTextures.push(this._opacityTexture);
  42941. }
  42942. if (this._reflectionTexture) {
  42943. activeTextures.push(this._reflectionTexture);
  42944. }
  42945. if (this._emissiveTexture) {
  42946. activeTextures.push(this._emissiveTexture);
  42947. }
  42948. if (this._reflectivityTexture) {
  42949. activeTextures.push(this._reflectivityTexture);
  42950. }
  42951. if (this._metallicTexture) {
  42952. activeTextures.push(this._metallicTexture);
  42953. }
  42954. if (this._microSurfaceTexture) {
  42955. activeTextures.push(this._microSurfaceTexture);
  42956. }
  42957. if (this._bumpTexture) {
  42958. activeTextures.push(this._bumpTexture);
  42959. }
  42960. if (this._lightmapTexture) {
  42961. activeTextures.push(this._lightmapTexture);
  42962. }
  42963. if (this._refractionTexture) {
  42964. activeTextures.push(this._refractionTexture);
  42965. }
  42966. return activeTextures;
  42967. };
  42968. /**
  42969. * Checks to see if a texture is used in the material.
  42970. * @param texture - Base texture to use.
  42971. * @returns - Boolean specifying if a texture is used in the material.
  42972. */
  42973. PBRMaterial.prototype.hasTexture = function (texture) {
  42974. if (_super.prototype.hasTexture.call(this, texture)) {
  42975. return true;
  42976. }
  42977. if (this._albedoTexture === texture) {
  42978. return true;
  42979. }
  42980. if (this._ambientTexture === texture) {
  42981. return true;
  42982. }
  42983. if (this._opacityTexture === texture) {
  42984. return true;
  42985. }
  42986. if (this._reflectionTexture === texture) {
  42987. return true;
  42988. }
  42989. if (this._reflectivityTexture === texture) {
  42990. return true;
  42991. }
  42992. if (this._metallicTexture === texture) {
  42993. return true;
  42994. }
  42995. if (this._microSurfaceTexture === texture) {
  42996. return true;
  42997. }
  42998. if (this._bumpTexture === texture) {
  42999. return true;
  43000. }
  43001. if (this._lightmapTexture === texture) {
  43002. return true;
  43003. }
  43004. if (this._refractionTexture === texture) {
  43005. return true;
  43006. }
  43007. return false;
  43008. };
  43009. /**
  43010. * Makes a duplicate of the current material.
  43011. * @param name - name to use for the new material.
  43012. */
  43013. PBRMaterial.prototype.clone = function (name) {
  43014. var _this = this;
  43015. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  43016. clone.id = name;
  43017. clone.name = name;
  43018. return clone;
  43019. };
  43020. /**
  43021. * Serializes this PBR Material.
  43022. * @returns - An object with the serialized material.
  43023. */
  43024. PBRMaterial.prototype.serialize = function () {
  43025. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43026. serializationObject.customType = "BABYLON.PBRMaterial";
  43027. return serializationObject;
  43028. };
  43029. // Statics
  43030. /**
  43031. * Parses a PBR Material from a serialized object.
  43032. * @param source - Serialized object.
  43033. * @param scene - BJS scene instance.
  43034. * @param rootUrl - url for the scene object
  43035. * @returns - PBRMaterial
  43036. */
  43037. PBRMaterial.Parse = function (source, scene, rootUrl) {
  43038. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  43039. };
  43040. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  43041. /**
  43042. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  43043. */
  43044. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  43045. /**
  43046. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  43047. */
  43048. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  43049. /**
  43050. * 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.
  43051. * They are also discarded below the alpha cutoff threshold to improve performances.
  43052. */
  43053. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  43054. __decorate([
  43055. BABYLON.serialize(),
  43056. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43057. ], PBRMaterial.prototype, "directIntensity", void 0);
  43058. __decorate([
  43059. BABYLON.serialize(),
  43060. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43061. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  43062. __decorate([
  43063. BABYLON.serialize(),
  43064. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43065. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  43066. __decorate([
  43067. BABYLON.serialize(),
  43068. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43069. ], PBRMaterial.prototype, "specularIntensity", void 0);
  43070. __decorate([
  43071. BABYLON.serialize(),
  43072. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43073. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  43074. __decorate([
  43075. BABYLON.serializeAsTexture(),
  43076. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43077. ], PBRMaterial.prototype, "albedoTexture", void 0);
  43078. __decorate([
  43079. BABYLON.serializeAsTexture(),
  43080. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43081. ], PBRMaterial.prototype, "ambientTexture", void 0);
  43082. __decorate([
  43083. BABYLON.serialize(),
  43084. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43085. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  43086. __decorate([
  43087. BABYLON.serializeAsTexture(),
  43088. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43089. ], PBRMaterial.prototype, "opacityTexture", void 0);
  43090. __decorate([
  43091. BABYLON.serializeAsTexture(),
  43092. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43093. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  43094. __decorate([
  43095. BABYLON.serializeAsTexture(),
  43096. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43097. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  43098. __decorate([
  43099. BABYLON.serializeAsTexture(),
  43100. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43101. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  43102. __decorate([
  43103. BABYLON.serializeAsTexture(),
  43104. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43105. ], PBRMaterial.prototype, "metallicTexture", void 0);
  43106. __decorate([
  43107. BABYLON.serialize(),
  43108. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43109. ], PBRMaterial.prototype, "metallic", void 0);
  43110. __decorate([
  43111. BABYLON.serialize(),
  43112. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43113. ], PBRMaterial.prototype, "roughness", void 0);
  43114. __decorate([
  43115. BABYLON.serializeAsTexture(),
  43116. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43117. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  43118. __decorate([
  43119. BABYLON.serializeAsTexture(),
  43120. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43121. ], PBRMaterial.prototype, "bumpTexture", void 0);
  43122. __decorate([
  43123. BABYLON.serializeAsTexture(),
  43124. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  43125. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  43126. __decorate([
  43127. BABYLON.serializeAsTexture(),
  43128. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43129. ], PBRMaterial.prototype, "refractionTexture", void 0);
  43130. __decorate([
  43131. BABYLON.serializeAsColor3("ambient"),
  43132. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43133. ], PBRMaterial.prototype, "ambientColor", void 0);
  43134. __decorate([
  43135. BABYLON.serializeAsColor3("albedo"),
  43136. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43137. ], PBRMaterial.prototype, "albedoColor", void 0);
  43138. __decorate([
  43139. BABYLON.serializeAsColor3("reflectivity"),
  43140. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43141. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  43142. __decorate([
  43143. BABYLON.serializeAsColor3("reflection"),
  43144. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43145. ], PBRMaterial.prototype, "reflectionColor", void 0);
  43146. __decorate([
  43147. BABYLON.serializeAsColor3("emissive"),
  43148. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43149. ], PBRMaterial.prototype, "emissiveColor", void 0);
  43150. __decorate([
  43151. BABYLON.serialize(),
  43152. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43153. ], PBRMaterial.prototype, "microSurface", void 0);
  43154. __decorate([
  43155. BABYLON.serialize(),
  43156. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43157. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  43158. __decorate([
  43159. BABYLON.serialize(),
  43160. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43161. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  43162. __decorate([
  43163. BABYLON.serialize(),
  43164. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43165. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  43166. __decorate([
  43167. BABYLON.serialize(),
  43168. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43169. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43170. __decorate([
  43171. BABYLON.serialize(),
  43172. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43173. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  43174. __decorate([
  43175. BABYLON.serialize(),
  43176. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43177. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  43178. __decorate([
  43179. BABYLON.serialize(),
  43180. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43181. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  43182. __decorate([
  43183. BABYLON.serialize(),
  43184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43185. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  43186. __decorate([
  43187. BABYLON.serialize(),
  43188. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43189. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  43190. __decorate([
  43191. BABYLON.serialize(),
  43192. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43193. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  43194. __decorate([
  43195. BABYLON.serialize(),
  43196. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43197. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  43198. __decorate([
  43199. BABYLON.serialize(),
  43200. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43201. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  43202. __decorate([
  43203. BABYLON.serialize(),
  43204. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43205. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  43206. __decorate([
  43207. BABYLON.serialize(),
  43208. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43209. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  43210. __decorate([
  43211. BABYLON.serialize(),
  43212. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43213. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  43214. __decorate([
  43215. BABYLON.serialize(),
  43216. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43217. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  43218. __decorate([
  43219. BABYLON.serialize(),
  43220. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43221. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  43222. __decorate([
  43223. BABYLON.serialize(),
  43224. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43225. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43226. __decorate([
  43227. BABYLON.serialize(),
  43228. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43229. ], PBRMaterial.prototype, "useParallax", void 0);
  43230. __decorate([
  43231. BABYLON.serialize(),
  43232. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43233. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  43234. __decorate([
  43235. BABYLON.serialize(),
  43236. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43237. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  43238. __decorate([
  43239. BABYLON.serialize(),
  43240. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43241. ], PBRMaterial.prototype, "disableLighting", void 0);
  43242. __decorate([
  43243. BABYLON.serialize(),
  43244. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43245. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  43246. __decorate([
  43247. BABYLON.serialize(),
  43248. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43249. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  43250. __decorate([
  43251. BABYLON.serialize(),
  43252. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43253. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  43254. __decorate([
  43255. BABYLON.serialize(),
  43256. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43257. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  43258. __decorate([
  43259. BABYLON.serialize(),
  43260. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43261. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  43262. __decorate([
  43263. BABYLON.serialize(),
  43264. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43265. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  43266. __decorate([
  43267. BABYLON.serialize(),
  43268. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43269. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  43270. __decorate([
  43271. BABYLON.serializeAsTexture(),
  43272. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43273. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  43274. __decorate([
  43275. BABYLON.serialize(),
  43276. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43277. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  43278. __decorate([
  43279. BABYLON.serialize(),
  43280. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43281. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  43282. __decorate([
  43283. BABYLON.serialize(),
  43284. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43285. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  43286. __decorate([
  43287. BABYLON.serialize(),
  43288. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43289. ], PBRMaterial.prototype, "unlit", void 0);
  43290. return PBRMaterial;
  43291. }(BABYLON.PBRBaseMaterial));
  43292. BABYLON.PBRMaterial = PBRMaterial;
  43293. })(BABYLON || (BABYLON = {}));
  43294. //# sourceMappingURL=babylon.pbrMaterial.js.map
  43295. "use strict";
  43296. var BABYLON;
  43297. (function (BABYLON) {
  43298. /**
  43299. * The PBR material of BJS following the metal roughness convention.
  43300. *
  43301. * This fits to the PBR convention in the GLTF definition:
  43302. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  43303. */
  43304. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  43305. __extends(PBRMetallicRoughnessMaterial, _super);
  43306. /**
  43307. * Instantiates a new PBRMetalRoughnessMaterial instance.
  43308. *
  43309. * @param name The material name
  43310. * @param scene The scene the material will be use in.
  43311. */
  43312. function PBRMetallicRoughnessMaterial(name, scene) {
  43313. var _this = _super.call(this, name, scene) || this;
  43314. _this._useRoughnessFromMetallicTextureAlpha = false;
  43315. _this._useRoughnessFromMetallicTextureGreen = true;
  43316. _this._useMetallnessFromMetallicTextureBlue = true;
  43317. _this.metallic = 1.0;
  43318. _this.roughness = 1.0;
  43319. return _this;
  43320. }
  43321. /**
  43322. * Return the currrent class name of the material.
  43323. */
  43324. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  43325. return "PBRMetallicRoughnessMaterial";
  43326. };
  43327. /**
  43328. * Return the active textures of the material.
  43329. */
  43330. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  43331. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43332. if (this.baseTexture) {
  43333. activeTextures.push(this.baseTexture);
  43334. }
  43335. if (this.metallicRoughnessTexture) {
  43336. activeTextures.push(this.metallicRoughnessTexture);
  43337. }
  43338. return activeTextures;
  43339. };
  43340. /**
  43341. * Checks to see if a texture is used in the material.
  43342. * @param texture - Base texture to use.
  43343. * @returns - Boolean specifying if a texture is used in the material.
  43344. */
  43345. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  43346. if (_super.prototype.hasTexture.call(this, texture)) {
  43347. return true;
  43348. }
  43349. if (this.baseTexture === texture) {
  43350. return true;
  43351. }
  43352. if (this.metallicRoughnessTexture === texture) {
  43353. return true;
  43354. }
  43355. return false;
  43356. };
  43357. /**
  43358. * Makes a duplicate of the current material.
  43359. * @param name - name to use for the new material.
  43360. */
  43361. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  43362. var _this = this;
  43363. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  43364. clone.id = name;
  43365. clone.name = name;
  43366. return clone;
  43367. };
  43368. /**
  43369. * Serialize the material to a parsable JSON object.
  43370. */
  43371. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  43372. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43373. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  43374. return serializationObject;
  43375. };
  43376. /**
  43377. * Parses a JSON object correponding to the serialize function.
  43378. */
  43379. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  43380. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  43381. };
  43382. __decorate([
  43383. BABYLON.serializeAsColor3(),
  43384. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43385. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  43386. __decorate([
  43387. BABYLON.serializeAsTexture(),
  43388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43389. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  43390. __decorate([
  43391. BABYLON.serialize(),
  43392. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43393. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  43394. __decorate([
  43395. BABYLON.serialize(),
  43396. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43397. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  43398. __decorate([
  43399. BABYLON.serializeAsTexture(),
  43400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  43401. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  43402. return PBRMetallicRoughnessMaterial;
  43403. }(BABYLON.PBRBaseSimpleMaterial));
  43404. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  43405. })(BABYLON || (BABYLON = {}));
  43406. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  43407. "use strict";
  43408. var BABYLON;
  43409. (function (BABYLON) {
  43410. /**
  43411. * The PBR material of BJS following the specular glossiness convention.
  43412. *
  43413. * This fits to the PBR convention in the GLTF definition:
  43414. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  43415. */
  43416. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  43417. __extends(PBRSpecularGlossinessMaterial, _super);
  43418. /**
  43419. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  43420. *
  43421. * @param name The material name
  43422. * @param scene The scene the material will be use in.
  43423. */
  43424. function PBRSpecularGlossinessMaterial(name, scene) {
  43425. var _this = _super.call(this, name, scene) || this;
  43426. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  43427. return _this;
  43428. }
  43429. /**
  43430. * Return the currrent class name of the material.
  43431. */
  43432. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  43433. return "PBRSpecularGlossinessMaterial";
  43434. };
  43435. /**
  43436. * Return the active textures of the material.
  43437. */
  43438. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  43439. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43440. if (this.diffuseTexture) {
  43441. activeTextures.push(this.diffuseTexture);
  43442. }
  43443. if (this.specularGlossinessTexture) {
  43444. activeTextures.push(this.specularGlossinessTexture);
  43445. }
  43446. return activeTextures;
  43447. };
  43448. /**
  43449. * Checks to see if a texture is used in the material.
  43450. * @param texture - Base texture to use.
  43451. * @returns - Boolean specifying if a texture is used in the material.
  43452. */
  43453. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  43454. if (_super.prototype.hasTexture.call(this, texture)) {
  43455. return true;
  43456. }
  43457. if (this.diffuseTexture === texture) {
  43458. return true;
  43459. }
  43460. if (this.specularGlossinessTexture === texture) {
  43461. return true;
  43462. }
  43463. return false;
  43464. };
  43465. /**
  43466. * Makes a duplicate of the current material.
  43467. * @param name - name to use for the new material.
  43468. */
  43469. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  43470. var _this = this;
  43471. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  43472. clone.id = name;
  43473. clone.name = name;
  43474. return clone;
  43475. };
  43476. /**
  43477. * Serialize the material to a parsable JSON object.
  43478. */
  43479. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  43480. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43481. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  43482. return serializationObject;
  43483. };
  43484. /**
  43485. * Parses a JSON object correponding to the serialize function.
  43486. */
  43487. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  43488. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  43489. };
  43490. __decorate([
  43491. BABYLON.serializeAsColor3("diffuse"),
  43492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43493. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  43494. __decorate([
  43495. BABYLON.serializeAsTexture(),
  43496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43497. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  43498. __decorate([
  43499. BABYLON.serializeAsColor3("specular"),
  43500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  43501. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  43502. __decorate([
  43503. BABYLON.serialize(),
  43504. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  43505. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  43506. __decorate([
  43507. BABYLON.serializeAsTexture(),
  43508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  43509. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  43510. return PBRSpecularGlossinessMaterial;
  43511. }(BABYLON.PBRBaseSimpleMaterial));
  43512. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  43513. })(BABYLON || (BABYLON = {}));
  43514. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  43515. "use strict";
  43516. var BABYLON;
  43517. (function (BABYLON) {
  43518. BABYLON.CameraInputTypes = {};
  43519. var CameraInputsManager = /** @class */ (function () {
  43520. function CameraInputsManager(camera) {
  43521. this.attached = {};
  43522. this.camera = camera;
  43523. this.checkInputs = function () { };
  43524. }
  43525. /**
  43526. * Add an input method to a camera.
  43527. * builtin inputs example: camera.inputs.addGamepad();
  43528. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  43529. * @param input camera input method
  43530. */
  43531. CameraInputsManager.prototype.add = function (input) {
  43532. var type = input.getSimpleName();
  43533. if (this.attached[type]) {
  43534. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  43535. return;
  43536. }
  43537. this.attached[type] = input;
  43538. input.camera = this.camera;
  43539. //for checkInputs, we are dynamically creating a function
  43540. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  43541. if (input.checkInputs) {
  43542. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43543. }
  43544. if (this.attachedElement) {
  43545. input.attachControl(this.attachedElement);
  43546. }
  43547. };
  43548. /**
  43549. * Remove a specific input method from a camera
  43550. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  43551. * @param inputToRemove camera input method
  43552. */
  43553. CameraInputsManager.prototype.remove = function (inputToRemove) {
  43554. for (var cam in this.attached) {
  43555. var input = this.attached[cam];
  43556. if (input === inputToRemove) {
  43557. input.detachControl(this.attachedElement);
  43558. input.camera = null;
  43559. delete this.attached[cam];
  43560. this.rebuildInputCheck();
  43561. }
  43562. }
  43563. };
  43564. CameraInputsManager.prototype.removeByType = function (inputType) {
  43565. for (var cam in this.attached) {
  43566. var input = this.attached[cam];
  43567. if (input.getClassName() === inputType) {
  43568. input.detachControl(this.attachedElement);
  43569. input.camera = null;
  43570. delete this.attached[cam];
  43571. this.rebuildInputCheck();
  43572. }
  43573. }
  43574. };
  43575. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  43576. var current = this.checkInputs;
  43577. return function () {
  43578. current();
  43579. fn();
  43580. };
  43581. };
  43582. CameraInputsManager.prototype.attachInput = function (input) {
  43583. if (this.attachedElement) {
  43584. input.attachControl(this.attachedElement, this.noPreventDefault);
  43585. }
  43586. };
  43587. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  43588. if (noPreventDefault === void 0) { noPreventDefault = false; }
  43589. if (this.attachedElement) {
  43590. return;
  43591. }
  43592. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43593. this.attachedElement = element;
  43594. this.noPreventDefault = noPreventDefault;
  43595. for (var cam in this.attached) {
  43596. this.attached[cam].attachControl(element, noPreventDefault);
  43597. }
  43598. };
  43599. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  43600. if (disconnect === void 0) { disconnect = false; }
  43601. if (this.attachedElement !== element) {
  43602. return;
  43603. }
  43604. for (var cam in this.attached) {
  43605. this.attached[cam].detachControl(element);
  43606. if (disconnect) {
  43607. this.attached[cam].camera = null;
  43608. }
  43609. }
  43610. this.attachedElement = null;
  43611. };
  43612. CameraInputsManager.prototype.rebuildInputCheck = function () {
  43613. this.checkInputs = function () { };
  43614. for (var cam in this.attached) {
  43615. var input = this.attached[cam];
  43616. if (input.checkInputs) {
  43617. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43618. }
  43619. }
  43620. };
  43621. /**
  43622. * Remove all attached input methods from a camera
  43623. */
  43624. CameraInputsManager.prototype.clear = function () {
  43625. if (this.attachedElement) {
  43626. this.detachElement(this.attachedElement, true);
  43627. }
  43628. this.attached = {};
  43629. this.attachedElement = null;
  43630. this.checkInputs = function () { };
  43631. };
  43632. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  43633. var inputs = {};
  43634. for (var cam in this.attached) {
  43635. var input = this.attached[cam];
  43636. var res = BABYLON.SerializationHelper.Serialize(input);
  43637. inputs[input.getClassName()] = res;
  43638. }
  43639. serializedCamera.inputsmgr = inputs;
  43640. };
  43641. CameraInputsManager.prototype.parse = function (parsedCamera) {
  43642. var parsedInputs = parsedCamera.inputsmgr;
  43643. if (parsedInputs) {
  43644. this.clear();
  43645. for (var n in parsedInputs) {
  43646. var construct = BABYLON.CameraInputTypes[n];
  43647. if (construct) {
  43648. var parsedinput = parsedInputs[n];
  43649. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  43650. this.add(input);
  43651. }
  43652. }
  43653. }
  43654. else {
  43655. //2016-03-08 this part is for managing backward compatibility
  43656. for (var n in this.attached) {
  43657. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  43658. if (construct) {
  43659. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  43660. this.remove(this.attached[n]);
  43661. this.add(input);
  43662. }
  43663. }
  43664. }
  43665. };
  43666. return CameraInputsManager;
  43667. }());
  43668. BABYLON.CameraInputsManager = CameraInputsManager;
  43669. })(BABYLON || (BABYLON = {}));
  43670. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  43671. "use strict";
  43672. var BABYLON;
  43673. (function (BABYLON) {
  43674. var TargetCamera = /** @class */ (function (_super) {
  43675. __extends(TargetCamera, _super);
  43676. function TargetCamera(name, position, scene) {
  43677. var _this = _super.call(this, name, position, scene) || this;
  43678. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43679. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  43680. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  43681. _this.speed = 2.0;
  43682. _this.noRotationConstraint = false;
  43683. _this.lockedTarget = null;
  43684. _this._currentTarget = BABYLON.Vector3.Zero();
  43685. _this._viewMatrix = BABYLON.Matrix.Zero();
  43686. _this._camMatrix = BABYLON.Matrix.Zero();
  43687. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  43688. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  43689. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  43690. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  43691. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  43692. _this._lookAtTemp = BABYLON.Matrix.Zero();
  43693. _this._tempMatrix = BABYLON.Matrix.Zero();
  43694. return _this;
  43695. }
  43696. TargetCamera.prototype.getFrontPosition = function (distance) {
  43697. this.getWorldMatrix();
  43698. var direction = this.getTarget().subtract(this.position);
  43699. direction.normalize();
  43700. direction.scaleInPlace(distance);
  43701. return this.globalPosition.add(direction);
  43702. };
  43703. TargetCamera.prototype._getLockedTargetPosition = function () {
  43704. if (!this.lockedTarget) {
  43705. return null;
  43706. }
  43707. if (this.lockedTarget.absolutePosition) {
  43708. this.lockedTarget.computeWorldMatrix();
  43709. }
  43710. return this.lockedTarget.absolutePosition || this.lockedTarget;
  43711. };
  43712. TargetCamera.prototype.storeState = function () {
  43713. this._storedPosition = this.position.clone();
  43714. this._storedRotation = this.rotation.clone();
  43715. if (this.rotationQuaternion) {
  43716. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  43717. }
  43718. return _super.prototype.storeState.call(this);
  43719. };
  43720. /**
  43721. * Restored camera state. You must call storeState() first
  43722. */
  43723. TargetCamera.prototype._restoreStateValues = function () {
  43724. if (!_super.prototype._restoreStateValues.call(this)) {
  43725. return false;
  43726. }
  43727. this.position = this._storedPosition.clone();
  43728. this.rotation = this._storedRotation.clone();
  43729. if (this.rotationQuaternion) {
  43730. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43731. }
  43732. this.cameraDirection.copyFromFloats(0, 0, 0);
  43733. this.cameraRotation.copyFromFloats(0, 0);
  43734. return true;
  43735. };
  43736. // Cache
  43737. TargetCamera.prototype._initCache = function () {
  43738. _super.prototype._initCache.call(this);
  43739. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43740. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43741. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43742. };
  43743. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43744. if (!ignoreParentClass) {
  43745. _super.prototype._updateCache.call(this);
  43746. }
  43747. var lockedTargetPosition = this._getLockedTargetPosition();
  43748. if (!lockedTargetPosition) {
  43749. this._cache.lockedTarget = null;
  43750. }
  43751. else {
  43752. if (!this._cache.lockedTarget) {
  43753. this._cache.lockedTarget = lockedTargetPosition.clone();
  43754. }
  43755. else {
  43756. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43757. }
  43758. }
  43759. this._cache.rotation.copyFrom(this.rotation);
  43760. if (this.rotationQuaternion)
  43761. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43762. };
  43763. // Synchronized
  43764. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43765. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43766. return false;
  43767. }
  43768. var lockedTargetPosition = this._getLockedTargetPosition();
  43769. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43770. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43771. };
  43772. // Methods
  43773. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43774. var engine = this.getEngine();
  43775. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43776. };
  43777. // Target
  43778. TargetCamera.prototype.setTarget = function (target) {
  43779. this.upVector.normalize();
  43780. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43781. this._camMatrix.invert();
  43782. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43783. var vDir = target.subtract(this.position);
  43784. if (vDir.x >= 0.0) {
  43785. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43786. }
  43787. else {
  43788. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43789. }
  43790. this.rotation.z = 0;
  43791. if (isNaN(this.rotation.x)) {
  43792. this.rotation.x = 0;
  43793. }
  43794. if (isNaN(this.rotation.y)) {
  43795. this.rotation.y = 0;
  43796. }
  43797. if (isNaN(this.rotation.z)) {
  43798. this.rotation.z = 0;
  43799. }
  43800. if (this.rotationQuaternion) {
  43801. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43802. }
  43803. };
  43804. /**
  43805. * Return the current target position of the camera. This value is expressed in local space.
  43806. */
  43807. TargetCamera.prototype.getTarget = function () {
  43808. return this._currentTarget;
  43809. };
  43810. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43811. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43812. };
  43813. TargetCamera.prototype._updatePosition = function () {
  43814. if (this.parent) {
  43815. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43816. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43817. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43818. return;
  43819. }
  43820. this.position.addInPlace(this.cameraDirection);
  43821. };
  43822. TargetCamera.prototype._checkInputs = function () {
  43823. var needToMove = this._decideIfNeedsToMove();
  43824. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43825. // Move
  43826. if (needToMove) {
  43827. this._updatePosition();
  43828. }
  43829. // Rotate
  43830. if (needToRotate) {
  43831. this.rotation.x += this.cameraRotation.x;
  43832. this.rotation.y += this.cameraRotation.y;
  43833. //rotate, if quaternion is set and rotation was used
  43834. if (this.rotationQuaternion) {
  43835. var len = this.rotation.lengthSquared();
  43836. if (len) {
  43837. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43838. }
  43839. }
  43840. if (!this.noRotationConstraint) {
  43841. var limit = (Math.PI / 2) * 0.95;
  43842. if (this.rotation.x > limit)
  43843. this.rotation.x = limit;
  43844. if (this.rotation.x < -limit)
  43845. this.rotation.x = -limit;
  43846. }
  43847. }
  43848. // Inertia
  43849. if (needToMove) {
  43850. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43851. this.cameraDirection.x = 0;
  43852. }
  43853. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43854. this.cameraDirection.y = 0;
  43855. }
  43856. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43857. this.cameraDirection.z = 0;
  43858. }
  43859. this.cameraDirection.scaleInPlace(this.inertia);
  43860. }
  43861. if (needToRotate) {
  43862. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43863. this.cameraRotation.x = 0;
  43864. }
  43865. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43866. this.cameraRotation.y = 0;
  43867. }
  43868. this.cameraRotation.scaleInPlace(this.inertia);
  43869. }
  43870. _super.prototype._checkInputs.call(this);
  43871. };
  43872. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43873. if (this.rotationQuaternion) {
  43874. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43875. }
  43876. else {
  43877. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43878. }
  43879. //update the up vector!
  43880. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43881. };
  43882. TargetCamera.prototype._getViewMatrix = function () {
  43883. if (this.lockedTarget) {
  43884. this.setTarget(this._getLockedTargetPosition());
  43885. }
  43886. // Compute
  43887. this._updateCameraRotationMatrix();
  43888. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43889. // Computing target and final matrix
  43890. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43891. if (this.getScene().useRightHandedSystem) {
  43892. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43893. }
  43894. else {
  43895. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43896. }
  43897. return this._viewMatrix;
  43898. };
  43899. /**
  43900. * @override
  43901. * Override Camera.createRigCamera
  43902. */
  43903. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43904. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43905. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43906. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43907. if (!this.rotationQuaternion) {
  43908. this.rotationQuaternion = new BABYLON.Quaternion();
  43909. }
  43910. rigCamera._cameraRigParams = {};
  43911. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43912. }
  43913. return rigCamera;
  43914. }
  43915. return null;
  43916. };
  43917. /**
  43918. * @override
  43919. * Override Camera._updateRigCameras
  43920. */
  43921. TargetCamera.prototype._updateRigCameras = function () {
  43922. var camLeft = this._rigCameras[0];
  43923. var camRight = this._rigCameras[1];
  43924. switch (this.cameraRigMode) {
  43925. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43926. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43927. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43928. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43929. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43930. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43931. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43932. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43933. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43934. camLeft.setTarget(this.getTarget());
  43935. camRight.setTarget(this.getTarget());
  43936. break;
  43937. case BABYLON.Camera.RIG_MODE_VR:
  43938. if (camLeft.rotationQuaternion) {
  43939. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43940. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43941. }
  43942. else {
  43943. camLeft.rotation.copyFrom(this.rotation);
  43944. camRight.rotation.copyFrom(this.rotation);
  43945. }
  43946. camLeft.position.copyFrom(this.position);
  43947. camRight.position.copyFrom(this.position);
  43948. break;
  43949. }
  43950. _super.prototype._updateRigCameras.call(this);
  43951. };
  43952. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43953. if (!this._rigCamTransformMatrix) {
  43954. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43955. }
  43956. var target = this.getTarget();
  43957. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43958. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43959. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43960. };
  43961. TargetCamera.prototype.getClassName = function () {
  43962. return "TargetCamera";
  43963. };
  43964. __decorate([
  43965. BABYLON.serializeAsVector3()
  43966. ], TargetCamera.prototype, "rotation", void 0);
  43967. __decorate([
  43968. BABYLON.serialize()
  43969. ], TargetCamera.prototype, "speed", void 0);
  43970. __decorate([
  43971. BABYLON.serializeAsMeshReference("lockedTargetId")
  43972. ], TargetCamera.prototype, "lockedTarget", void 0);
  43973. return TargetCamera;
  43974. }(BABYLON.Camera));
  43975. BABYLON.TargetCamera = TargetCamera;
  43976. })(BABYLON || (BABYLON = {}));
  43977. //# sourceMappingURL=babylon.targetCamera.js.map
  43978. "use strict";
  43979. var BABYLON;
  43980. (function (BABYLON) {
  43981. var FreeCameraMouseInput = /** @class */ (function () {
  43982. function FreeCameraMouseInput(touchEnabled) {
  43983. if (touchEnabled === void 0) { touchEnabled = true; }
  43984. this.touchEnabled = touchEnabled;
  43985. this.buttons = [0, 1, 2];
  43986. this.angularSensibility = 2000.0;
  43987. this.previousPosition = null;
  43988. }
  43989. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43990. var _this = this;
  43991. var engine = this.camera.getEngine();
  43992. if (!this._pointerInput) {
  43993. this._pointerInput = function (p, s) {
  43994. var evt = p.event;
  43995. if (engine.isInVRExclusivePointerMode) {
  43996. return;
  43997. }
  43998. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43999. return;
  44000. }
  44001. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44002. return;
  44003. }
  44004. var srcElement = (evt.srcElement || evt.target);
  44005. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44006. try {
  44007. srcElement.setPointerCapture(evt.pointerId);
  44008. }
  44009. catch (e) {
  44010. //Nothing to do with the error. Execution will continue.
  44011. }
  44012. _this.previousPosition = {
  44013. x: evt.clientX,
  44014. y: evt.clientY
  44015. };
  44016. if (!noPreventDefault) {
  44017. evt.preventDefault();
  44018. element.focus();
  44019. }
  44020. }
  44021. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44022. try {
  44023. srcElement.releasePointerCapture(evt.pointerId);
  44024. }
  44025. catch (e) {
  44026. //Nothing to do with the error.
  44027. }
  44028. _this.previousPosition = null;
  44029. if (!noPreventDefault) {
  44030. evt.preventDefault();
  44031. }
  44032. }
  44033. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44034. if (!_this.previousPosition || engine.isPointerLock) {
  44035. return;
  44036. }
  44037. var offsetX = evt.clientX - _this.previousPosition.x;
  44038. var offsetY = evt.clientY - _this.previousPosition.y;
  44039. if (_this.camera.getScene().useRightHandedSystem) {
  44040. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  44041. }
  44042. else {
  44043. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  44044. }
  44045. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  44046. _this.previousPosition = {
  44047. x: evt.clientX,
  44048. y: evt.clientY
  44049. };
  44050. if (!noPreventDefault) {
  44051. evt.preventDefault();
  44052. }
  44053. }
  44054. };
  44055. }
  44056. this._onMouseMove = function (evt) {
  44057. if (!engine.isPointerLock) {
  44058. return;
  44059. }
  44060. if (engine.isInVRExclusivePointerMode) {
  44061. return;
  44062. }
  44063. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44064. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44065. if (_this.camera.getScene().useRightHandedSystem) {
  44066. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  44067. }
  44068. else {
  44069. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  44070. }
  44071. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  44072. _this.previousPosition = null;
  44073. if (!noPreventDefault) {
  44074. evt.preventDefault();
  44075. }
  44076. };
  44077. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  44078. element.addEventListener("mousemove", this._onMouseMove, false);
  44079. };
  44080. FreeCameraMouseInput.prototype.detachControl = function (element) {
  44081. if (this._observer && element) {
  44082. this.camera.getScene().onPointerObservable.remove(this._observer);
  44083. if (this._onMouseMove) {
  44084. element.removeEventListener("mousemove", this._onMouseMove);
  44085. }
  44086. this._observer = null;
  44087. this._onMouseMove = null;
  44088. this.previousPosition = null;
  44089. }
  44090. };
  44091. FreeCameraMouseInput.prototype.getClassName = function () {
  44092. return "FreeCameraMouseInput";
  44093. };
  44094. FreeCameraMouseInput.prototype.getSimpleName = function () {
  44095. return "mouse";
  44096. };
  44097. __decorate([
  44098. BABYLON.serialize()
  44099. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  44100. __decorate([
  44101. BABYLON.serialize()
  44102. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  44103. return FreeCameraMouseInput;
  44104. }());
  44105. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  44106. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  44107. })(BABYLON || (BABYLON = {}));
  44108. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  44109. "use strict";
  44110. var BABYLON;
  44111. (function (BABYLON) {
  44112. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  44113. function FreeCameraKeyboardMoveInput() {
  44114. this._keys = new Array();
  44115. this.keysUp = [38];
  44116. this.keysDown = [40];
  44117. this.keysLeft = [37];
  44118. this.keysRight = [39];
  44119. }
  44120. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44121. var _this = this;
  44122. if (this._onCanvasBlurObserver) {
  44123. return;
  44124. }
  44125. this._scene = this.camera.getScene();
  44126. this._engine = this._scene.getEngine();
  44127. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44128. _this._keys = [];
  44129. });
  44130. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44131. var evt = info.event;
  44132. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44133. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44134. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44135. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44136. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  44137. var index = _this._keys.indexOf(evt.keyCode);
  44138. if (index === -1) {
  44139. _this._keys.push(evt.keyCode);
  44140. }
  44141. if (!noPreventDefault) {
  44142. evt.preventDefault();
  44143. }
  44144. }
  44145. }
  44146. else {
  44147. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44148. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44149. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44150. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  44151. var index = _this._keys.indexOf(evt.keyCode);
  44152. if (index >= 0) {
  44153. _this._keys.splice(index, 1);
  44154. }
  44155. if (!noPreventDefault) {
  44156. evt.preventDefault();
  44157. }
  44158. }
  44159. }
  44160. });
  44161. };
  44162. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44163. if (this._scene) {
  44164. if (this._onKeyboardObserver) {
  44165. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44166. }
  44167. if (this._onCanvasBlurObserver) {
  44168. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44169. }
  44170. this._onKeyboardObserver = null;
  44171. this._onCanvasBlurObserver = null;
  44172. }
  44173. this._keys = [];
  44174. };
  44175. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44176. if (this._onKeyboardObserver) {
  44177. var camera = this.camera;
  44178. // Keyboard
  44179. for (var index = 0; index < this._keys.length; index++) {
  44180. var keyCode = this._keys[index];
  44181. var speed = camera._computeLocalCameraSpeed();
  44182. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44183. camera._localDirection.copyFromFloats(-speed, 0, 0);
  44184. }
  44185. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44186. camera._localDirection.copyFromFloats(0, 0, speed);
  44187. }
  44188. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44189. camera._localDirection.copyFromFloats(speed, 0, 0);
  44190. }
  44191. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44192. camera._localDirection.copyFromFloats(0, 0, -speed);
  44193. }
  44194. if (camera.getScene().useRightHandedSystem) {
  44195. camera._localDirection.z *= -1;
  44196. }
  44197. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  44198. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  44199. camera.cameraDirection.addInPlace(camera._transformedDirection);
  44200. }
  44201. }
  44202. };
  44203. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  44204. return "FreeCameraKeyboardMoveInput";
  44205. };
  44206. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  44207. this._keys = [];
  44208. };
  44209. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44210. return "keyboard";
  44211. };
  44212. __decorate([
  44213. BABYLON.serialize()
  44214. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44215. __decorate([
  44216. BABYLON.serialize()
  44217. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44218. __decorate([
  44219. BABYLON.serialize()
  44220. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44221. __decorate([
  44222. BABYLON.serialize()
  44223. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44224. return FreeCameraKeyboardMoveInput;
  44225. }());
  44226. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  44227. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  44228. })(BABYLON || (BABYLON = {}));
  44229. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  44230. "use strict";
  44231. var BABYLON;
  44232. (function (BABYLON) {
  44233. var FreeCameraInputsManager = /** @class */ (function (_super) {
  44234. __extends(FreeCameraInputsManager, _super);
  44235. function FreeCameraInputsManager(camera) {
  44236. return _super.call(this, camera) || this;
  44237. }
  44238. FreeCameraInputsManager.prototype.addKeyboard = function () {
  44239. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  44240. return this;
  44241. };
  44242. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  44243. if (touchEnabled === void 0) { touchEnabled = true; }
  44244. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  44245. return this;
  44246. };
  44247. FreeCameraInputsManager.prototype.addGamepad = function () {
  44248. this.add(new BABYLON.FreeCameraGamepadInput());
  44249. return this;
  44250. };
  44251. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  44252. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  44253. return this;
  44254. };
  44255. FreeCameraInputsManager.prototype.addTouch = function () {
  44256. this.add(new BABYLON.FreeCameraTouchInput());
  44257. return this;
  44258. };
  44259. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  44260. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  44261. return this;
  44262. };
  44263. return FreeCameraInputsManager;
  44264. }(BABYLON.CameraInputsManager));
  44265. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  44266. })(BABYLON || (BABYLON = {}));
  44267. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  44268. "use strict";
  44269. var BABYLON;
  44270. (function (BABYLON) {
  44271. var FreeCamera = /** @class */ (function (_super) {
  44272. __extends(FreeCamera, _super);
  44273. function FreeCamera(name, position, scene) {
  44274. var _this = _super.call(this, name, position, scene) || this;
  44275. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  44276. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  44277. _this.checkCollisions = false;
  44278. _this.applyGravity = false;
  44279. _this._needMoveForGravity = false;
  44280. _this._oldPosition = BABYLON.Vector3.Zero();
  44281. _this._diffPosition = BABYLON.Vector3.Zero();
  44282. _this._newPosition = BABYLON.Vector3.Zero();
  44283. // Collisions
  44284. _this._collisionMask = -1;
  44285. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44286. if (collidedMesh === void 0) { collidedMesh = null; }
  44287. //TODO move this to the collision coordinator!
  44288. if (_this.getScene().workerCollisions)
  44289. newPosition.multiplyInPlace(_this._collider._radius);
  44290. var updatePosition = function (newPos) {
  44291. _this._newPosition.copyFrom(newPos);
  44292. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  44293. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  44294. _this.position.addInPlace(_this._diffPosition);
  44295. if (_this.onCollide && collidedMesh) {
  44296. _this.onCollide(collidedMesh);
  44297. }
  44298. }
  44299. };
  44300. updatePosition(newPosition);
  44301. };
  44302. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  44303. _this.inputs.addKeyboard().addMouse();
  44304. return _this;
  44305. }
  44306. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  44307. //-- begin properties for backward compatibility for inputs
  44308. /**
  44309. * Gets the input sensibility for a mouse input. (default is 2000.0)
  44310. * Higher values reduce sensitivity.
  44311. */
  44312. get: function () {
  44313. var mouse = this.inputs.attached["mouse"];
  44314. if (mouse)
  44315. return mouse.angularSensibility;
  44316. return 0;
  44317. },
  44318. /**
  44319. * Sets the input sensibility for a mouse input. (default is 2000.0)
  44320. * Higher values reduce sensitivity.
  44321. */
  44322. set: function (value) {
  44323. var mouse = this.inputs.attached["mouse"];
  44324. if (mouse)
  44325. mouse.angularSensibility = value;
  44326. },
  44327. enumerable: true,
  44328. configurable: true
  44329. });
  44330. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  44331. get: function () {
  44332. var keyboard = this.inputs.attached["keyboard"];
  44333. if (keyboard)
  44334. return keyboard.keysUp;
  44335. return [];
  44336. },
  44337. set: function (value) {
  44338. var keyboard = this.inputs.attached["keyboard"];
  44339. if (keyboard)
  44340. keyboard.keysUp = value;
  44341. },
  44342. enumerable: true,
  44343. configurable: true
  44344. });
  44345. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  44346. get: function () {
  44347. var keyboard = this.inputs.attached["keyboard"];
  44348. if (keyboard)
  44349. return keyboard.keysDown;
  44350. return [];
  44351. },
  44352. set: function (value) {
  44353. var keyboard = this.inputs.attached["keyboard"];
  44354. if (keyboard)
  44355. keyboard.keysDown = value;
  44356. },
  44357. enumerable: true,
  44358. configurable: true
  44359. });
  44360. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  44361. get: function () {
  44362. var keyboard = this.inputs.attached["keyboard"];
  44363. if (keyboard)
  44364. return keyboard.keysLeft;
  44365. return [];
  44366. },
  44367. set: function (value) {
  44368. var keyboard = this.inputs.attached["keyboard"];
  44369. if (keyboard)
  44370. keyboard.keysLeft = value;
  44371. },
  44372. enumerable: true,
  44373. configurable: true
  44374. });
  44375. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  44376. get: function () {
  44377. var keyboard = this.inputs.attached["keyboard"];
  44378. if (keyboard)
  44379. return keyboard.keysRight;
  44380. return [];
  44381. },
  44382. set: function (value) {
  44383. var keyboard = this.inputs.attached["keyboard"];
  44384. if (keyboard)
  44385. keyboard.keysRight = value;
  44386. },
  44387. enumerable: true,
  44388. configurable: true
  44389. });
  44390. // Controls
  44391. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  44392. this.inputs.attachElement(element, noPreventDefault);
  44393. };
  44394. FreeCamera.prototype.detachControl = function (element) {
  44395. this.inputs.detachElement(element);
  44396. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  44397. this.cameraRotation = new BABYLON.Vector2(0, 0);
  44398. };
  44399. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  44400. get: function () {
  44401. return this._collisionMask;
  44402. },
  44403. set: function (mask) {
  44404. this._collisionMask = !isNaN(mask) ? mask : -1;
  44405. },
  44406. enumerable: true,
  44407. configurable: true
  44408. });
  44409. FreeCamera.prototype._collideWithWorld = function (displacement) {
  44410. var globalPosition;
  44411. if (this.parent) {
  44412. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  44413. }
  44414. else {
  44415. globalPosition = this.position;
  44416. }
  44417. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  44418. this._oldPosition.addInPlace(this.ellipsoidOffset);
  44419. if (!this._collider) {
  44420. this._collider = new BABYLON.Collider();
  44421. }
  44422. this._collider._radius = this.ellipsoid;
  44423. this._collider.collisionMask = this._collisionMask;
  44424. //no need for clone, as long as gravity is not on.
  44425. var actualDisplacement = displacement;
  44426. //add gravity to the direction to prevent the dual-collision checking
  44427. if (this.applyGravity) {
  44428. //this prevents mending with cameraDirection, a global variable of the free camera class.
  44429. actualDisplacement = displacement.add(this.getScene().gravity);
  44430. }
  44431. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44432. };
  44433. FreeCamera.prototype._checkInputs = function () {
  44434. if (!this._localDirection) {
  44435. this._localDirection = BABYLON.Vector3.Zero();
  44436. this._transformedDirection = BABYLON.Vector3.Zero();
  44437. }
  44438. this.inputs.checkInputs();
  44439. _super.prototype._checkInputs.call(this);
  44440. };
  44441. FreeCamera.prototype._decideIfNeedsToMove = function () {
  44442. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  44443. };
  44444. FreeCamera.prototype._updatePosition = function () {
  44445. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  44446. this._collideWithWorld(this.cameraDirection);
  44447. }
  44448. else {
  44449. _super.prototype._updatePosition.call(this);
  44450. }
  44451. };
  44452. FreeCamera.prototype.dispose = function () {
  44453. this.inputs.clear();
  44454. _super.prototype.dispose.call(this);
  44455. };
  44456. FreeCamera.prototype.getClassName = function () {
  44457. return "FreeCamera";
  44458. };
  44459. __decorate([
  44460. BABYLON.serializeAsVector3()
  44461. ], FreeCamera.prototype, "ellipsoid", void 0);
  44462. __decorate([
  44463. BABYLON.serializeAsVector3()
  44464. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  44465. __decorate([
  44466. BABYLON.serialize()
  44467. ], FreeCamera.prototype, "checkCollisions", void 0);
  44468. __decorate([
  44469. BABYLON.serialize()
  44470. ], FreeCamera.prototype, "applyGravity", void 0);
  44471. return FreeCamera;
  44472. }(BABYLON.TargetCamera));
  44473. BABYLON.FreeCamera = FreeCamera;
  44474. })(BABYLON || (BABYLON = {}));
  44475. //# sourceMappingURL=babylon.freeCamera.js.map
  44476. "use strict";
  44477. var BABYLON;
  44478. (function (BABYLON) {
  44479. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  44480. function ArcRotateCameraKeyboardMoveInput() {
  44481. this._keys = new Array();
  44482. this.keysUp = [38];
  44483. this.keysDown = [40];
  44484. this.keysLeft = [37];
  44485. this.keysRight = [39];
  44486. this.keysReset = [220];
  44487. this.panningSensibility = 50.0;
  44488. this.zoomingSensibility = 25.0;
  44489. this.useAltToZoom = true;
  44490. }
  44491. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44492. var _this = this;
  44493. if (this._onCanvasBlurObserver) {
  44494. return;
  44495. }
  44496. this._scene = this.camera.getScene();
  44497. this._engine = this._scene.getEngine();
  44498. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44499. _this._keys = [];
  44500. });
  44501. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44502. var evt = info.event;
  44503. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44504. _this._ctrlPressed = evt.ctrlKey;
  44505. _this._altPressed = evt.altKey;
  44506. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44507. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44508. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44509. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44510. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44511. var index = _this._keys.indexOf(evt.keyCode);
  44512. if (index === -1) {
  44513. _this._keys.push(evt.keyCode);
  44514. }
  44515. if (evt.preventDefault) {
  44516. if (!noPreventDefault) {
  44517. evt.preventDefault();
  44518. }
  44519. }
  44520. }
  44521. }
  44522. else {
  44523. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44524. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44525. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44526. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44527. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44528. var index = _this._keys.indexOf(evt.keyCode);
  44529. if (index >= 0) {
  44530. _this._keys.splice(index, 1);
  44531. }
  44532. if (evt.preventDefault) {
  44533. if (!noPreventDefault) {
  44534. evt.preventDefault();
  44535. }
  44536. }
  44537. }
  44538. }
  44539. });
  44540. };
  44541. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44542. if (this._scene) {
  44543. if (this._onKeyboardObserver) {
  44544. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44545. }
  44546. if (this._onCanvasBlurObserver) {
  44547. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44548. }
  44549. this._onKeyboardObserver = null;
  44550. this._onCanvasBlurObserver = null;
  44551. }
  44552. this._keys = [];
  44553. };
  44554. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44555. if (this._onKeyboardObserver) {
  44556. var camera = this.camera;
  44557. for (var index = 0; index < this._keys.length; index++) {
  44558. var keyCode = this._keys[index];
  44559. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44560. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44561. camera.inertialPanningX -= 1 / this.panningSensibility;
  44562. }
  44563. else {
  44564. camera.inertialAlphaOffset -= 0.01;
  44565. }
  44566. }
  44567. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44568. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44569. camera.inertialPanningY += 1 / this.panningSensibility;
  44570. }
  44571. else if (this._altPressed && this.useAltToZoom) {
  44572. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  44573. }
  44574. else {
  44575. camera.inertialBetaOffset -= 0.01;
  44576. }
  44577. }
  44578. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44579. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44580. camera.inertialPanningX += 1 / this.panningSensibility;
  44581. }
  44582. else {
  44583. camera.inertialAlphaOffset += 0.01;
  44584. }
  44585. }
  44586. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44587. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44588. camera.inertialPanningY -= 1 / this.panningSensibility;
  44589. }
  44590. else if (this._altPressed && this.useAltToZoom) {
  44591. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  44592. }
  44593. else {
  44594. camera.inertialBetaOffset += 0.01;
  44595. }
  44596. }
  44597. else if (this.keysReset.indexOf(keyCode) !== -1) {
  44598. camera.restoreState();
  44599. }
  44600. }
  44601. }
  44602. };
  44603. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  44604. return "ArcRotateCameraKeyboardMoveInput";
  44605. };
  44606. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44607. return "keyboard";
  44608. };
  44609. __decorate([
  44610. BABYLON.serialize()
  44611. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44612. __decorate([
  44613. BABYLON.serialize()
  44614. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44615. __decorate([
  44616. BABYLON.serialize()
  44617. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44618. __decorate([
  44619. BABYLON.serialize()
  44620. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44621. __decorate([
  44622. BABYLON.serialize()
  44623. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  44624. __decorate([
  44625. BABYLON.serialize()
  44626. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  44627. __decorate([
  44628. BABYLON.serialize()
  44629. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  44630. __decorate([
  44631. BABYLON.serialize()
  44632. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  44633. return ArcRotateCameraKeyboardMoveInput;
  44634. }());
  44635. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  44636. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  44637. })(BABYLON || (BABYLON = {}));
  44638. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  44639. "use strict";
  44640. var BABYLON;
  44641. (function (BABYLON) {
  44642. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  44643. function ArcRotateCameraMouseWheelInput() {
  44644. this.wheelPrecision = 3.0;
  44645. /**
  44646. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  44647. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  44648. */
  44649. this.wheelDeltaPercentage = 0;
  44650. }
  44651. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  44652. var _this = this;
  44653. this._wheel = function (p, s) {
  44654. //sanity check - this should be a PointerWheel event.
  44655. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  44656. return;
  44657. var event = p.event;
  44658. var delta = 0;
  44659. if (event.wheelDelta) {
  44660. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  44661. }
  44662. else if (event.detail) {
  44663. delta = -event.detail / _this.wheelPrecision;
  44664. }
  44665. if (delta)
  44666. _this.camera.inertialRadiusOffset += delta;
  44667. if (event.preventDefault) {
  44668. if (!noPreventDefault) {
  44669. event.preventDefault();
  44670. }
  44671. }
  44672. };
  44673. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  44674. };
  44675. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  44676. if (this._observer && element) {
  44677. this.camera.getScene().onPointerObservable.remove(this._observer);
  44678. this._observer = null;
  44679. this._wheel = null;
  44680. }
  44681. };
  44682. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  44683. return "ArcRotateCameraMouseWheelInput";
  44684. };
  44685. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  44686. return "mousewheel";
  44687. };
  44688. __decorate([
  44689. BABYLON.serialize()
  44690. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  44691. __decorate([
  44692. BABYLON.serialize()
  44693. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  44694. return ArcRotateCameraMouseWheelInput;
  44695. }());
  44696. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  44697. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  44698. })(BABYLON || (BABYLON = {}));
  44699. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  44700. "use strict";
  44701. var BABYLON;
  44702. (function (BABYLON) {
  44703. var ArcRotateCameraPointersInput = /** @class */ (function () {
  44704. function ArcRotateCameraPointersInput() {
  44705. this.buttons = [0, 1, 2];
  44706. this.angularSensibilityX = 1000.0;
  44707. this.angularSensibilityY = 1000.0;
  44708. this.pinchPrecision = 12.0;
  44709. /**
  44710. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  44711. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  44712. */
  44713. this.pinchDeltaPercentage = 0;
  44714. this.panningSensibility = 1000.0;
  44715. this.multiTouchPanning = true;
  44716. this.multiTouchPanAndZoom = true;
  44717. this._isPanClick = false;
  44718. this.pinchInwards = true;
  44719. }
  44720. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  44721. var _this = this;
  44722. var engine = this.camera.getEngine();
  44723. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  44724. var pointA = null;
  44725. var pointB = null;
  44726. var previousPinchSquaredDistance = 0;
  44727. var initialDistance = 0;
  44728. var twoFingerActivityCount = 0;
  44729. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44730. this._pointerInput = function (p, s) {
  44731. var evt = p.event;
  44732. var isTouch = p.event.pointerType === "touch";
  44733. if (engine.isInVRExclusivePointerMode) {
  44734. return;
  44735. }
  44736. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44737. return;
  44738. }
  44739. var srcElement = (evt.srcElement || evt.target);
  44740. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44741. try {
  44742. srcElement.setPointerCapture(evt.pointerId);
  44743. }
  44744. catch (e) {
  44745. //Nothing to do with the error. Execution will continue.
  44746. }
  44747. // Manage panning with pan button click
  44748. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44749. // manage pointers
  44750. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44751. if (pointA === null) {
  44752. pointA = cacheSoloPointer;
  44753. }
  44754. else if (pointB === null) {
  44755. pointB = cacheSoloPointer;
  44756. }
  44757. if (!noPreventDefault) {
  44758. evt.preventDefault();
  44759. element.focus();
  44760. }
  44761. }
  44762. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44763. _this.camera.restoreState();
  44764. }
  44765. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44766. try {
  44767. srcElement.releasePointerCapture(evt.pointerId);
  44768. }
  44769. catch (e) {
  44770. //Nothing to do with the error.
  44771. }
  44772. cacheSoloPointer = null;
  44773. previousPinchSquaredDistance = 0;
  44774. previousMultiTouchPanPosition.isPaning = false;
  44775. previousMultiTouchPanPosition.isPinching = false;
  44776. twoFingerActivityCount = 0;
  44777. initialDistance = 0;
  44778. if (!isTouch) {
  44779. pointB = null; // Mouse and pen are mono pointer
  44780. }
  44781. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44782. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44783. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44784. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44785. if (engine.badOS) {
  44786. pointA = pointB = null;
  44787. }
  44788. else {
  44789. //only remove the impacted pointer in case of multitouch allowing on most
  44790. //platforms switching from rotate to zoom and pan seamlessly.
  44791. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44792. pointA = pointB;
  44793. pointB = null;
  44794. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44795. }
  44796. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44797. pointB = null;
  44798. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44799. }
  44800. else {
  44801. pointA = pointB = null;
  44802. }
  44803. }
  44804. if (!noPreventDefault) {
  44805. evt.preventDefault();
  44806. }
  44807. }
  44808. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44809. if (!noPreventDefault) {
  44810. evt.preventDefault();
  44811. }
  44812. // One button down
  44813. if (pointA && pointB === null && cacheSoloPointer) {
  44814. if (_this.panningSensibility !== 0 &&
  44815. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44816. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44817. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44818. }
  44819. else {
  44820. var offsetX = evt.clientX - cacheSoloPointer.x;
  44821. var offsetY = evt.clientY - cacheSoloPointer.y;
  44822. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44823. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44824. }
  44825. cacheSoloPointer.x = evt.clientX;
  44826. cacheSoloPointer.y = evt.clientY;
  44827. }
  44828. else if (pointA && pointB) {
  44829. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44830. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44831. ed.x = evt.clientX;
  44832. ed.y = evt.clientY;
  44833. var direction = _this.pinchInwards ? 1 : -1;
  44834. var distX = pointA.x - pointB.x;
  44835. var distY = pointA.y - pointB.y;
  44836. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44837. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44838. if (previousPinchSquaredDistance === 0) {
  44839. initialDistance = pinchDistance;
  44840. previousPinchSquaredDistance = pinchSquaredDistance;
  44841. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44842. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44843. return;
  44844. }
  44845. if (_this.multiTouchPanAndZoom) {
  44846. if (_this.pinchDeltaPercentage) {
  44847. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44848. }
  44849. else {
  44850. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44851. (_this.pinchPrecision *
  44852. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44853. direction);
  44854. }
  44855. if (_this.panningSensibility !== 0) {
  44856. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44857. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44858. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44859. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44860. previousMultiTouchPanPosition.x = pointersCenterX;
  44861. previousMultiTouchPanPosition.y = pointersCenterY;
  44862. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44863. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44864. }
  44865. }
  44866. else {
  44867. twoFingerActivityCount++;
  44868. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44869. if (_this.pinchDeltaPercentage) {
  44870. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44871. }
  44872. else {
  44873. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44874. (_this.pinchPrecision *
  44875. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44876. direction);
  44877. }
  44878. previousMultiTouchPanPosition.isPaning = false;
  44879. previousMultiTouchPanPosition.isPinching = true;
  44880. }
  44881. else {
  44882. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44883. if (!previousMultiTouchPanPosition.isPaning) {
  44884. previousMultiTouchPanPosition.isPaning = true;
  44885. previousMultiTouchPanPosition.isPinching = false;
  44886. previousMultiTouchPanPosition.x = ed.x;
  44887. previousMultiTouchPanPosition.y = ed.y;
  44888. return;
  44889. }
  44890. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44891. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44892. }
  44893. }
  44894. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44895. previousMultiTouchPanPosition.x = ed.x;
  44896. previousMultiTouchPanPosition.y = ed.y;
  44897. }
  44898. }
  44899. previousPinchSquaredDistance = pinchSquaredDistance;
  44900. }
  44901. }
  44902. };
  44903. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44904. this._onContextMenu = function (evt) {
  44905. evt.preventDefault();
  44906. };
  44907. if (!this.camera._useCtrlForPanning) {
  44908. element.addEventListener("contextmenu", this._onContextMenu, false);
  44909. }
  44910. this._onLostFocus = function () {
  44911. //this._keys = [];
  44912. pointA = pointB = null;
  44913. previousPinchSquaredDistance = 0;
  44914. previousMultiTouchPanPosition.isPaning = false;
  44915. previousMultiTouchPanPosition.isPinching = false;
  44916. twoFingerActivityCount = 0;
  44917. cacheSoloPointer = null;
  44918. initialDistance = 0;
  44919. };
  44920. this._onMouseMove = function (evt) {
  44921. if (!engine.isPointerLock) {
  44922. return;
  44923. }
  44924. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44925. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44926. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44927. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44928. if (!noPreventDefault) {
  44929. evt.preventDefault();
  44930. }
  44931. };
  44932. this._onGestureStart = function (e) {
  44933. if (window.MSGesture === undefined) {
  44934. return;
  44935. }
  44936. if (!_this._MSGestureHandler) {
  44937. _this._MSGestureHandler = new MSGesture();
  44938. _this._MSGestureHandler.target = element;
  44939. }
  44940. _this._MSGestureHandler.addPointer(e.pointerId);
  44941. };
  44942. this._onGesture = function (e) {
  44943. _this.camera.radius *= e.scale;
  44944. if (e.preventDefault) {
  44945. if (!noPreventDefault) {
  44946. e.stopPropagation();
  44947. e.preventDefault();
  44948. }
  44949. }
  44950. };
  44951. element.addEventListener("mousemove", this._onMouseMove, false);
  44952. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44953. element.addEventListener("MSGestureChange", this._onGesture, false);
  44954. BABYLON.Tools.RegisterTopRootEvents([
  44955. { name: "blur", handler: this._onLostFocus }
  44956. ]);
  44957. };
  44958. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44959. if (this._onLostFocus) {
  44960. BABYLON.Tools.UnregisterTopRootEvents([
  44961. { name: "blur", handler: this._onLostFocus }
  44962. ]);
  44963. }
  44964. if (element && this._observer) {
  44965. this.camera.getScene().onPointerObservable.remove(this._observer);
  44966. this._observer = null;
  44967. if (this._onContextMenu) {
  44968. element.removeEventListener("contextmenu", this._onContextMenu);
  44969. }
  44970. if (this._onMouseMove) {
  44971. element.removeEventListener("mousemove", this._onMouseMove);
  44972. }
  44973. if (this._onGestureStart) {
  44974. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44975. }
  44976. if (this._onGesture) {
  44977. element.removeEventListener("MSGestureChange", this._onGesture);
  44978. }
  44979. this._isPanClick = false;
  44980. this.pinchInwards = true;
  44981. this._onMouseMove = null;
  44982. this._onGestureStart = null;
  44983. this._onGesture = null;
  44984. this._MSGestureHandler = null;
  44985. this._onLostFocus = null;
  44986. this._onContextMenu = null;
  44987. }
  44988. };
  44989. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44990. return "ArcRotateCameraPointersInput";
  44991. };
  44992. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44993. return "pointers";
  44994. };
  44995. __decorate([
  44996. BABYLON.serialize()
  44997. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44998. __decorate([
  44999. BABYLON.serialize()
  45000. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  45001. __decorate([
  45002. BABYLON.serialize()
  45003. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  45004. __decorate([
  45005. BABYLON.serialize()
  45006. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  45007. __decorate([
  45008. BABYLON.serialize()
  45009. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  45010. __decorate([
  45011. BABYLON.serialize()
  45012. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  45013. __decorate([
  45014. BABYLON.serialize()
  45015. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  45016. __decorate([
  45017. BABYLON.serialize()
  45018. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  45019. return ArcRotateCameraPointersInput;
  45020. }());
  45021. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  45022. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  45023. })(BABYLON || (BABYLON = {}));
  45024. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  45025. "use strict";
  45026. var BABYLON;
  45027. (function (BABYLON) {
  45028. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  45029. __extends(ArcRotateCameraInputsManager, _super);
  45030. function ArcRotateCameraInputsManager(camera) {
  45031. return _super.call(this, camera) || this;
  45032. }
  45033. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  45034. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  45035. return this;
  45036. };
  45037. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  45038. this.add(new BABYLON.ArcRotateCameraPointersInput());
  45039. return this;
  45040. };
  45041. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  45042. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  45043. return this;
  45044. };
  45045. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  45046. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  45047. return this;
  45048. };
  45049. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  45050. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  45051. return this;
  45052. };
  45053. return ArcRotateCameraInputsManager;
  45054. }(BABYLON.CameraInputsManager));
  45055. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  45056. })(BABYLON || (BABYLON = {}));
  45057. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  45058. "use strict";
  45059. var BABYLON;
  45060. (function (BABYLON) {
  45061. var ArcRotateCamera = /** @class */ (function (_super) {
  45062. __extends(ArcRotateCamera, _super);
  45063. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  45064. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  45065. _this.inertialAlphaOffset = 0;
  45066. _this.inertialBetaOffset = 0;
  45067. _this.inertialRadiusOffset = 0;
  45068. _this.lowerAlphaLimit = null;
  45069. _this.upperAlphaLimit = null;
  45070. _this.lowerBetaLimit = 0.01;
  45071. _this.upperBetaLimit = Math.PI;
  45072. _this.lowerRadiusLimit = null;
  45073. _this.upperRadiusLimit = null;
  45074. _this.inertialPanningX = 0;
  45075. _this.inertialPanningY = 0;
  45076. _this.pinchToPanMaxDistance = 20;
  45077. _this.panningDistanceLimit = null;
  45078. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  45079. _this.panningInertia = 0.9;
  45080. //-- end properties for backward compatibility for inputs
  45081. _this.zoomOnFactor = 1;
  45082. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  45083. _this.allowUpsideDown = true;
  45084. _this._viewMatrix = new BABYLON.Matrix();
  45085. // Panning
  45086. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  45087. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  45088. _this.checkCollisions = false;
  45089. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  45090. _this._previousPosition = BABYLON.Vector3.Zero();
  45091. _this._collisionVelocity = BABYLON.Vector3.Zero();
  45092. _this._newPosition = BABYLON.Vector3.Zero();
  45093. _this._computationVector = BABYLON.Vector3.Zero();
  45094. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  45095. if (collidedMesh === void 0) { collidedMesh = null; }
  45096. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  45097. newPosition.multiplyInPlace(_this._collider._radius);
  45098. }
  45099. if (!collidedMesh) {
  45100. _this._previousPosition.copyFrom(_this.position);
  45101. }
  45102. else {
  45103. _this.setPosition(newPosition);
  45104. if (_this.onCollide) {
  45105. _this.onCollide(collidedMesh);
  45106. }
  45107. }
  45108. // Recompute because of constraints
  45109. var cosa = Math.cos(_this.alpha);
  45110. var sina = Math.sin(_this.alpha);
  45111. var cosb = Math.cos(_this.beta);
  45112. var sinb = Math.sin(_this.beta);
  45113. if (sinb === 0) {
  45114. sinb = 0.0001;
  45115. }
  45116. var target = _this._getTargetPosition();
  45117. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  45118. target.addToRef(_this._computationVector, _this._newPosition);
  45119. _this.position.copyFrom(_this._newPosition);
  45120. var up = _this.upVector;
  45121. if (_this.allowUpsideDown && _this.beta < 0) {
  45122. up = up.clone();
  45123. up = up.negate();
  45124. }
  45125. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  45126. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  45127. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  45128. _this._collisionTriggered = false;
  45129. };
  45130. _this._target = BABYLON.Vector3.Zero();
  45131. if (target) {
  45132. _this.setTarget(target);
  45133. }
  45134. _this.alpha = alpha;
  45135. _this.beta = beta;
  45136. _this.radius = radius;
  45137. _this.getViewMatrix();
  45138. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  45139. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  45140. return _this;
  45141. }
  45142. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  45143. get: function () {
  45144. return this._target;
  45145. },
  45146. set: function (value) {
  45147. this.setTarget(value);
  45148. },
  45149. enumerable: true,
  45150. configurable: true
  45151. });
  45152. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  45153. //-- begin properties for backward compatibility for inputs
  45154. get: function () {
  45155. var pointers = this.inputs.attached["pointers"];
  45156. if (pointers)
  45157. return pointers.angularSensibilityX;
  45158. return 0;
  45159. },
  45160. set: function (value) {
  45161. var pointers = this.inputs.attached["pointers"];
  45162. if (pointers) {
  45163. pointers.angularSensibilityX = value;
  45164. }
  45165. },
  45166. enumerable: true,
  45167. configurable: true
  45168. });
  45169. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  45170. get: function () {
  45171. var pointers = this.inputs.attached["pointers"];
  45172. if (pointers)
  45173. return pointers.angularSensibilityY;
  45174. return 0;
  45175. },
  45176. set: function (value) {
  45177. var pointers = this.inputs.attached["pointers"];
  45178. if (pointers) {
  45179. pointers.angularSensibilityY = value;
  45180. }
  45181. },
  45182. enumerable: true,
  45183. configurable: true
  45184. });
  45185. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  45186. get: function () {
  45187. var pointers = this.inputs.attached["pointers"];
  45188. if (pointers)
  45189. return pointers.pinchPrecision;
  45190. return 0;
  45191. },
  45192. set: function (value) {
  45193. var pointers = this.inputs.attached["pointers"];
  45194. if (pointers) {
  45195. pointers.pinchPrecision = value;
  45196. }
  45197. },
  45198. enumerable: true,
  45199. configurable: true
  45200. });
  45201. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  45202. get: function () {
  45203. var pointers = this.inputs.attached["pointers"];
  45204. if (pointers)
  45205. return pointers.pinchDeltaPercentage;
  45206. return 0;
  45207. },
  45208. set: function (value) {
  45209. var pointers = this.inputs.attached["pointers"];
  45210. if (pointers) {
  45211. pointers.pinchDeltaPercentage = value;
  45212. }
  45213. },
  45214. enumerable: true,
  45215. configurable: true
  45216. });
  45217. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  45218. get: function () {
  45219. var pointers = this.inputs.attached["pointers"];
  45220. if (pointers)
  45221. return pointers.panningSensibility;
  45222. return 0;
  45223. },
  45224. set: function (value) {
  45225. var pointers = this.inputs.attached["pointers"];
  45226. if (pointers) {
  45227. pointers.panningSensibility = value;
  45228. }
  45229. },
  45230. enumerable: true,
  45231. configurable: true
  45232. });
  45233. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  45234. get: function () {
  45235. var keyboard = this.inputs.attached["keyboard"];
  45236. if (keyboard)
  45237. return keyboard.keysUp;
  45238. return [];
  45239. },
  45240. set: function (value) {
  45241. var keyboard = this.inputs.attached["keyboard"];
  45242. if (keyboard)
  45243. keyboard.keysUp = value;
  45244. },
  45245. enumerable: true,
  45246. configurable: true
  45247. });
  45248. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  45249. get: function () {
  45250. var keyboard = this.inputs.attached["keyboard"];
  45251. if (keyboard)
  45252. return keyboard.keysDown;
  45253. return [];
  45254. },
  45255. set: function (value) {
  45256. var keyboard = this.inputs.attached["keyboard"];
  45257. if (keyboard)
  45258. keyboard.keysDown = value;
  45259. },
  45260. enumerable: true,
  45261. configurable: true
  45262. });
  45263. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  45264. get: function () {
  45265. var keyboard = this.inputs.attached["keyboard"];
  45266. if (keyboard)
  45267. return keyboard.keysLeft;
  45268. return [];
  45269. },
  45270. set: function (value) {
  45271. var keyboard = this.inputs.attached["keyboard"];
  45272. if (keyboard)
  45273. keyboard.keysLeft = value;
  45274. },
  45275. enumerable: true,
  45276. configurable: true
  45277. });
  45278. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  45279. get: function () {
  45280. var keyboard = this.inputs.attached["keyboard"];
  45281. if (keyboard)
  45282. return keyboard.keysRight;
  45283. return [];
  45284. },
  45285. set: function (value) {
  45286. var keyboard = this.inputs.attached["keyboard"];
  45287. if (keyboard)
  45288. keyboard.keysRight = value;
  45289. },
  45290. enumerable: true,
  45291. configurable: true
  45292. });
  45293. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  45294. get: function () {
  45295. var mousewheel = this.inputs.attached["mousewheel"];
  45296. if (mousewheel)
  45297. return mousewheel.wheelPrecision;
  45298. return 0;
  45299. },
  45300. set: function (value) {
  45301. var mousewheel = this.inputs.attached["mousewheel"];
  45302. if (mousewheel)
  45303. mousewheel.wheelPrecision = value;
  45304. },
  45305. enumerable: true,
  45306. configurable: true
  45307. });
  45308. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  45309. get: function () {
  45310. var mousewheel = this.inputs.attached["mousewheel"];
  45311. if (mousewheel)
  45312. return mousewheel.wheelDeltaPercentage;
  45313. return 0;
  45314. },
  45315. set: function (value) {
  45316. var mousewheel = this.inputs.attached["mousewheel"];
  45317. if (mousewheel)
  45318. mousewheel.wheelDeltaPercentage = value;
  45319. },
  45320. enumerable: true,
  45321. configurable: true
  45322. });
  45323. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  45324. get: function () {
  45325. return this._bouncingBehavior;
  45326. },
  45327. enumerable: true,
  45328. configurable: true
  45329. });
  45330. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  45331. get: function () {
  45332. return this._bouncingBehavior != null;
  45333. },
  45334. set: function (value) {
  45335. if (value === this.useBouncingBehavior) {
  45336. return;
  45337. }
  45338. if (value) {
  45339. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  45340. this.addBehavior(this._bouncingBehavior);
  45341. }
  45342. else if (this._bouncingBehavior) {
  45343. this.removeBehavior(this._bouncingBehavior);
  45344. this._bouncingBehavior = null;
  45345. }
  45346. },
  45347. enumerable: true,
  45348. configurable: true
  45349. });
  45350. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  45351. get: function () {
  45352. return this._framingBehavior;
  45353. },
  45354. enumerable: true,
  45355. configurable: true
  45356. });
  45357. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  45358. get: function () {
  45359. return this._framingBehavior != null;
  45360. },
  45361. set: function (value) {
  45362. if (value === this.useFramingBehavior) {
  45363. return;
  45364. }
  45365. if (value) {
  45366. this._framingBehavior = new BABYLON.FramingBehavior();
  45367. this.addBehavior(this._framingBehavior);
  45368. }
  45369. else if (this._framingBehavior) {
  45370. this.removeBehavior(this._framingBehavior);
  45371. this._framingBehavior = null;
  45372. }
  45373. },
  45374. enumerable: true,
  45375. configurable: true
  45376. });
  45377. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  45378. get: function () {
  45379. return this._autoRotationBehavior;
  45380. },
  45381. enumerable: true,
  45382. configurable: true
  45383. });
  45384. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  45385. get: function () {
  45386. return this._autoRotationBehavior != null;
  45387. },
  45388. set: function (value) {
  45389. if (value === this.useAutoRotationBehavior) {
  45390. return;
  45391. }
  45392. if (value) {
  45393. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  45394. this.addBehavior(this._autoRotationBehavior);
  45395. }
  45396. else if (this._autoRotationBehavior) {
  45397. this.removeBehavior(this._autoRotationBehavior);
  45398. this._autoRotationBehavior = null;
  45399. }
  45400. },
  45401. enumerable: true,
  45402. configurable: true
  45403. });
  45404. // Cache
  45405. ArcRotateCamera.prototype._initCache = function () {
  45406. _super.prototype._initCache.call(this);
  45407. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45408. this._cache.alpha = undefined;
  45409. this._cache.beta = undefined;
  45410. this._cache.radius = undefined;
  45411. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  45412. };
  45413. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  45414. if (!ignoreParentClass) {
  45415. _super.prototype._updateCache.call(this);
  45416. }
  45417. this._cache._target.copyFrom(this._getTargetPosition());
  45418. this._cache.alpha = this.alpha;
  45419. this._cache.beta = this.beta;
  45420. this._cache.radius = this.radius;
  45421. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  45422. };
  45423. ArcRotateCamera.prototype._getTargetPosition = function () {
  45424. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  45425. var pos = this._targetHost.getAbsolutePosition();
  45426. if (this._targetBoundingCenter) {
  45427. pos.addToRef(this._targetBoundingCenter, this._target);
  45428. }
  45429. else {
  45430. this._target.copyFrom(pos);
  45431. }
  45432. }
  45433. var lockedTargetPosition = this._getLockedTargetPosition();
  45434. if (lockedTargetPosition) {
  45435. return lockedTargetPosition;
  45436. }
  45437. return this._target;
  45438. };
  45439. ArcRotateCamera.prototype.storeState = function () {
  45440. this._storedAlpha = this.alpha;
  45441. this._storedBeta = this.beta;
  45442. this._storedRadius = this.radius;
  45443. this._storedTarget = this._getTargetPosition().clone();
  45444. return _super.prototype.storeState.call(this);
  45445. };
  45446. /**
  45447. * Restored camera state. You must call storeState() first
  45448. */
  45449. ArcRotateCamera.prototype._restoreStateValues = function () {
  45450. if (!_super.prototype._restoreStateValues.call(this)) {
  45451. return false;
  45452. }
  45453. this.alpha = this._storedAlpha;
  45454. this.beta = this._storedBeta;
  45455. this.radius = this._storedRadius;
  45456. this.setTarget(this._storedTarget.clone());
  45457. this.inertialAlphaOffset = 0;
  45458. this.inertialBetaOffset = 0;
  45459. this.inertialRadiusOffset = 0;
  45460. this.inertialPanningX = 0;
  45461. this.inertialPanningY = 0;
  45462. return true;
  45463. };
  45464. // Synchronized
  45465. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  45466. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  45467. return false;
  45468. return this._cache._target.equals(this._getTargetPosition())
  45469. && this._cache.alpha === this.alpha
  45470. && this._cache.beta === this.beta
  45471. && this._cache.radius === this.radius
  45472. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  45473. };
  45474. // Methods
  45475. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  45476. var _this = this;
  45477. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  45478. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  45479. this._useCtrlForPanning = useCtrlForPanning;
  45480. this._panningMouseButton = panningMouseButton;
  45481. this.inputs.attachElement(element, noPreventDefault);
  45482. this._reset = function () {
  45483. _this.inertialAlphaOffset = 0;
  45484. _this.inertialBetaOffset = 0;
  45485. _this.inertialRadiusOffset = 0;
  45486. _this.inertialPanningX = 0;
  45487. _this.inertialPanningY = 0;
  45488. };
  45489. };
  45490. ArcRotateCamera.prototype.detachControl = function (element) {
  45491. this.inputs.detachElement(element);
  45492. if (this._reset) {
  45493. this._reset();
  45494. }
  45495. };
  45496. ArcRotateCamera.prototype._checkInputs = function () {
  45497. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  45498. if (this._collisionTriggered) {
  45499. return;
  45500. }
  45501. this.inputs.checkInputs();
  45502. // Inertia
  45503. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  45504. if (this.getScene().useRightHandedSystem) {
  45505. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45506. }
  45507. else {
  45508. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45509. }
  45510. this.beta += this.inertialBetaOffset;
  45511. this.radius -= this.inertialRadiusOffset;
  45512. this.inertialAlphaOffset *= this.inertia;
  45513. this.inertialBetaOffset *= this.inertia;
  45514. this.inertialRadiusOffset *= this.inertia;
  45515. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  45516. this.inertialAlphaOffset = 0;
  45517. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  45518. this.inertialBetaOffset = 0;
  45519. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  45520. this.inertialRadiusOffset = 0;
  45521. }
  45522. // Panning inertia
  45523. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  45524. if (!this._localDirection) {
  45525. this._localDirection = BABYLON.Vector3.Zero();
  45526. this._transformedDirection = BABYLON.Vector3.Zero();
  45527. }
  45528. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  45529. this._localDirection.multiplyInPlace(this.panningAxis);
  45530. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  45531. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  45532. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  45533. if (!this.panningAxis.y) {
  45534. this._transformedDirection.y = 0;
  45535. }
  45536. if (!this._targetHost) {
  45537. if (this.panningDistanceLimit) {
  45538. this._transformedDirection.addInPlace(this._target);
  45539. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  45540. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  45541. this._target.copyFrom(this._transformedDirection);
  45542. }
  45543. }
  45544. else {
  45545. this._target.addInPlace(this._transformedDirection);
  45546. }
  45547. }
  45548. this.inertialPanningX *= this.panningInertia;
  45549. this.inertialPanningY *= this.panningInertia;
  45550. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  45551. this.inertialPanningX = 0;
  45552. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  45553. this.inertialPanningY = 0;
  45554. }
  45555. // Limits
  45556. this._checkLimits();
  45557. _super.prototype._checkInputs.call(this);
  45558. };
  45559. ArcRotateCamera.prototype._checkLimits = function () {
  45560. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  45561. if (this.allowUpsideDown && this.beta > Math.PI) {
  45562. this.beta = this.beta - (2 * Math.PI);
  45563. }
  45564. }
  45565. else {
  45566. if (this.beta < this.lowerBetaLimit) {
  45567. this.beta = this.lowerBetaLimit;
  45568. }
  45569. }
  45570. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  45571. if (this.allowUpsideDown && this.beta < -Math.PI) {
  45572. this.beta = this.beta + (2 * Math.PI);
  45573. }
  45574. }
  45575. else {
  45576. if (this.beta > this.upperBetaLimit) {
  45577. this.beta = this.upperBetaLimit;
  45578. }
  45579. }
  45580. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  45581. this.alpha = this.lowerAlphaLimit;
  45582. }
  45583. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  45584. this.alpha = this.upperAlphaLimit;
  45585. }
  45586. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  45587. this.radius = this.lowerRadiusLimit;
  45588. }
  45589. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  45590. this.radius = this.upperRadiusLimit;
  45591. }
  45592. };
  45593. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  45594. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  45595. this.radius = this._computationVector.length();
  45596. if (this.radius === 0) {
  45597. this.radius = 0.0001; // Just to avoid division by zero
  45598. }
  45599. // Alpha
  45600. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  45601. if (this._computationVector.z < 0) {
  45602. this.alpha = 2 * Math.PI - this.alpha;
  45603. }
  45604. // Beta
  45605. this.beta = Math.acos(this._computationVector.y / this.radius);
  45606. this._checkLimits();
  45607. };
  45608. ArcRotateCamera.prototype.setPosition = function (position) {
  45609. if (this.position.equals(position)) {
  45610. return;
  45611. }
  45612. this.position.copyFrom(position);
  45613. this.rebuildAnglesAndRadius();
  45614. };
  45615. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  45616. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  45617. if (allowSamePosition === void 0) { allowSamePosition = false; }
  45618. if (target.getBoundingInfo) {
  45619. if (toBoundingCenter) {
  45620. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  45621. }
  45622. else {
  45623. this._targetBoundingCenter = null;
  45624. }
  45625. this._targetHost = target;
  45626. this._target = this._getTargetPosition();
  45627. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  45628. }
  45629. else {
  45630. var newTarget = target;
  45631. var currentTarget = this._getTargetPosition();
  45632. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  45633. return;
  45634. }
  45635. this._targetHost = null;
  45636. this._target = newTarget;
  45637. this._targetBoundingCenter = null;
  45638. this.onMeshTargetChangedObservable.notifyObservers(null);
  45639. }
  45640. this.rebuildAnglesAndRadius();
  45641. };
  45642. ArcRotateCamera.prototype._getViewMatrix = function () {
  45643. // Compute
  45644. var cosa = Math.cos(this.alpha);
  45645. var sina = Math.sin(this.alpha);
  45646. var cosb = Math.cos(this.beta);
  45647. var sinb = Math.sin(this.beta);
  45648. if (sinb === 0) {
  45649. sinb = 0.0001;
  45650. }
  45651. var target = this._getTargetPosition();
  45652. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  45653. target.addToRef(this._computationVector, this._newPosition);
  45654. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  45655. if (!this._collider) {
  45656. this._collider = new BABYLON.Collider();
  45657. }
  45658. this._collider._radius = this.collisionRadius;
  45659. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  45660. this._collisionTriggered = true;
  45661. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  45662. }
  45663. else {
  45664. this.position.copyFrom(this._newPosition);
  45665. var up = this.upVector;
  45666. if (this.allowUpsideDown && sinb < 0) {
  45667. up = up.clone();
  45668. up = up.negate();
  45669. }
  45670. if (this.getScene().useRightHandedSystem) {
  45671. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  45672. }
  45673. else {
  45674. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  45675. }
  45676. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  45677. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  45678. }
  45679. this._currentTarget = target;
  45680. return this._viewMatrix;
  45681. };
  45682. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  45683. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45684. meshes = meshes || this.getScene().meshes;
  45685. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  45686. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  45687. this.radius = distance * this.zoomOnFactor;
  45688. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  45689. };
  45690. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  45691. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45692. var meshesOrMinMaxVector;
  45693. var distance;
  45694. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  45695. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  45696. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  45697. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  45698. }
  45699. else {
  45700. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  45701. meshesOrMinMaxVector = minMaxVectorAndDistance;
  45702. distance = minMaxVectorAndDistance.distance;
  45703. }
  45704. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  45705. if (!doNotUpdateMaxZ) {
  45706. this.maxZ = distance * 2;
  45707. }
  45708. };
  45709. /**
  45710. * @override
  45711. * Override Camera.createRigCamera
  45712. */
  45713. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45714. var alphaShift = 0;
  45715. switch (this.cameraRigMode) {
  45716. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45717. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45718. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45719. case BABYLON.Camera.RIG_MODE_VR:
  45720. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  45721. break;
  45722. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45723. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  45724. break;
  45725. }
  45726. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  45727. rigCam._cameraRigParams = {};
  45728. return rigCam;
  45729. };
  45730. /**
  45731. * @override
  45732. * Override Camera._updateRigCameras
  45733. */
  45734. ArcRotateCamera.prototype._updateRigCameras = function () {
  45735. var camLeft = this._rigCameras[0];
  45736. var camRight = this._rigCameras[1];
  45737. camLeft.beta = camRight.beta = this.beta;
  45738. camLeft.radius = camRight.radius = this.radius;
  45739. switch (this.cameraRigMode) {
  45740. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45741. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45742. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45743. case BABYLON.Camera.RIG_MODE_VR:
  45744. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45745. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45746. break;
  45747. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45748. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45749. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45750. break;
  45751. }
  45752. _super.prototype._updateRigCameras.call(this);
  45753. };
  45754. ArcRotateCamera.prototype.dispose = function () {
  45755. this.inputs.clear();
  45756. _super.prototype.dispose.call(this);
  45757. };
  45758. ArcRotateCamera.prototype.getClassName = function () {
  45759. return "ArcRotateCamera";
  45760. };
  45761. __decorate([
  45762. BABYLON.serialize()
  45763. ], ArcRotateCamera.prototype, "alpha", void 0);
  45764. __decorate([
  45765. BABYLON.serialize()
  45766. ], ArcRotateCamera.prototype, "beta", void 0);
  45767. __decorate([
  45768. BABYLON.serialize()
  45769. ], ArcRotateCamera.prototype, "radius", void 0);
  45770. __decorate([
  45771. BABYLON.serializeAsVector3("target")
  45772. ], ArcRotateCamera.prototype, "_target", void 0);
  45773. __decorate([
  45774. BABYLON.serialize()
  45775. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45776. __decorate([
  45777. BABYLON.serialize()
  45778. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45779. __decorate([
  45780. BABYLON.serialize()
  45781. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45782. __decorate([
  45783. BABYLON.serialize()
  45784. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45785. __decorate([
  45786. BABYLON.serialize()
  45787. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45788. __decorate([
  45789. BABYLON.serialize()
  45790. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45791. __decorate([
  45792. BABYLON.serialize()
  45793. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45794. __decorate([
  45795. BABYLON.serialize()
  45796. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45797. __decorate([
  45798. BABYLON.serialize()
  45799. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45800. __decorate([
  45801. BABYLON.serialize()
  45802. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45803. __decorate([
  45804. BABYLON.serialize()
  45805. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45806. __decorate([
  45807. BABYLON.serialize()
  45808. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45809. __decorate([
  45810. BABYLON.serialize()
  45811. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45812. __decorate([
  45813. BABYLON.serializeAsVector3()
  45814. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45815. __decorate([
  45816. BABYLON.serialize()
  45817. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45818. __decorate([
  45819. BABYLON.serialize()
  45820. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45821. __decorate([
  45822. BABYLON.serialize()
  45823. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45824. return ArcRotateCamera;
  45825. }(BABYLON.TargetCamera));
  45826. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45827. })(BABYLON || (BABYLON = {}));
  45828. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45829. "use strict";
  45830. var BABYLON;
  45831. (function (BABYLON) {
  45832. /**
  45833. * The HemisphericLight simulates the ambient environment light,
  45834. * so the passed direction is the light reflection direction, not the incoming direction.
  45835. */
  45836. var HemisphericLight = /** @class */ (function (_super) {
  45837. __extends(HemisphericLight, _super);
  45838. /**
  45839. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45840. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45841. * The HemisphericLight can't cast shadows.
  45842. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45843. * @param name The friendly name of the light
  45844. * @param direction The direction of the light reflection
  45845. * @param scene The scene the light belongs to
  45846. */
  45847. function HemisphericLight(name, direction, scene) {
  45848. var _this = _super.call(this, name, scene) || this;
  45849. /**
  45850. * The groundColor is the light in the opposite direction to the one specified during creation.
  45851. * 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.
  45852. */
  45853. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45854. _this.direction = direction || BABYLON.Vector3.Up();
  45855. return _this;
  45856. }
  45857. HemisphericLight.prototype._buildUniformLayout = function () {
  45858. this._uniformBuffer.addUniform("vLightData", 4);
  45859. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45860. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45861. this._uniformBuffer.addUniform("vLightGround", 3);
  45862. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45863. this._uniformBuffer.addUniform("depthValues", 2);
  45864. this._uniformBuffer.create();
  45865. };
  45866. /**
  45867. * Returns the string "HemisphericLight".
  45868. * @return The class name
  45869. */
  45870. HemisphericLight.prototype.getClassName = function () {
  45871. return "HemisphericLight";
  45872. };
  45873. /**
  45874. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45875. * Returns the updated direction.
  45876. * @param target The target the direction should point to
  45877. * @return The computed direction
  45878. */
  45879. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45880. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45881. return this.direction;
  45882. };
  45883. /**
  45884. * Returns the shadow generator associated to the light.
  45885. * @returns Always null for hemispheric lights because it does not support shadows.
  45886. */
  45887. HemisphericLight.prototype.getShadowGenerator = function () {
  45888. return null;
  45889. };
  45890. /**
  45891. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45892. * @param effect The effect to update
  45893. * @param lightIndex The index of the light in the effect to update
  45894. * @returns The hemispheric light
  45895. */
  45896. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45897. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45898. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45899. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45900. return this;
  45901. };
  45902. /**
  45903. * @ignore internal use only.
  45904. */
  45905. HemisphericLight.prototype._getWorldMatrix = function () {
  45906. if (!this._worldMatrix) {
  45907. this._worldMatrix = BABYLON.Matrix.Identity();
  45908. }
  45909. return this._worldMatrix;
  45910. };
  45911. /**
  45912. * Returns the integer 3.
  45913. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45914. */
  45915. HemisphericLight.prototype.getTypeID = function () {
  45916. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45917. };
  45918. __decorate([
  45919. BABYLON.serializeAsColor3()
  45920. ], HemisphericLight.prototype, "groundColor", void 0);
  45921. __decorate([
  45922. BABYLON.serializeAsVector3()
  45923. ], HemisphericLight.prototype, "direction", void 0);
  45924. return HemisphericLight;
  45925. }(BABYLON.Light));
  45926. BABYLON.HemisphericLight = HemisphericLight;
  45927. })(BABYLON || (BABYLON = {}));
  45928. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45929. "use strict";
  45930. var BABYLON;
  45931. (function (BABYLON) {
  45932. /**
  45933. * Base implementation of @see IShadowLight
  45934. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45935. */
  45936. var ShadowLight = /** @class */ (function (_super) {
  45937. __extends(ShadowLight, _super);
  45938. function ShadowLight() {
  45939. var _this = _super !== null && _super.apply(this, arguments) || this;
  45940. _this._needProjectionMatrixCompute = true;
  45941. return _this;
  45942. }
  45943. ShadowLight.prototype._setPosition = function (value) {
  45944. this._position = value;
  45945. };
  45946. Object.defineProperty(ShadowLight.prototype, "position", {
  45947. /**
  45948. * Sets the position the shadow will be casted from. Also use as the light position for both
  45949. * point and spot lights.
  45950. */
  45951. get: function () {
  45952. return this._position;
  45953. },
  45954. /**
  45955. * Sets the position the shadow will be casted from. Also use as the light position for both
  45956. * point and spot lights.
  45957. */
  45958. set: function (value) {
  45959. this._setPosition(value);
  45960. },
  45961. enumerable: true,
  45962. configurable: true
  45963. });
  45964. ShadowLight.prototype._setDirection = function (value) {
  45965. this._direction = value;
  45966. };
  45967. Object.defineProperty(ShadowLight.prototype, "direction", {
  45968. /**
  45969. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45970. * Also use as the light direction on spot and directional lights.
  45971. */
  45972. get: function () {
  45973. return this._direction;
  45974. },
  45975. /**
  45976. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45977. * Also use as the light direction on spot and directional lights.
  45978. */
  45979. set: function (value) {
  45980. this._setDirection(value);
  45981. },
  45982. enumerable: true,
  45983. configurable: true
  45984. });
  45985. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45986. /**
  45987. * Gets the shadow projection clipping minimum z value.
  45988. */
  45989. get: function () {
  45990. return this._shadowMinZ;
  45991. },
  45992. /**
  45993. * Sets the shadow projection clipping minimum z value.
  45994. */
  45995. set: function (value) {
  45996. this._shadowMinZ = value;
  45997. this.forceProjectionMatrixCompute();
  45998. },
  45999. enumerable: true,
  46000. configurable: true
  46001. });
  46002. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  46003. /**
  46004. * Sets the shadow projection clipping maximum z value.
  46005. */
  46006. get: function () {
  46007. return this._shadowMaxZ;
  46008. },
  46009. /**
  46010. * Gets the shadow projection clipping maximum z value.
  46011. */
  46012. set: function (value) {
  46013. this._shadowMaxZ = value;
  46014. this.forceProjectionMatrixCompute();
  46015. },
  46016. enumerable: true,
  46017. configurable: true
  46018. });
  46019. /**
  46020. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  46021. * @returns true if the information has been computed, false if it does not need to (no parenting)
  46022. */
  46023. ShadowLight.prototype.computeTransformedInformation = function () {
  46024. if (this.parent && this.parent.getWorldMatrix) {
  46025. if (!this.transformedPosition) {
  46026. this.transformedPosition = BABYLON.Vector3.Zero();
  46027. }
  46028. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  46029. // In case the direction is present.
  46030. if (this.direction) {
  46031. if (!this.transformedDirection) {
  46032. this.transformedDirection = BABYLON.Vector3.Zero();
  46033. }
  46034. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  46035. }
  46036. return true;
  46037. }
  46038. return false;
  46039. };
  46040. /**
  46041. * Return the depth scale used for the shadow map.
  46042. * @returns the depth scale.
  46043. */
  46044. ShadowLight.prototype.getDepthScale = function () {
  46045. return 50.0;
  46046. };
  46047. /**
  46048. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  46049. * @param faceIndex The index of the face we are computed the direction to generate shadow
  46050. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  46051. */
  46052. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  46053. return this.transformedDirection ? this.transformedDirection : this.direction;
  46054. };
  46055. /**
  46056. * Returns the ShadowLight absolute position in the World.
  46057. * @returns the position vector in world space
  46058. */
  46059. ShadowLight.prototype.getAbsolutePosition = function () {
  46060. return this.transformedPosition ? this.transformedPosition : this.position;
  46061. };
  46062. /**
  46063. * Sets the ShadowLight direction toward the passed target.
  46064. * @param target The point tot target in local space
  46065. * @returns the updated ShadowLight direction
  46066. */
  46067. ShadowLight.prototype.setDirectionToTarget = function (target) {
  46068. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  46069. return this.direction;
  46070. };
  46071. /**
  46072. * Returns the light rotation in euler definition.
  46073. * @returns the x y z rotation in local space.
  46074. */
  46075. ShadowLight.prototype.getRotation = function () {
  46076. this.direction.normalize();
  46077. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  46078. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  46079. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  46080. };
  46081. /**
  46082. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  46083. * @returns true if a cube texture needs to be use
  46084. */
  46085. ShadowLight.prototype.needCube = function () {
  46086. return false;
  46087. };
  46088. /**
  46089. * Detects if the projection matrix requires to be recomputed this frame.
  46090. * @returns true if it requires to be recomputed otherwise, false.
  46091. */
  46092. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  46093. return this._needProjectionMatrixCompute;
  46094. };
  46095. /**
  46096. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  46097. */
  46098. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  46099. this._needProjectionMatrixCompute = true;
  46100. };
  46101. /**
  46102. * Get the world matrix of the sahdow lights.
  46103. * @ignore Internal Use Only
  46104. */
  46105. ShadowLight.prototype._getWorldMatrix = function () {
  46106. if (!this._worldMatrix) {
  46107. this._worldMatrix = BABYLON.Matrix.Identity();
  46108. }
  46109. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  46110. return this._worldMatrix;
  46111. };
  46112. /**
  46113. * Gets the minZ used for shadow according to both the scene and the light.
  46114. * @param activeCamera The camera we are returning the min for
  46115. * @returns the depth min z
  46116. */
  46117. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  46118. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  46119. };
  46120. /**
  46121. * Gets the maxZ used for shadow according to both the scene and the light.
  46122. * @param activeCamera The camera we are returning the max for
  46123. * @returns the depth max z
  46124. */
  46125. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  46126. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  46127. };
  46128. /**
  46129. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  46130. * @param matrix The materix to updated with the projection information
  46131. * @param viewMatrix The transform matrix of the light
  46132. * @param renderList The list of mesh to render in the map
  46133. * @returns The current light
  46134. */
  46135. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46136. if (this.customProjectionMatrixBuilder) {
  46137. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  46138. }
  46139. else {
  46140. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46141. }
  46142. return this;
  46143. };
  46144. __decorate([
  46145. BABYLON.serializeAsVector3()
  46146. ], ShadowLight.prototype, "position", null);
  46147. __decorate([
  46148. BABYLON.serializeAsVector3()
  46149. ], ShadowLight.prototype, "direction", null);
  46150. __decorate([
  46151. BABYLON.serialize()
  46152. ], ShadowLight.prototype, "shadowMinZ", null);
  46153. __decorate([
  46154. BABYLON.serialize()
  46155. ], ShadowLight.prototype, "shadowMaxZ", null);
  46156. return ShadowLight;
  46157. }(BABYLON.Light));
  46158. BABYLON.ShadowLight = ShadowLight;
  46159. })(BABYLON || (BABYLON = {}));
  46160. //# sourceMappingURL=babylon.shadowLight.js.map
  46161. "use strict";
  46162. var BABYLON;
  46163. (function (BABYLON) {
  46164. /**
  46165. * A point light is a light defined by an unique point in world space.
  46166. * The light is emitted in every direction from this point.
  46167. * A good example of a point light is a standard light bulb.
  46168. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46169. */
  46170. var PointLight = /** @class */ (function (_super) {
  46171. __extends(PointLight, _super);
  46172. /**
  46173. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  46174. * A PointLight emits the light in every direction.
  46175. * It can cast shadows.
  46176. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  46177. * ```javascript
  46178. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  46179. * ```
  46180. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46181. * @param name The light friendly name
  46182. * @param position The position of the point light in the scene
  46183. * @param scene The scene the lights belongs to
  46184. */
  46185. function PointLight(name, position, scene) {
  46186. var _this = _super.call(this, name, scene) || this;
  46187. _this._shadowAngle = Math.PI / 2;
  46188. _this.position = position;
  46189. return _this;
  46190. }
  46191. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  46192. /**
  46193. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46194. * This specifies what angle the shadow will use to be created.
  46195. *
  46196. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46197. */
  46198. get: function () {
  46199. return this._shadowAngle;
  46200. },
  46201. /**
  46202. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46203. * This specifies what angle the shadow will use to be created.
  46204. *
  46205. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46206. */
  46207. set: function (value) {
  46208. this._shadowAngle = value;
  46209. this.forceProjectionMatrixCompute();
  46210. },
  46211. enumerable: true,
  46212. configurable: true
  46213. });
  46214. Object.defineProperty(PointLight.prototype, "direction", {
  46215. /**
  46216. * Gets the direction if it has been set.
  46217. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46218. */
  46219. get: function () {
  46220. return this._direction;
  46221. },
  46222. /**
  46223. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46224. */
  46225. set: function (value) {
  46226. var previousNeedCube = this.needCube();
  46227. this._direction = value;
  46228. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  46229. this._shadowGenerator.recreateShadowMap();
  46230. }
  46231. },
  46232. enumerable: true,
  46233. configurable: true
  46234. });
  46235. /**
  46236. * Returns the string "PointLight"
  46237. * @returns the class name
  46238. */
  46239. PointLight.prototype.getClassName = function () {
  46240. return "PointLight";
  46241. };
  46242. /**
  46243. * Returns the integer 0.
  46244. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46245. */
  46246. PointLight.prototype.getTypeID = function () {
  46247. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  46248. };
  46249. /**
  46250. * Specifies wether or not the shadowmap should be a cube texture.
  46251. * @returns true if the shadowmap needs to be a cube texture.
  46252. */
  46253. PointLight.prototype.needCube = function () {
  46254. return !this.direction;
  46255. };
  46256. /**
  46257. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  46258. * @param faceIndex The index of the face we are computed the direction to generate shadow
  46259. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  46260. */
  46261. PointLight.prototype.getShadowDirection = function (faceIndex) {
  46262. if (this.direction) {
  46263. return _super.prototype.getShadowDirection.call(this, faceIndex);
  46264. }
  46265. else {
  46266. switch (faceIndex) {
  46267. case 0:
  46268. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  46269. case 1:
  46270. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  46271. case 2:
  46272. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  46273. case 3:
  46274. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  46275. case 4:
  46276. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  46277. case 5:
  46278. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  46279. }
  46280. }
  46281. return BABYLON.Vector3.Zero();
  46282. };
  46283. /**
  46284. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  46285. * - fov = PI / 2
  46286. * - aspect ratio : 1.0
  46287. * - z-near and far equal to the active camera minZ and maxZ.
  46288. * Returns the PointLight.
  46289. */
  46290. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46291. var activeCamera = this.getScene().activeCamera;
  46292. if (!activeCamera) {
  46293. return;
  46294. }
  46295. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46296. };
  46297. PointLight.prototype._buildUniformLayout = function () {
  46298. this._uniformBuffer.addUniform("vLightData", 4);
  46299. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46300. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46301. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46302. this._uniformBuffer.addUniform("depthValues", 2);
  46303. this._uniformBuffer.create();
  46304. };
  46305. /**
  46306. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  46307. * @param effect The effect to update
  46308. * @param lightIndex The index of the light in the effect to update
  46309. * @returns The point light
  46310. */
  46311. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  46312. if (this.computeTransformedInformation()) {
  46313. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  46314. return this;
  46315. }
  46316. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  46317. return this;
  46318. };
  46319. __decorate([
  46320. BABYLON.serialize()
  46321. ], PointLight.prototype, "shadowAngle", null);
  46322. return PointLight;
  46323. }(BABYLON.ShadowLight));
  46324. BABYLON.PointLight = PointLight;
  46325. })(BABYLON || (BABYLON = {}));
  46326. //# sourceMappingURL=babylon.pointLight.js.map
  46327. "use strict";
  46328. var BABYLON;
  46329. (function (BABYLON) {
  46330. /**
  46331. * A directional light is defined by a direction (what a surprise!).
  46332. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  46333. * 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.
  46334. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46335. */
  46336. var DirectionalLight = /** @class */ (function (_super) {
  46337. __extends(DirectionalLight, _super);
  46338. /**
  46339. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  46340. * The directional light is emitted from everywhere in the given direction.
  46341. * It can cast shawdows.
  46342. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46343. * @param name The friendly name of the light
  46344. * @param direction The direction of the light
  46345. * @param scene The scene the light belongs to
  46346. */
  46347. function DirectionalLight(name, direction, scene) {
  46348. var _this = _super.call(this, name, scene) || this;
  46349. _this._shadowFrustumSize = 0;
  46350. _this._shadowOrthoScale = 0.1;
  46351. /**
  46352. * Automatically compute the projection matrix to best fit (including all the casters)
  46353. * on each frame.
  46354. */
  46355. _this.autoUpdateExtends = true;
  46356. // Cache
  46357. _this._orthoLeft = Number.MAX_VALUE;
  46358. _this._orthoRight = Number.MIN_VALUE;
  46359. _this._orthoTop = Number.MIN_VALUE;
  46360. _this._orthoBottom = Number.MAX_VALUE;
  46361. _this.position = direction.scale(-1.0);
  46362. _this.direction = direction;
  46363. return _this;
  46364. }
  46365. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  46366. /**
  46367. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  46368. */
  46369. get: function () {
  46370. return this._shadowFrustumSize;
  46371. },
  46372. /**
  46373. * Specifies a fix frustum size for the shadow generation.
  46374. */
  46375. set: function (value) {
  46376. this._shadowFrustumSize = value;
  46377. this.forceProjectionMatrixCompute();
  46378. },
  46379. enumerable: true,
  46380. configurable: true
  46381. });
  46382. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  46383. /**
  46384. * Gets the shadow projection scale against the optimal computed one.
  46385. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46386. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46387. */
  46388. get: function () {
  46389. return this._shadowOrthoScale;
  46390. },
  46391. /**
  46392. * Sets the shadow projection scale against the optimal computed one.
  46393. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46394. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46395. */
  46396. set: function (value) {
  46397. this._shadowOrthoScale = value;
  46398. this.forceProjectionMatrixCompute();
  46399. },
  46400. enumerable: true,
  46401. configurable: true
  46402. });
  46403. /**
  46404. * Returns the string "DirectionalLight".
  46405. * @return The class name
  46406. */
  46407. DirectionalLight.prototype.getClassName = function () {
  46408. return "DirectionalLight";
  46409. };
  46410. /**
  46411. * Returns the integer 1.
  46412. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46413. */
  46414. DirectionalLight.prototype.getTypeID = function () {
  46415. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  46416. };
  46417. /**
  46418. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  46419. * Returns the DirectionalLight Shadow projection matrix.
  46420. */
  46421. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46422. if (this.shadowFrustumSize > 0) {
  46423. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  46424. }
  46425. else {
  46426. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46427. }
  46428. };
  46429. /**
  46430. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  46431. * Returns the DirectionalLight Shadow projection matrix.
  46432. */
  46433. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  46434. var activeCamera = this.getScene().activeCamera;
  46435. if (!activeCamera) {
  46436. return;
  46437. }
  46438. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  46439. };
  46440. /**
  46441. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  46442. * Returns the DirectionalLight Shadow projection matrix.
  46443. */
  46444. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46445. var activeCamera = this.getScene().activeCamera;
  46446. if (!activeCamera) {
  46447. return;
  46448. }
  46449. // Check extends
  46450. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  46451. var tempVector3 = BABYLON.Vector3.Zero();
  46452. this._orthoLeft = Number.MAX_VALUE;
  46453. this._orthoRight = Number.MIN_VALUE;
  46454. this._orthoTop = Number.MIN_VALUE;
  46455. this._orthoBottom = Number.MAX_VALUE;
  46456. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  46457. var mesh = renderList[meshIndex];
  46458. if (!mesh) {
  46459. continue;
  46460. }
  46461. var boundingInfo = mesh.getBoundingInfo();
  46462. var boundingBox = boundingInfo.boundingBox;
  46463. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  46464. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  46465. if (tempVector3.x < this._orthoLeft)
  46466. this._orthoLeft = tempVector3.x;
  46467. if (tempVector3.y < this._orthoBottom)
  46468. this._orthoBottom = tempVector3.y;
  46469. if (tempVector3.x > this._orthoRight)
  46470. this._orthoRight = tempVector3.x;
  46471. if (tempVector3.y > this._orthoTop)
  46472. this._orthoTop = tempVector3.y;
  46473. }
  46474. }
  46475. }
  46476. var xOffset = this._orthoRight - this._orthoLeft;
  46477. var yOffset = this._orthoTop - this._orthoBottom;
  46478. 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);
  46479. };
  46480. DirectionalLight.prototype._buildUniformLayout = function () {
  46481. this._uniformBuffer.addUniform("vLightData", 4);
  46482. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46483. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46484. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46485. this._uniformBuffer.addUniform("depthValues", 2);
  46486. this._uniformBuffer.create();
  46487. };
  46488. /**
  46489. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  46490. * @param effect The effect to update
  46491. * @param lightIndex The index of the light in the effect to update
  46492. * @returns The directional light
  46493. */
  46494. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  46495. if (this.computeTransformedInformation()) {
  46496. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  46497. return this;
  46498. }
  46499. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  46500. return this;
  46501. };
  46502. /**
  46503. * Gets the minZ used for shadow according to both the scene and the light.
  46504. *
  46505. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46506. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46507. * @param activeCamera The camera we are returning the min for
  46508. * @returns the depth min z
  46509. */
  46510. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  46511. return 1;
  46512. };
  46513. /**
  46514. * Gets the maxZ used for shadow according to both the scene and the light.
  46515. *
  46516. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46517. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46518. * @param activeCamera The camera we are returning the max for
  46519. * @returns the depth max z
  46520. */
  46521. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  46522. return 1;
  46523. };
  46524. __decorate([
  46525. BABYLON.serialize()
  46526. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  46527. __decorate([
  46528. BABYLON.serialize()
  46529. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  46530. __decorate([
  46531. BABYLON.serialize()
  46532. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  46533. return DirectionalLight;
  46534. }(BABYLON.ShadowLight));
  46535. BABYLON.DirectionalLight = DirectionalLight;
  46536. })(BABYLON || (BABYLON = {}));
  46537. //# sourceMappingURL=babylon.directionalLight.js.map
  46538. "use strict";
  46539. var BABYLON;
  46540. (function (BABYLON) {
  46541. /**
  46542. * A spot light is defined by a position, a direction, an angle, and an exponent.
  46543. * These values define a cone of light starting from the position, emitting toward the direction.
  46544. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  46545. * and the exponent defines the speed of the decay of the light with distance (reach).
  46546. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46547. */
  46548. var SpotLight = /** @class */ (function (_super) {
  46549. __extends(SpotLight, _super);
  46550. /**
  46551. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  46552. * It can cast shadows.
  46553. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46554. * @param name The light friendly name
  46555. * @param position The position of the spot light in the scene
  46556. * @param direction The direction of the light in the scene
  46557. * @param angle The cone angle of the light in Radians
  46558. * @param exponent The light decay speed with the distance from the emission spot
  46559. * @param scene The scene the lights belongs to
  46560. */
  46561. function SpotLight(name, position, direction, angle, exponent, scene) {
  46562. var _this = _super.call(this, name, scene) || this;
  46563. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  46564. _this._projectionTextureLightNear = 1e-6;
  46565. _this._projectionTextureLightFar = 1000.0;
  46566. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  46567. _this._projectionTextureViewLightDirty = true;
  46568. _this._projectionTextureProjectionLightDirty = true;
  46569. _this._projectionTextureDirty = true;
  46570. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  46571. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  46572. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  46573. _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);
  46574. _this.position = position;
  46575. _this.direction = direction;
  46576. _this.angle = angle;
  46577. _this.exponent = exponent;
  46578. return _this;
  46579. }
  46580. Object.defineProperty(SpotLight.prototype, "angle", {
  46581. /**
  46582. * Gets the cone angle of the spot light in Radians.
  46583. */
  46584. get: function () {
  46585. return this._angle;
  46586. },
  46587. /**
  46588. * Sets the cone angle of the spot light in Radians.
  46589. */
  46590. set: function (value) {
  46591. this._angle = value;
  46592. this._projectionTextureProjectionLightDirty = true;
  46593. this.forceProjectionMatrixCompute();
  46594. },
  46595. enumerable: true,
  46596. configurable: true
  46597. });
  46598. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  46599. /**
  46600. * Allows scaling the angle of the light for shadow generation only.
  46601. */
  46602. get: function () {
  46603. return this._shadowAngleScale;
  46604. },
  46605. /**
  46606. * Allows scaling the angle of the light for shadow generation only.
  46607. */
  46608. set: function (value) {
  46609. this._shadowAngleScale = value;
  46610. this.forceProjectionMatrixCompute();
  46611. },
  46612. enumerable: true,
  46613. configurable: true
  46614. });
  46615. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  46616. /**
  46617. * Allows reading the projecton texture
  46618. */
  46619. get: function () {
  46620. return this._projectionTextureMatrix;
  46621. },
  46622. enumerable: true,
  46623. configurable: true
  46624. });
  46625. ;
  46626. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  46627. /**
  46628. * Gets the near clip of the Spotlight for texture projection.
  46629. */
  46630. get: function () {
  46631. return this._projectionTextureLightNear;
  46632. },
  46633. /**
  46634. * Sets the near clip of the Spotlight for texture projection.
  46635. */
  46636. set: function (value) {
  46637. this._projectionTextureLightNear = value;
  46638. this._projectionTextureProjectionLightDirty = true;
  46639. },
  46640. enumerable: true,
  46641. configurable: true
  46642. });
  46643. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  46644. /**
  46645. * Gets the far clip of the Spotlight for texture projection.
  46646. */
  46647. get: function () {
  46648. return this._projectionTextureLightFar;
  46649. },
  46650. /**
  46651. * Sets the far clip of the Spotlight for texture projection.
  46652. */
  46653. set: function (value) {
  46654. this._projectionTextureLightFar = value;
  46655. this._projectionTextureProjectionLightDirty = true;
  46656. },
  46657. enumerable: true,
  46658. configurable: true
  46659. });
  46660. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  46661. /**
  46662. * Gets the Up vector of the Spotlight for texture projection.
  46663. */
  46664. get: function () {
  46665. return this._projectionTextureUpDirection;
  46666. },
  46667. /**
  46668. * Sets the Up vector of the Spotlight for texture projection.
  46669. */
  46670. set: function (value) {
  46671. this._projectionTextureUpDirection = value;
  46672. this._projectionTextureProjectionLightDirty = true;
  46673. },
  46674. enumerable: true,
  46675. configurable: true
  46676. });
  46677. ;
  46678. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  46679. /**
  46680. * Gets the projection texture of the light.
  46681. */
  46682. get: function () {
  46683. return this._projectionTexture;
  46684. },
  46685. /**
  46686. * Sets the projection texture of the light.
  46687. */
  46688. set: function (value) {
  46689. this._projectionTexture = value;
  46690. this._projectionTextureDirty = true;
  46691. },
  46692. enumerable: true,
  46693. configurable: true
  46694. });
  46695. /**
  46696. * Returns the string "SpotLight".
  46697. * @returns the class name
  46698. */
  46699. SpotLight.prototype.getClassName = function () {
  46700. return "SpotLight";
  46701. };
  46702. /**
  46703. * Returns the integer 2.
  46704. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46705. */
  46706. SpotLight.prototype.getTypeID = function () {
  46707. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  46708. };
  46709. /**
  46710. * Overrides the direction setter to recompute the projection texture view light Matrix.
  46711. */
  46712. SpotLight.prototype._setDirection = function (value) {
  46713. _super.prototype._setDirection.call(this, value);
  46714. this._projectionTextureViewLightDirty = true;
  46715. };
  46716. /**
  46717. * Overrides the position setter to recompute the projection texture view light Matrix.
  46718. */
  46719. SpotLight.prototype._setPosition = function (value) {
  46720. _super.prototype._setPosition.call(this, value);
  46721. this._projectionTextureViewLightDirty = true;
  46722. };
  46723. /**
  46724. * 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.
  46725. * Returns the SpotLight.
  46726. */
  46727. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46728. var activeCamera = this.getScene().activeCamera;
  46729. if (!activeCamera) {
  46730. return;
  46731. }
  46732. this._shadowAngleScale = this._shadowAngleScale || 1;
  46733. var angle = this._shadowAngleScale * this._angle;
  46734. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46735. };
  46736. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46737. this._projectionTextureViewLightDirty = false;
  46738. this._projectionTextureDirty = true;
  46739. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46740. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46741. };
  46742. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46743. this._projectionTextureProjectionLightDirty = false;
  46744. this._projectionTextureDirty = true;
  46745. var light_far = this.projectionTextureLightFar;
  46746. var light_near = this.projectionTextureLightNear;
  46747. var P = light_far / (light_far - light_near);
  46748. var Q = -P * light_near;
  46749. var S = 1.0 / Math.tan(this._angle / 2.0);
  46750. var A = 1.0;
  46751. 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);
  46752. };
  46753. /**
  46754. * Main function for light texture projection matrix computing.
  46755. */
  46756. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46757. this._projectionTextureDirty = false;
  46758. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46759. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46760. };
  46761. SpotLight.prototype._buildUniformLayout = function () {
  46762. this._uniformBuffer.addUniform("vLightData", 4);
  46763. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46764. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46765. this._uniformBuffer.addUniform("vLightDirection", 3);
  46766. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46767. this._uniformBuffer.addUniform("depthValues", 2);
  46768. this._uniformBuffer.create();
  46769. };
  46770. /**
  46771. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46772. * @param effect The effect to update
  46773. * @param lightIndex The index of the light in the effect to update
  46774. * @returns The spot light
  46775. */
  46776. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46777. var normalizeDirection;
  46778. if (this.computeTransformedInformation()) {
  46779. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46780. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46781. }
  46782. else {
  46783. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46784. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46785. }
  46786. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46787. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46788. if (this._projectionTextureViewLightDirty) {
  46789. this._computeProjectionTextureViewLightMatrix();
  46790. }
  46791. if (this._projectionTextureProjectionLightDirty) {
  46792. this._computeProjectionTextureProjectionLightMatrix();
  46793. }
  46794. if (this._projectionTextureDirty) {
  46795. this._computeProjectionTextureMatrix();
  46796. }
  46797. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46798. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46799. }
  46800. return this;
  46801. };
  46802. /**
  46803. * Disposes the light and the associated resources.
  46804. */
  46805. SpotLight.prototype.dispose = function () {
  46806. _super.prototype.dispose.call(this);
  46807. if (this._projectionTexture) {
  46808. this._projectionTexture.dispose();
  46809. }
  46810. };
  46811. __decorate([
  46812. BABYLON.serialize()
  46813. ], SpotLight.prototype, "angle", null);
  46814. __decorate([
  46815. BABYLON.serialize()
  46816. ], SpotLight.prototype, "shadowAngleScale", null);
  46817. __decorate([
  46818. BABYLON.serialize()
  46819. ], SpotLight.prototype, "exponent", void 0);
  46820. __decorate([
  46821. BABYLON.serialize()
  46822. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46823. __decorate([
  46824. BABYLON.serialize()
  46825. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46826. __decorate([
  46827. BABYLON.serialize()
  46828. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46829. __decorate([
  46830. BABYLON.serializeAsTexture("projectedLightTexture")
  46831. ], SpotLight.prototype, "_projectionTexture", void 0);
  46832. return SpotLight;
  46833. }(BABYLON.ShadowLight));
  46834. BABYLON.SpotLight = SpotLight;
  46835. })(BABYLON || (BABYLON = {}));
  46836. //# sourceMappingURL=babylon.spotLight.js.map
  46837. "use strict";
  46838. var BABYLON;
  46839. (function (BABYLON) {
  46840. /**
  46841. * Class used to override all child animations of a given target
  46842. */
  46843. var AnimationPropertiesOverride = /** @class */ (function () {
  46844. function AnimationPropertiesOverride() {
  46845. /**
  46846. * Gets or sets a value indicating if animation blending must be used
  46847. */
  46848. this.enableBlending = false;
  46849. /**
  46850. * Gets or sets the blending speed to use when enableBlending is true
  46851. */
  46852. this.blendingSpeed = 0.01;
  46853. /**
  46854. * Gets or sets the default loop mode to use
  46855. */
  46856. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46857. }
  46858. return AnimationPropertiesOverride;
  46859. }());
  46860. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46861. })(BABYLON || (BABYLON = {}));
  46862. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46863. "use strict";
  46864. var BABYLON;
  46865. (function (BABYLON) {
  46866. var AnimationRange = /** @class */ (function () {
  46867. function AnimationRange(name, from, to) {
  46868. this.name = name;
  46869. this.from = from;
  46870. this.to = to;
  46871. }
  46872. AnimationRange.prototype.clone = function () {
  46873. return new AnimationRange(this.name, this.from, this.to);
  46874. };
  46875. return AnimationRange;
  46876. }());
  46877. BABYLON.AnimationRange = AnimationRange;
  46878. /**
  46879. * Composed of a frame, and an action function
  46880. */
  46881. var AnimationEvent = /** @class */ (function () {
  46882. function AnimationEvent(frame, action, onlyOnce) {
  46883. this.frame = frame;
  46884. this.action = action;
  46885. this.onlyOnce = onlyOnce;
  46886. this.isDone = false;
  46887. }
  46888. return AnimationEvent;
  46889. }());
  46890. BABYLON.AnimationEvent = AnimationEvent;
  46891. var PathCursor = /** @class */ (function () {
  46892. function PathCursor(path) {
  46893. this.path = path;
  46894. this._onchange = new Array();
  46895. this.value = 0;
  46896. this.animations = new Array();
  46897. }
  46898. PathCursor.prototype.getPoint = function () {
  46899. var point = this.path.getPointAtLengthPosition(this.value);
  46900. return new BABYLON.Vector3(point.x, 0, point.y);
  46901. };
  46902. PathCursor.prototype.moveAhead = function (step) {
  46903. if (step === void 0) { step = 0.002; }
  46904. this.move(step);
  46905. return this;
  46906. };
  46907. PathCursor.prototype.moveBack = function (step) {
  46908. if (step === void 0) { step = 0.002; }
  46909. this.move(-step);
  46910. return this;
  46911. };
  46912. PathCursor.prototype.move = function (step) {
  46913. if (Math.abs(step) > 1) {
  46914. throw "step size should be less than 1.";
  46915. }
  46916. this.value += step;
  46917. this.ensureLimits();
  46918. this.raiseOnChange();
  46919. return this;
  46920. };
  46921. PathCursor.prototype.ensureLimits = function () {
  46922. while (this.value > 1) {
  46923. this.value -= 1;
  46924. }
  46925. while (this.value < 0) {
  46926. this.value += 1;
  46927. }
  46928. return this;
  46929. };
  46930. // used by animation engine
  46931. PathCursor.prototype.raiseOnChange = function () {
  46932. var _this = this;
  46933. this._onchange.forEach(function (f) { return f(_this); });
  46934. return this;
  46935. };
  46936. PathCursor.prototype.onchange = function (f) {
  46937. this._onchange.push(f);
  46938. return this;
  46939. };
  46940. return PathCursor;
  46941. }());
  46942. BABYLON.PathCursor = PathCursor;
  46943. var AnimationKeyInterpolation;
  46944. (function (AnimationKeyInterpolation) {
  46945. /**
  46946. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46947. */
  46948. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46949. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46950. var Animation = /** @class */ (function () {
  46951. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46952. this.name = name;
  46953. this.targetProperty = targetProperty;
  46954. this.framePerSecond = framePerSecond;
  46955. this.dataType = dataType;
  46956. this.loopMode = loopMode;
  46957. this.enableBlending = enableBlending;
  46958. this._runtimeAnimations = new Array();
  46959. // The set of event that will be linked to this animation
  46960. this._events = new Array();
  46961. this.blendingSpeed = 0.01;
  46962. this._ranges = {};
  46963. this.targetPropertyPath = targetProperty.split(".");
  46964. this.dataType = dataType;
  46965. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46966. }
  46967. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46968. var dataType = undefined;
  46969. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46970. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46971. }
  46972. else if (from instanceof BABYLON.Quaternion) {
  46973. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46974. }
  46975. else if (from instanceof BABYLON.Vector3) {
  46976. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46977. }
  46978. else if (from instanceof BABYLON.Vector2) {
  46979. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46980. }
  46981. else if (from instanceof BABYLON.Color3) {
  46982. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46983. }
  46984. else if (from instanceof BABYLON.Size) {
  46985. dataType = Animation.ANIMATIONTYPE_SIZE;
  46986. }
  46987. if (dataType == undefined) {
  46988. return null;
  46989. }
  46990. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46991. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46992. animation.setKeys(keys);
  46993. if (easingFunction !== undefined) {
  46994. animation.setEasingFunction(easingFunction);
  46995. }
  46996. return animation;
  46997. };
  46998. /**
  46999. * Sets up an animation.
  47000. * @param property the property to animate
  47001. * @param animationType the animation type to apply
  47002. * @param easingFunction the easing function used in the animation
  47003. * @returns The created animation
  47004. */
  47005. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  47006. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  47007. animation.setEasingFunction(easingFunction);
  47008. return animation;
  47009. };
  47010. /**
  47011. * Create and start an animation on a node
  47012. * @param {string} name defines the name of the global animation that will be run on all nodes
  47013. * @param {BABYLON.Node} node defines the root node where the animation will take place
  47014. * @param {string} targetProperty defines property to animate
  47015. * @param {number} framePerSecond defines the number of frame per second yo use
  47016. * @param {number} totalFrame defines the number of frames in total
  47017. * @param {any} from defines the initial value
  47018. * @param {any} to defines the final value
  47019. * @param {number} loopMode defines which loop mode you want to use (off by default)
  47020. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  47021. * @param onAnimationEnd defines the callback to call when animation end
  47022. * @returns the animatable created for this animation
  47023. */
  47024. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  47025. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  47026. if (!animation) {
  47027. return null;
  47028. }
  47029. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  47030. };
  47031. /**
  47032. * Create and start an animation on a node and its descendants
  47033. * @param {string} name defines the name of the global animation that will be run on all nodes
  47034. * @param {BABYLON.Node} node defines the root node where the animation will take place
  47035. * @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.
  47036. * @param {string} targetProperty defines property to animate
  47037. * @param {number} framePerSecond defines the number of frame per second yo use
  47038. * @param {number} totalFrame defines the number of frames in total
  47039. * @param {any} from defines the initial value
  47040. * @param {any} to defines the final value
  47041. * @param {number} loopMode defines which loop mode you want to use (off by default)
  47042. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  47043. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  47044. * @returns the list of animatables created for all nodes
  47045. * @example https://www.babylonjs-playground.com/#MH0VLI
  47046. */
  47047. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  47048. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  47049. if (!animation) {
  47050. return null;
  47051. }
  47052. var scene = node.getScene();
  47053. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  47054. };
  47055. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  47056. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  47057. if (!animation) {
  47058. return null;
  47059. }
  47060. node.animations.push(animation);
  47061. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  47062. };
  47063. /**
  47064. * Transition property of the Camera to the target Value.
  47065. * @param property The property to transition
  47066. * @param targetValue The target Value of the property
  47067. * @param host The object where the property to animate belongs
  47068. * @param scene Scene used to run the animation
  47069. * @param frameRate Framerate (in frame/s) to use
  47070. * @param transition The transition type we want to use
  47071. * @param duration The duration of the animation, in milliseconds
  47072. * @param onAnimationEnd Call back trigger at the end of the animation.
  47073. */
  47074. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  47075. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  47076. if (duration <= 0) {
  47077. host[property] = targetValue;
  47078. if (onAnimationEnd) {
  47079. onAnimationEnd();
  47080. }
  47081. return null;
  47082. }
  47083. var endFrame = frameRate * (duration / 1000);
  47084. transition.setKeys([{
  47085. frame: 0,
  47086. value: host[property].clone ? host[property].clone() : host[property]
  47087. },
  47088. {
  47089. frame: endFrame,
  47090. value: targetValue
  47091. }]);
  47092. if (!host.animations) {
  47093. host.animations = [];
  47094. }
  47095. host.animations.push(transition);
  47096. var animation = scene.beginAnimation(host, 0, endFrame, false);
  47097. animation.onAnimationEnd = onAnimationEnd;
  47098. return animation;
  47099. };
  47100. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  47101. /**
  47102. * Return the array of runtime animations currently using this animation
  47103. */
  47104. get: function () {
  47105. return this._runtimeAnimations;
  47106. },
  47107. enumerable: true,
  47108. configurable: true
  47109. });
  47110. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  47111. get: function () {
  47112. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  47113. var runtimeAnimation = _a[_i];
  47114. if (!runtimeAnimation.isStopped) {
  47115. return true;
  47116. }
  47117. }
  47118. return false;
  47119. },
  47120. enumerable: true,
  47121. configurable: true
  47122. });
  47123. // Methods
  47124. /**
  47125. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  47126. */
  47127. Animation.prototype.toString = function (fullDetails) {
  47128. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  47129. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  47130. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  47131. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  47132. if (fullDetails) {
  47133. ret += ", Ranges: {";
  47134. var first = true;
  47135. for (var name in this._ranges) {
  47136. if (first) {
  47137. ret += ", ";
  47138. first = false;
  47139. }
  47140. ret += name;
  47141. }
  47142. ret += "}";
  47143. }
  47144. return ret;
  47145. };
  47146. /**
  47147. * Add an event to this animation.
  47148. */
  47149. Animation.prototype.addEvent = function (event) {
  47150. this._events.push(event);
  47151. };
  47152. /**
  47153. * Remove all events found at the given frame
  47154. * @param frame
  47155. */
  47156. Animation.prototype.removeEvents = function (frame) {
  47157. for (var index = 0; index < this._events.length; index++) {
  47158. if (this._events[index].frame === frame) {
  47159. this._events.splice(index, 1);
  47160. index--;
  47161. }
  47162. }
  47163. };
  47164. Animation.prototype.getEvents = function () {
  47165. return this._events;
  47166. };
  47167. Animation.prototype.createRange = function (name, from, to) {
  47168. // check name not already in use; could happen for bones after serialized
  47169. if (!this._ranges[name]) {
  47170. this._ranges[name] = new AnimationRange(name, from, to);
  47171. }
  47172. };
  47173. Animation.prototype.deleteRange = function (name, deleteFrames) {
  47174. if (deleteFrames === void 0) { deleteFrames = true; }
  47175. var range = this._ranges[name];
  47176. if (!range) {
  47177. return;
  47178. }
  47179. if (deleteFrames) {
  47180. var from = range.from;
  47181. var to = range.to;
  47182. // this loop MUST go high to low for multiple splices to work
  47183. for (var key = this._keys.length - 1; key >= 0; key--) {
  47184. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  47185. this._keys.splice(key, 1);
  47186. }
  47187. }
  47188. }
  47189. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  47190. };
  47191. Animation.prototype.getRange = function (name) {
  47192. return this._ranges[name];
  47193. };
  47194. Animation.prototype.getKeys = function () {
  47195. return this._keys;
  47196. };
  47197. Animation.prototype.getHighestFrame = function () {
  47198. var ret = 0;
  47199. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  47200. if (ret < this._keys[key].frame) {
  47201. ret = this._keys[key].frame;
  47202. }
  47203. }
  47204. return ret;
  47205. };
  47206. Animation.prototype.getEasingFunction = function () {
  47207. return this._easingFunction;
  47208. };
  47209. Animation.prototype.setEasingFunction = function (easingFunction) {
  47210. this._easingFunction = easingFunction;
  47211. };
  47212. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  47213. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  47214. };
  47215. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47216. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47217. };
  47218. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  47219. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  47220. };
  47221. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47222. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  47223. };
  47224. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  47225. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  47226. };
  47227. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47228. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47229. };
  47230. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  47231. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  47232. };
  47233. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47234. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47235. };
  47236. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  47237. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  47238. };
  47239. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  47240. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  47241. };
  47242. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  47243. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  47244. };
  47245. Animation.prototype.clone = function () {
  47246. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  47247. clone.enableBlending = this.enableBlending;
  47248. clone.blendingSpeed = this.blendingSpeed;
  47249. if (this._keys) {
  47250. clone.setKeys(this._keys);
  47251. }
  47252. if (this._ranges) {
  47253. clone._ranges = {};
  47254. for (var name in this._ranges) {
  47255. var range = this._ranges[name];
  47256. if (!range) {
  47257. continue;
  47258. }
  47259. clone._ranges[name] = range.clone();
  47260. }
  47261. }
  47262. return clone;
  47263. };
  47264. Animation.prototype.setKeys = function (values) {
  47265. this._keys = values.slice(0);
  47266. };
  47267. Animation.prototype.serialize = function () {
  47268. var serializationObject = {};
  47269. serializationObject.name = this.name;
  47270. serializationObject.property = this.targetProperty;
  47271. serializationObject.framePerSecond = this.framePerSecond;
  47272. serializationObject.dataType = this.dataType;
  47273. serializationObject.loopBehavior = this.loopMode;
  47274. serializationObject.enableBlending = this.enableBlending;
  47275. serializationObject.blendingSpeed = this.blendingSpeed;
  47276. var dataType = this.dataType;
  47277. serializationObject.keys = [];
  47278. var keys = this.getKeys();
  47279. for (var index = 0; index < keys.length; index++) {
  47280. var animationKey = keys[index];
  47281. var key = {};
  47282. key.frame = animationKey.frame;
  47283. switch (dataType) {
  47284. case Animation.ANIMATIONTYPE_FLOAT:
  47285. key.values = [animationKey.value];
  47286. break;
  47287. case Animation.ANIMATIONTYPE_QUATERNION:
  47288. case Animation.ANIMATIONTYPE_MATRIX:
  47289. case Animation.ANIMATIONTYPE_VECTOR3:
  47290. case Animation.ANIMATIONTYPE_COLOR3:
  47291. key.values = animationKey.value.asArray();
  47292. break;
  47293. }
  47294. serializationObject.keys.push(key);
  47295. }
  47296. serializationObject.ranges = [];
  47297. for (var name in this._ranges) {
  47298. var source = this._ranges[name];
  47299. if (!source) {
  47300. continue;
  47301. }
  47302. var range = {};
  47303. range.name = name;
  47304. range.from = source.from;
  47305. range.to = source.to;
  47306. serializationObject.ranges.push(range);
  47307. }
  47308. return serializationObject;
  47309. };
  47310. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  47311. get: function () {
  47312. return Animation._ANIMATIONTYPE_FLOAT;
  47313. },
  47314. enumerable: true,
  47315. configurable: true
  47316. });
  47317. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  47318. get: function () {
  47319. return Animation._ANIMATIONTYPE_VECTOR3;
  47320. },
  47321. enumerable: true,
  47322. configurable: true
  47323. });
  47324. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  47325. get: function () {
  47326. return Animation._ANIMATIONTYPE_VECTOR2;
  47327. },
  47328. enumerable: true,
  47329. configurable: true
  47330. });
  47331. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  47332. get: function () {
  47333. return Animation._ANIMATIONTYPE_SIZE;
  47334. },
  47335. enumerable: true,
  47336. configurable: true
  47337. });
  47338. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  47339. get: function () {
  47340. return Animation._ANIMATIONTYPE_QUATERNION;
  47341. },
  47342. enumerable: true,
  47343. configurable: true
  47344. });
  47345. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  47346. get: function () {
  47347. return Animation._ANIMATIONTYPE_MATRIX;
  47348. },
  47349. enumerable: true,
  47350. configurable: true
  47351. });
  47352. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  47353. get: function () {
  47354. return Animation._ANIMATIONTYPE_COLOR3;
  47355. },
  47356. enumerable: true,
  47357. configurable: true
  47358. });
  47359. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  47360. get: function () {
  47361. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  47362. },
  47363. enumerable: true,
  47364. configurable: true
  47365. });
  47366. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  47367. get: function () {
  47368. return Animation._ANIMATIONLOOPMODE_CYCLE;
  47369. },
  47370. enumerable: true,
  47371. configurable: true
  47372. });
  47373. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  47374. get: function () {
  47375. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  47376. },
  47377. enumerable: true,
  47378. configurable: true
  47379. });
  47380. Animation.Parse = function (parsedAnimation) {
  47381. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  47382. var dataType = parsedAnimation.dataType;
  47383. var keys = [];
  47384. var data;
  47385. var index;
  47386. if (parsedAnimation.enableBlending) {
  47387. animation.enableBlending = parsedAnimation.enableBlending;
  47388. }
  47389. if (parsedAnimation.blendingSpeed) {
  47390. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  47391. }
  47392. for (index = 0; index < parsedAnimation.keys.length; index++) {
  47393. var key = parsedAnimation.keys[index];
  47394. var inTangent;
  47395. var outTangent;
  47396. switch (dataType) {
  47397. case Animation.ANIMATIONTYPE_FLOAT:
  47398. data = key.values[0];
  47399. if (key.values.length >= 1) {
  47400. inTangent = key.values[1];
  47401. }
  47402. if (key.values.length >= 2) {
  47403. outTangent = key.values[2];
  47404. }
  47405. break;
  47406. case Animation.ANIMATIONTYPE_QUATERNION:
  47407. data = BABYLON.Quaternion.FromArray(key.values);
  47408. if (key.values.length >= 8) {
  47409. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  47410. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  47411. inTangent = _inTangent;
  47412. }
  47413. }
  47414. if (key.values.length >= 12) {
  47415. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  47416. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  47417. outTangent = _outTangent;
  47418. }
  47419. }
  47420. break;
  47421. case Animation.ANIMATIONTYPE_MATRIX:
  47422. data = BABYLON.Matrix.FromArray(key.values);
  47423. break;
  47424. case Animation.ANIMATIONTYPE_COLOR3:
  47425. data = BABYLON.Color3.FromArray(key.values);
  47426. break;
  47427. case Animation.ANIMATIONTYPE_VECTOR3:
  47428. default:
  47429. data = BABYLON.Vector3.FromArray(key.values);
  47430. break;
  47431. }
  47432. var keyData = {};
  47433. keyData.frame = key.frame;
  47434. keyData.value = data;
  47435. if (inTangent != undefined) {
  47436. keyData.inTangent = inTangent;
  47437. }
  47438. if (outTangent != undefined) {
  47439. keyData.outTangent = outTangent;
  47440. }
  47441. keys.push(keyData);
  47442. }
  47443. animation.setKeys(keys);
  47444. if (parsedAnimation.ranges) {
  47445. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  47446. data = parsedAnimation.ranges[index];
  47447. animation.createRange(data.name, data.from, data.to);
  47448. }
  47449. }
  47450. return animation;
  47451. };
  47452. Animation.AppendSerializedAnimations = function (source, destination) {
  47453. if (source.animations) {
  47454. destination.animations = [];
  47455. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  47456. var animation = source.animations[animationIndex];
  47457. destination.animations.push(animation.serialize());
  47458. }
  47459. }
  47460. };
  47461. Animation.AllowMatricesInterpolation = false;
  47462. // Statics
  47463. Animation._ANIMATIONTYPE_FLOAT = 0;
  47464. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  47465. Animation._ANIMATIONTYPE_QUATERNION = 2;
  47466. Animation._ANIMATIONTYPE_MATRIX = 3;
  47467. Animation._ANIMATIONTYPE_COLOR3 = 4;
  47468. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  47469. Animation._ANIMATIONTYPE_SIZE = 6;
  47470. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  47471. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  47472. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  47473. return Animation;
  47474. }());
  47475. BABYLON.Animation = Animation;
  47476. })(BABYLON || (BABYLON = {}));
  47477. //# sourceMappingURL=babylon.animation.js.map
  47478. "use strict";
  47479. var BABYLON;
  47480. (function (BABYLON) {
  47481. /**
  47482. * This class defines the direct association between an animation and a target
  47483. */
  47484. var TargetedAnimation = /** @class */ (function () {
  47485. function TargetedAnimation() {
  47486. }
  47487. return TargetedAnimation;
  47488. }());
  47489. BABYLON.TargetedAnimation = TargetedAnimation;
  47490. /**
  47491. * Use this class to create coordinated animations on multiple targets
  47492. */
  47493. var AnimationGroup = /** @class */ (function () {
  47494. function AnimationGroup(name, scene) {
  47495. if (scene === void 0) { scene = null; }
  47496. this.name = name;
  47497. this._targetedAnimations = new Array();
  47498. this._animatables = new Array();
  47499. this._from = Number.MAX_VALUE;
  47500. this._to = -Number.MAX_VALUE;
  47501. this._speedRatio = 1;
  47502. this.onAnimationEndObservable = new BABYLON.Observable();
  47503. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47504. this._scene.animationGroups.push(this);
  47505. }
  47506. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  47507. /**
  47508. * Define if the animations are started
  47509. */
  47510. get: function () {
  47511. return this._isStarted;
  47512. },
  47513. enumerable: true,
  47514. configurable: true
  47515. });
  47516. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  47517. /**
  47518. * Gets or sets the speed ratio to use for all animations
  47519. */
  47520. get: function () {
  47521. return this._speedRatio;
  47522. },
  47523. /**
  47524. * Gets or sets the speed ratio to use for all animations
  47525. */
  47526. set: function (value) {
  47527. if (this._speedRatio === value) {
  47528. return;
  47529. }
  47530. this._speedRatio = value;
  47531. for (var index = 0; index < this._animatables.length; index++) {
  47532. var animatable = this._animatables[index];
  47533. animatable.speedRatio = this._speedRatio;
  47534. }
  47535. },
  47536. enumerable: true,
  47537. configurable: true
  47538. });
  47539. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  47540. /**
  47541. * Gets the targeted animations for this animation group
  47542. */
  47543. get: function () {
  47544. return this._targetedAnimations;
  47545. },
  47546. enumerable: true,
  47547. configurable: true
  47548. });
  47549. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  47550. /**
  47551. * returning the list of animatables controlled by this animation group.
  47552. */
  47553. get: function () {
  47554. return this._animatables;
  47555. },
  47556. enumerable: true,
  47557. configurable: true
  47558. });
  47559. /**
  47560. * Add an animation (with its target) in the group
  47561. * @param animation defines the animation we want to add
  47562. * @param target defines the target of the animation
  47563. * @returns the {BABYLON.TargetedAnimation} object
  47564. */
  47565. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  47566. var targetedAnimation = {
  47567. animation: animation,
  47568. target: target
  47569. };
  47570. var keys = animation.getKeys();
  47571. if (this._from > keys[0].frame) {
  47572. this._from = keys[0].frame;
  47573. }
  47574. if (this._to < keys[keys.length - 1].frame) {
  47575. this._to = keys[keys.length - 1].frame;
  47576. }
  47577. this._targetedAnimations.push(targetedAnimation);
  47578. return targetedAnimation;
  47579. };
  47580. /**
  47581. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  47582. * It can add constant keys at begin or end
  47583. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  47584. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  47585. */
  47586. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  47587. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  47588. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  47589. beginFrame = Math.max(beginFrame, this._from);
  47590. endFrame = Math.min(endFrame, this._to);
  47591. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47592. var targetedAnimation = this._targetedAnimations[index];
  47593. var keys = targetedAnimation.animation.getKeys();
  47594. var startKey = keys[0];
  47595. var endKey = keys[keys.length - 1];
  47596. if (startKey.frame > beginFrame) {
  47597. var newKey = {
  47598. frame: beginFrame,
  47599. value: startKey.value,
  47600. inTangent: startKey.inTangent,
  47601. outTangent: startKey.outTangent,
  47602. interpolation: startKey.interpolation
  47603. };
  47604. keys.splice(0, 0, newKey);
  47605. }
  47606. if (endKey.frame < endFrame) {
  47607. var newKey = {
  47608. frame: endFrame,
  47609. value: endKey.value,
  47610. inTangent: endKey.outTangent,
  47611. outTangent: endKey.outTangent,
  47612. interpolation: endKey.interpolation
  47613. };
  47614. keys.push(newKey);
  47615. }
  47616. }
  47617. return this;
  47618. };
  47619. /**
  47620. * Start all animations on given targets
  47621. * @param loop defines if animations must loop
  47622. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  47623. */
  47624. AnimationGroup.prototype.start = function (loop, speedRatio) {
  47625. var _this = this;
  47626. if (loop === void 0) { loop = false; }
  47627. if (speedRatio === void 0) { speedRatio = 1; }
  47628. if (this._isStarted || this._targetedAnimations.length === 0) {
  47629. return this;
  47630. }
  47631. var _loop_1 = function () {
  47632. var targetedAnimation = this_1._targetedAnimations[index];
  47633. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  47634. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  47635. }));
  47636. };
  47637. var this_1 = this;
  47638. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47639. _loop_1();
  47640. }
  47641. this._speedRatio = speedRatio;
  47642. this._isStarted = true;
  47643. return this;
  47644. };
  47645. /**
  47646. * Pause all animations
  47647. */
  47648. AnimationGroup.prototype.pause = function () {
  47649. if (!this._isStarted) {
  47650. return this;
  47651. }
  47652. for (var index = 0; index < this._animatables.length; index++) {
  47653. var animatable = this._animatables[index];
  47654. animatable.pause();
  47655. }
  47656. return this;
  47657. };
  47658. /**
  47659. * Play all animations to initial state
  47660. * This function will start() the animations if they were not started or will restart() them if they were paused
  47661. * @param loop defines if animations must loop
  47662. */
  47663. AnimationGroup.prototype.play = function (loop) {
  47664. if (this.isStarted) {
  47665. if (loop !== undefined) {
  47666. for (var index = 0; index < this._animatables.length; index++) {
  47667. var animatable = this._animatables[index];
  47668. animatable.loopAnimation = loop;
  47669. }
  47670. }
  47671. this.restart();
  47672. }
  47673. else {
  47674. this.start(loop, this._speedRatio);
  47675. }
  47676. return this;
  47677. };
  47678. /**
  47679. * Reset all animations to initial state
  47680. */
  47681. AnimationGroup.prototype.reset = function () {
  47682. if (!this._isStarted) {
  47683. return this;
  47684. }
  47685. for (var index = 0; index < this._animatables.length; index++) {
  47686. var animatable = this._animatables[index];
  47687. animatable.reset();
  47688. }
  47689. return this;
  47690. };
  47691. /**
  47692. * Restart animations from key 0
  47693. */
  47694. AnimationGroup.prototype.restart = function () {
  47695. if (!this._isStarted) {
  47696. return this;
  47697. }
  47698. for (var index = 0; index < this._animatables.length; index++) {
  47699. var animatable = this._animatables[index];
  47700. animatable.restart();
  47701. }
  47702. return this;
  47703. };
  47704. /**
  47705. * Stop all animations
  47706. */
  47707. AnimationGroup.prototype.stop = function () {
  47708. if (!this._isStarted) {
  47709. return this;
  47710. }
  47711. for (var index = 0; index < this._animatables.length; index++) {
  47712. var animatable = this._animatables[index];
  47713. animatable.stop();
  47714. }
  47715. this._isStarted = false;
  47716. return this;
  47717. };
  47718. /**
  47719. * Goes to a specific frame in this animation group
  47720. *
  47721. * @param frame the frame number to go to
  47722. * @return the animationGroup
  47723. */
  47724. AnimationGroup.prototype.goToFrame = function (frame) {
  47725. if (!this._isStarted) {
  47726. return this;
  47727. }
  47728. for (var index = 0; index < this._animatables.length; index++) {
  47729. var animatable = this._animatables[index];
  47730. animatable.goToFrame(frame);
  47731. }
  47732. return this;
  47733. };
  47734. /**
  47735. * Dispose all associated resources
  47736. */
  47737. AnimationGroup.prototype.dispose = function () {
  47738. this._targetedAnimations = [];
  47739. this._animatables = [];
  47740. var index = this._scene.animationGroups.indexOf(this);
  47741. if (index > -1) {
  47742. this._scene.animationGroups.splice(index, 1);
  47743. }
  47744. };
  47745. return AnimationGroup;
  47746. }());
  47747. BABYLON.AnimationGroup = AnimationGroup;
  47748. })(BABYLON || (BABYLON = {}));
  47749. //# sourceMappingURL=babylon.animationGroup.js.map
  47750. "use strict";
  47751. var BABYLON;
  47752. (function (BABYLON) {
  47753. var RuntimeAnimation = /** @class */ (function () {
  47754. /**
  47755. * Create a new RuntimeAnimation object
  47756. * @param target defines the target of the animation
  47757. * @param animation defines the source {BABYLON.Animation} object
  47758. * @param scene defines the hosting scene
  47759. */
  47760. function RuntimeAnimation(target, animation, scene) {
  47761. this._offsetsCache = {};
  47762. this._highLimitsCache = {};
  47763. this._stopped = false;
  47764. this._blendingFactor = 0;
  47765. this._weight = 1.0;
  47766. this._ratioOffset = 0;
  47767. this._animation = animation;
  47768. this._target = target;
  47769. this._scene = scene;
  47770. animation._runtimeAnimations.push(this);
  47771. }
  47772. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  47773. /**
  47774. * Gets the weight of the runtime animation
  47775. */
  47776. get: function () {
  47777. return this._weight;
  47778. },
  47779. enumerable: true,
  47780. configurable: true
  47781. });
  47782. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  47783. /**
  47784. * Gets the original value of the runtime animation
  47785. */
  47786. get: function () {
  47787. return this._originalValue;
  47788. },
  47789. enumerable: true,
  47790. configurable: true
  47791. });
  47792. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  47793. /**
  47794. * Gets the current value of the runtime animation
  47795. */
  47796. get: function () {
  47797. return this._currentValue;
  47798. },
  47799. enumerable: true,
  47800. configurable: true
  47801. });
  47802. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  47803. /**
  47804. * Gets the path where to store the animated value in the target
  47805. */
  47806. get: function () {
  47807. return this._targetPath;
  47808. },
  47809. enumerable: true,
  47810. configurable: true
  47811. });
  47812. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  47813. /**
  47814. * Gets the actual target of the runtime animation
  47815. */
  47816. get: function () {
  47817. return this._activeTarget;
  47818. },
  47819. enumerable: true,
  47820. configurable: true
  47821. });
  47822. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47823. get: function () {
  47824. return this._animation;
  47825. },
  47826. enumerable: true,
  47827. configurable: true
  47828. });
  47829. RuntimeAnimation.prototype.reset = function () {
  47830. this._offsetsCache = {};
  47831. this._highLimitsCache = {};
  47832. this.currentFrame = 0;
  47833. this._blendingFactor = 0;
  47834. this._originalValue = null;
  47835. };
  47836. RuntimeAnimation.prototype.isStopped = function () {
  47837. return this._stopped;
  47838. };
  47839. RuntimeAnimation.prototype.dispose = function () {
  47840. var index = this._animation.runtimeAnimations.indexOf(this);
  47841. if (index > -1) {
  47842. this._animation.runtimeAnimations.splice(index, 1);
  47843. }
  47844. };
  47845. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47846. if (typeof value === "function") {
  47847. return value();
  47848. }
  47849. return value;
  47850. };
  47851. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47852. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47853. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47854. }
  47855. this.currentFrame = currentFrame;
  47856. var keys = this._animation.getKeys();
  47857. // Try to get a hash to find the right key
  47858. 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));
  47859. if (keys[startKeyIndex].frame >= currentFrame) {
  47860. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47861. startKeyIndex--;
  47862. }
  47863. }
  47864. for (var key = startKeyIndex; key < keys.length; key++) {
  47865. var endKey = keys[key + 1];
  47866. if (endKey.frame >= currentFrame) {
  47867. var startKey = keys[key];
  47868. var startValue = this._getKeyValue(startKey.value);
  47869. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47870. return startValue;
  47871. }
  47872. var endValue = this._getKeyValue(endKey.value);
  47873. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47874. var frameDelta = endKey.frame - startKey.frame;
  47875. // gradient : percent of currentFrame between the frame inf and the frame sup
  47876. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47877. // check for easingFunction and correction of gradient
  47878. var easingFunction = this._animation.getEasingFunction();
  47879. if (easingFunction != null) {
  47880. gradient = easingFunction.ease(gradient);
  47881. }
  47882. switch (this._animation.dataType) {
  47883. // Float
  47884. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47885. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47886. switch (loopMode) {
  47887. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47888. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47889. return floatValue;
  47890. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47891. return offsetValue * repeatCount + floatValue;
  47892. }
  47893. break;
  47894. // Quaternion
  47895. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47896. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47897. switch (loopMode) {
  47898. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47899. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47900. return quatValue;
  47901. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47902. return quatValue.add(offsetValue.scale(repeatCount));
  47903. }
  47904. return quatValue;
  47905. // Vector3
  47906. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47907. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47908. switch (loopMode) {
  47909. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47910. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47911. return vec3Value;
  47912. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47913. return vec3Value.add(offsetValue.scale(repeatCount));
  47914. }
  47915. // Vector2
  47916. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47917. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47918. switch (loopMode) {
  47919. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47920. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47921. return vec2Value;
  47922. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47923. return vec2Value.add(offsetValue.scale(repeatCount));
  47924. }
  47925. // Size
  47926. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47927. switch (loopMode) {
  47928. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47929. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47930. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47931. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47932. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47933. }
  47934. // Color3
  47935. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47936. switch (loopMode) {
  47937. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47938. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47939. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47940. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47941. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47942. }
  47943. // Matrix
  47944. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47945. switch (loopMode) {
  47946. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47947. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47948. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47949. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47950. }
  47951. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47952. return startValue;
  47953. }
  47954. default:
  47955. break;
  47956. }
  47957. break;
  47958. }
  47959. }
  47960. return this._getKeyValue(keys[keys.length - 1].value);
  47961. };
  47962. /**
  47963. * Affect the interpolated value to the target
  47964. * @param currentValue defines the value computed by the animation
  47965. * @param weight defines the weight to apply to this value
  47966. */
  47967. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  47968. if (weight === void 0) { weight = 1.0; }
  47969. // Set value
  47970. var path;
  47971. var destination;
  47972. var targetPropertyPath = this._animation.targetPropertyPath;
  47973. if (targetPropertyPath.length > 1) {
  47974. var property = this._target[targetPropertyPath[0]];
  47975. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47976. property = property[targetPropertyPath[index]];
  47977. }
  47978. path = [targetPropertyPath.length - 1];
  47979. destination = property;
  47980. }
  47981. else {
  47982. path = targetPropertyPath[0];
  47983. destination = this._target;
  47984. }
  47985. this._targetPath = path;
  47986. this._activeTarget = destination;
  47987. this._weight = weight;
  47988. // Blending
  47989. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  47990. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  47991. if (enableBlending && this._blendingFactor <= 1.0 || weight !== -1.0) {
  47992. if (!this._originalValue) {
  47993. var originalValue = void 0;
  47994. if (destination.getRestPose) {
  47995. originalValue = destination.getRestPose();
  47996. }
  47997. else {
  47998. originalValue = destination[path];
  47999. }
  48000. if (originalValue.clone) {
  48001. this._originalValue = originalValue.clone();
  48002. }
  48003. else {
  48004. this._originalValue = originalValue;
  48005. }
  48006. }
  48007. }
  48008. if (enableBlending && this._blendingFactor <= 1.0) {
  48009. if (this._originalValue.prototype) {
  48010. if (this._originalValue.prototype.Lerp) {
  48011. this._currentValue = this._originalValue.construtor.prototype.Lerp(currentValue, this._originalValue, this._blendingFactor);
  48012. }
  48013. else {
  48014. this._currentValue = currentValue;
  48015. }
  48016. }
  48017. else if (this._originalValue.m) {
  48018. this._currentValue = BABYLON.Matrix.Lerp(this._originalValue, currentValue, this._blendingFactor);
  48019. }
  48020. else {
  48021. this._currentValue = this._originalValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  48022. }
  48023. this._blendingFactor += blendingSpeed;
  48024. destination[path] = this._currentValue;
  48025. }
  48026. else {
  48027. this._currentValue = currentValue;
  48028. if (weight !== -1.0) {
  48029. this._scene._registerTargetForLateAnimationBinding(this);
  48030. }
  48031. else {
  48032. destination[path] = this._currentValue;
  48033. }
  48034. }
  48035. if (this._target.markAsDirty) {
  48036. this._target.markAsDirty(this._animation.targetProperty);
  48037. }
  48038. };
  48039. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  48040. if (this._target && this._target.animationPropertiesOverride) {
  48041. return this._target.animationPropertiesOverride.loopMode;
  48042. }
  48043. return this._animation.loopMode;
  48044. };
  48045. /**
  48046. * Move the current animation to a given frame
  48047. * @param frame defines the frame to move to
  48048. */
  48049. RuntimeAnimation.prototype.goToFrame = function (frame) {
  48050. var keys = this._animation.getKeys();
  48051. if (frame < keys[0].frame) {
  48052. frame = keys[0].frame;
  48053. }
  48054. else if (frame > keys[keys.length - 1].frame) {
  48055. frame = keys[keys.length - 1].frame;
  48056. }
  48057. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  48058. this.setValue(currentValue, -1);
  48059. };
  48060. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  48061. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  48062. this._ratioOffset = this._previousRatio - newRatio;
  48063. };
  48064. /**
  48065. * Execute the current animation
  48066. * @param delay defines the delay to add to the current frame
  48067. * @param from defines the lower bound of the animation range
  48068. * @param to defines the upper bound of the animation range
  48069. * @param loop defines if the current animation must loop
  48070. * @param speedRatio defines the current speed ratio
  48071. * @param weight defines the weight of the animation (default is -1 so no weight)
  48072. * @returns a boolean indicating if the animation has ended
  48073. */
  48074. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  48075. if (weight === void 0) { weight = -1.0; }
  48076. var targetPropertyPath = this._animation.targetPropertyPath;
  48077. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  48078. this._stopped = true;
  48079. return false;
  48080. }
  48081. var returnValue = true;
  48082. var keys = this._animation.getKeys();
  48083. // Adding a start key at frame 0 if missing
  48084. if (keys[0].frame !== 0) {
  48085. var newKey = { frame: 0, value: keys[0].value };
  48086. keys.splice(0, 0, newKey);
  48087. }
  48088. // Check limits
  48089. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  48090. from = keys[0].frame;
  48091. }
  48092. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  48093. to = keys[keys.length - 1].frame;
  48094. }
  48095. //to and from cannot be the same key
  48096. if (from === to) {
  48097. if (from > keys[0].frame) {
  48098. from--;
  48099. }
  48100. else if (to < keys[keys.length - 1].frame) {
  48101. to++;
  48102. }
  48103. }
  48104. // Compute ratio
  48105. var range = to - from;
  48106. var offsetValue;
  48107. // ratio represents the frame delta between from and to
  48108. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  48109. var highLimitValue = 0;
  48110. this._previousDelay = delay;
  48111. this._previousRatio = ratio;
  48112. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  48113. returnValue = false;
  48114. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  48115. }
  48116. else {
  48117. // Get max value if required
  48118. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  48119. var keyOffset = to.toString() + from.toString();
  48120. if (!this._offsetsCache[keyOffset]) {
  48121. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48122. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48123. switch (this._animation.dataType) {
  48124. // Float
  48125. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48126. this._offsetsCache[keyOffset] = toValue - fromValue;
  48127. break;
  48128. // Quaternion
  48129. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48130. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48131. break;
  48132. // Vector3
  48133. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48134. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48135. // Vector2
  48136. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48137. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48138. // Size
  48139. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48140. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48141. // Color3
  48142. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48143. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48144. default:
  48145. break;
  48146. }
  48147. this._highLimitsCache[keyOffset] = toValue;
  48148. }
  48149. highLimitValue = this._highLimitsCache[keyOffset];
  48150. offsetValue = this._offsetsCache[keyOffset];
  48151. }
  48152. }
  48153. if (offsetValue === undefined) {
  48154. switch (this._animation.dataType) {
  48155. // Float
  48156. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48157. offsetValue = 0;
  48158. break;
  48159. // Quaternion
  48160. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48161. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  48162. break;
  48163. // Vector3
  48164. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48165. offsetValue = BABYLON.Vector3.Zero();
  48166. break;
  48167. // Vector2
  48168. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48169. offsetValue = BABYLON.Vector2.Zero();
  48170. break;
  48171. // Size
  48172. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48173. offsetValue = BABYLON.Size.Zero();
  48174. break;
  48175. // Color3
  48176. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48177. offsetValue = BABYLON.Color3.Black();
  48178. }
  48179. }
  48180. // Compute value
  48181. var repeatCount = (ratio / range) >> 0;
  48182. var currentFrame = returnValue ? from + ratio % range : to;
  48183. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  48184. // Set value
  48185. this.setValue(currentValue, weight);
  48186. // Check events
  48187. var events = this._animation.getEvents();
  48188. for (var index = 0; index < events.length; index++) {
  48189. // Make sure current frame has passed event frame and that event frame is within the current range
  48190. // Also, handle both forward and reverse animations
  48191. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  48192. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  48193. var event = events[index];
  48194. if (!event.isDone) {
  48195. // If event should be done only once, remove it.
  48196. if (event.onlyOnce) {
  48197. events.splice(index, 1);
  48198. index--;
  48199. }
  48200. event.isDone = true;
  48201. event.action();
  48202. } // Don't do anything if the event has already be done.
  48203. }
  48204. else if (events[index].isDone && !events[index].onlyOnce) {
  48205. // reset event, the animation is looping
  48206. events[index].isDone = false;
  48207. }
  48208. }
  48209. if (!returnValue) {
  48210. this._stopped = true;
  48211. }
  48212. return returnValue;
  48213. };
  48214. return RuntimeAnimation;
  48215. }());
  48216. BABYLON.RuntimeAnimation = RuntimeAnimation;
  48217. })(BABYLON || (BABYLON = {}));
  48218. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  48219. "use strict";
  48220. var BABYLON;
  48221. (function (BABYLON) {
  48222. var Animatable = /** @class */ (function () {
  48223. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  48224. if (fromFrame === void 0) { fromFrame = 0; }
  48225. if (toFrame === void 0) { toFrame = 100; }
  48226. if (loopAnimation === void 0) { loopAnimation = false; }
  48227. if (speedRatio === void 0) { speedRatio = 1.0; }
  48228. this.target = target;
  48229. this.fromFrame = fromFrame;
  48230. this.toFrame = toFrame;
  48231. this.loopAnimation = loopAnimation;
  48232. this.onAnimationEnd = onAnimationEnd;
  48233. this._localDelayOffset = null;
  48234. this._pausedDelay = null;
  48235. this._runtimeAnimations = new Array();
  48236. this._paused = false;
  48237. this._speedRatio = 1;
  48238. this._weight = -1.0;
  48239. this.animationStarted = false;
  48240. if (animations) {
  48241. this.appendAnimations(target, animations);
  48242. }
  48243. this._speedRatio = speedRatio;
  48244. this._scene = scene;
  48245. scene._activeAnimatables.push(this);
  48246. }
  48247. Object.defineProperty(Animatable.prototype, "weight", {
  48248. /**
  48249. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  48250. */
  48251. get: function () {
  48252. return this._weight;
  48253. },
  48254. set: function (value) {
  48255. if (value === -1) {
  48256. this._weight = -1;
  48257. return;
  48258. }
  48259. // Else weight must be in [0, 1] range
  48260. this._weight = Math.min(Math.max(value, 0), 1.0);
  48261. },
  48262. enumerable: true,
  48263. configurable: true
  48264. });
  48265. Object.defineProperty(Animatable.prototype, "speedRatio", {
  48266. /**
  48267. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  48268. */
  48269. get: function () {
  48270. return this._speedRatio;
  48271. },
  48272. set: function (value) {
  48273. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  48274. var animation = this._runtimeAnimations[index];
  48275. animation._prepareForSpeedRatioChange(value);
  48276. }
  48277. this._speedRatio = value;
  48278. },
  48279. enumerable: true,
  48280. configurable: true
  48281. });
  48282. // Methods
  48283. Animatable.prototype.getAnimations = function () {
  48284. return this._runtimeAnimations;
  48285. };
  48286. Animatable.prototype.appendAnimations = function (target, animations) {
  48287. for (var index = 0; index < animations.length; index++) {
  48288. var animation = animations[index];
  48289. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene));
  48290. }
  48291. };
  48292. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  48293. var runtimeAnimations = this._runtimeAnimations;
  48294. for (var index = 0; index < runtimeAnimations.length; index++) {
  48295. if (runtimeAnimations[index].animation.targetProperty === property) {
  48296. return runtimeAnimations[index].animation;
  48297. }
  48298. }
  48299. return null;
  48300. };
  48301. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  48302. var runtimeAnimations = this._runtimeAnimations;
  48303. for (var index = 0; index < runtimeAnimations.length; index++) {
  48304. if (runtimeAnimations[index].animation.targetProperty === property) {
  48305. return runtimeAnimations[index];
  48306. }
  48307. }
  48308. return null;
  48309. };
  48310. Animatable.prototype.reset = function () {
  48311. var runtimeAnimations = this._runtimeAnimations;
  48312. for (var index = 0; index < runtimeAnimations.length; index++) {
  48313. runtimeAnimations[index].reset();
  48314. }
  48315. // Reset to original value
  48316. for (index = 0; index < runtimeAnimations.length; index++) {
  48317. var animation = runtimeAnimations[index];
  48318. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  48319. }
  48320. this._localDelayOffset = null;
  48321. this._pausedDelay = null;
  48322. };
  48323. Animatable.prototype.enableBlending = function (blendingSpeed) {
  48324. var runtimeAnimations = this._runtimeAnimations;
  48325. for (var index = 0; index < runtimeAnimations.length; index++) {
  48326. runtimeAnimations[index].animation.enableBlending = true;
  48327. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  48328. }
  48329. };
  48330. Animatable.prototype.disableBlending = function () {
  48331. var runtimeAnimations = this._runtimeAnimations;
  48332. for (var index = 0; index < runtimeAnimations.length; index++) {
  48333. runtimeAnimations[index].animation.enableBlending = false;
  48334. }
  48335. };
  48336. Animatable.prototype.goToFrame = function (frame) {
  48337. var runtimeAnimations = this._runtimeAnimations;
  48338. if (runtimeAnimations[0]) {
  48339. var fps = runtimeAnimations[0].animation.framePerSecond;
  48340. var currentFrame = runtimeAnimations[0].currentFrame;
  48341. var adjustTime = frame - currentFrame;
  48342. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  48343. if (this._localDelayOffset === null) {
  48344. this._localDelayOffset = 0;
  48345. }
  48346. this._localDelayOffset -= delay;
  48347. }
  48348. for (var index = 0; index < runtimeAnimations.length; index++) {
  48349. runtimeAnimations[index].goToFrame(frame);
  48350. }
  48351. };
  48352. Animatable.prototype.pause = function () {
  48353. if (this._paused) {
  48354. return;
  48355. }
  48356. this._paused = true;
  48357. };
  48358. Animatable.prototype.restart = function () {
  48359. this._paused = false;
  48360. };
  48361. Animatable.prototype.stop = function (animationName) {
  48362. if (animationName) {
  48363. var idx = this._scene._activeAnimatables.indexOf(this);
  48364. if (idx > -1) {
  48365. var runtimeAnimations = this._runtimeAnimations;
  48366. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  48367. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  48368. continue;
  48369. }
  48370. runtimeAnimations[index].dispose();
  48371. runtimeAnimations.splice(index, 1);
  48372. }
  48373. if (runtimeAnimations.length == 0) {
  48374. this._scene._activeAnimatables.splice(idx, 1);
  48375. if (this.onAnimationEnd) {
  48376. this.onAnimationEnd();
  48377. }
  48378. }
  48379. }
  48380. }
  48381. else {
  48382. var index = this._scene._activeAnimatables.indexOf(this);
  48383. if (index > -1) {
  48384. this._scene._activeAnimatables.splice(index, 1);
  48385. var runtimeAnimations = this._runtimeAnimations;
  48386. for (var index = 0; index < runtimeAnimations.length; index++) {
  48387. runtimeAnimations[index].dispose();
  48388. }
  48389. if (this.onAnimationEnd) {
  48390. this.onAnimationEnd();
  48391. }
  48392. }
  48393. }
  48394. };
  48395. Animatable.prototype._animate = function (delay) {
  48396. if (this._paused) {
  48397. this.animationStarted = false;
  48398. if (this._pausedDelay === null) {
  48399. this._pausedDelay = delay;
  48400. }
  48401. return true;
  48402. }
  48403. if (this._localDelayOffset === null) {
  48404. this._localDelayOffset = delay;
  48405. this._pausedDelay = null;
  48406. }
  48407. else if (this._pausedDelay !== null) {
  48408. this._localDelayOffset += delay - this._pausedDelay;
  48409. this._pausedDelay = null;
  48410. }
  48411. // Animating
  48412. var running = false;
  48413. var runtimeAnimations = this._runtimeAnimations;
  48414. var index;
  48415. for (index = 0; index < runtimeAnimations.length; index++) {
  48416. var animation = runtimeAnimations[index];
  48417. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  48418. running = running || isRunning;
  48419. }
  48420. this.animationStarted = running;
  48421. if (!running) {
  48422. // Remove from active animatables
  48423. index = this._scene._activeAnimatables.indexOf(this);
  48424. this._scene._activeAnimatables.splice(index, 1);
  48425. // Dispose all runtime animations
  48426. for (index = 0; index < runtimeAnimations.length; index++) {
  48427. runtimeAnimations[index].dispose();
  48428. }
  48429. }
  48430. if (!running && this.onAnimationEnd) {
  48431. this.onAnimationEnd();
  48432. this.onAnimationEnd = null;
  48433. }
  48434. return running;
  48435. };
  48436. return Animatable;
  48437. }());
  48438. BABYLON.Animatable = Animatable;
  48439. })(BABYLON || (BABYLON = {}));
  48440. //# sourceMappingURL=babylon.animatable.js.map
  48441. "use strict";
  48442. var BABYLON;
  48443. (function (BABYLON) {
  48444. var EasingFunction = /** @class */ (function () {
  48445. function EasingFunction() {
  48446. // Properties
  48447. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  48448. }
  48449. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  48450. get: function () {
  48451. return EasingFunction._EASINGMODE_EASEIN;
  48452. },
  48453. enumerable: true,
  48454. configurable: true
  48455. });
  48456. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  48457. get: function () {
  48458. return EasingFunction._EASINGMODE_EASEOUT;
  48459. },
  48460. enumerable: true,
  48461. configurable: true
  48462. });
  48463. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  48464. get: function () {
  48465. return EasingFunction._EASINGMODE_EASEINOUT;
  48466. },
  48467. enumerable: true,
  48468. configurable: true
  48469. });
  48470. EasingFunction.prototype.setEasingMode = function (easingMode) {
  48471. var n = Math.min(Math.max(easingMode, 0), 2);
  48472. this._easingMode = n;
  48473. };
  48474. EasingFunction.prototype.getEasingMode = function () {
  48475. return this._easingMode;
  48476. };
  48477. EasingFunction.prototype.easeInCore = function (gradient) {
  48478. throw new Error('You must implement this method');
  48479. };
  48480. EasingFunction.prototype.ease = function (gradient) {
  48481. switch (this._easingMode) {
  48482. case EasingFunction.EASINGMODE_EASEIN:
  48483. return this.easeInCore(gradient);
  48484. case EasingFunction.EASINGMODE_EASEOUT:
  48485. return (1 - this.easeInCore(1 - gradient));
  48486. }
  48487. if (gradient >= 0.5) {
  48488. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  48489. }
  48490. return (this.easeInCore(gradient * 2) * 0.5);
  48491. };
  48492. //Statics
  48493. EasingFunction._EASINGMODE_EASEIN = 0;
  48494. EasingFunction._EASINGMODE_EASEOUT = 1;
  48495. EasingFunction._EASINGMODE_EASEINOUT = 2;
  48496. return EasingFunction;
  48497. }());
  48498. BABYLON.EasingFunction = EasingFunction;
  48499. var CircleEase = /** @class */ (function (_super) {
  48500. __extends(CircleEase, _super);
  48501. function CircleEase() {
  48502. return _super !== null && _super.apply(this, arguments) || this;
  48503. }
  48504. CircleEase.prototype.easeInCore = function (gradient) {
  48505. gradient = Math.max(0, Math.min(1, gradient));
  48506. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  48507. };
  48508. return CircleEase;
  48509. }(EasingFunction));
  48510. BABYLON.CircleEase = CircleEase;
  48511. var BackEase = /** @class */ (function (_super) {
  48512. __extends(BackEase, _super);
  48513. function BackEase(amplitude) {
  48514. if (amplitude === void 0) { amplitude = 1; }
  48515. var _this = _super.call(this) || this;
  48516. _this.amplitude = amplitude;
  48517. return _this;
  48518. }
  48519. BackEase.prototype.easeInCore = function (gradient) {
  48520. var num = Math.max(0, this.amplitude);
  48521. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  48522. };
  48523. return BackEase;
  48524. }(EasingFunction));
  48525. BABYLON.BackEase = BackEase;
  48526. var BounceEase = /** @class */ (function (_super) {
  48527. __extends(BounceEase, _super);
  48528. function BounceEase(bounces, bounciness) {
  48529. if (bounces === void 0) { bounces = 3; }
  48530. if (bounciness === void 0) { bounciness = 2; }
  48531. var _this = _super.call(this) || this;
  48532. _this.bounces = bounces;
  48533. _this.bounciness = bounciness;
  48534. return _this;
  48535. }
  48536. BounceEase.prototype.easeInCore = function (gradient) {
  48537. var y = Math.max(0.0, this.bounces);
  48538. var bounciness = this.bounciness;
  48539. if (bounciness <= 1.0) {
  48540. bounciness = 1.001;
  48541. }
  48542. var num9 = Math.pow(bounciness, y);
  48543. var num5 = 1.0 - bounciness;
  48544. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  48545. var num15 = gradient * num4;
  48546. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  48547. var num3 = Math.floor(num65);
  48548. var num13 = num3 + 1.0;
  48549. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  48550. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  48551. var num7 = (num8 + num12) * 0.5;
  48552. var num6 = gradient - num7;
  48553. var num2 = num7 - num8;
  48554. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  48555. };
  48556. return BounceEase;
  48557. }(EasingFunction));
  48558. BABYLON.BounceEase = BounceEase;
  48559. var CubicEase = /** @class */ (function (_super) {
  48560. __extends(CubicEase, _super);
  48561. function CubicEase() {
  48562. return _super !== null && _super.apply(this, arguments) || this;
  48563. }
  48564. CubicEase.prototype.easeInCore = function (gradient) {
  48565. return (gradient * gradient * gradient);
  48566. };
  48567. return CubicEase;
  48568. }(EasingFunction));
  48569. BABYLON.CubicEase = CubicEase;
  48570. var ElasticEase = /** @class */ (function (_super) {
  48571. __extends(ElasticEase, _super);
  48572. function ElasticEase(oscillations, springiness) {
  48573. if (oscillations === void 0) { oscillations = 3; }
  48574. if (springiness === void 0) { springiness = 3; }
  48575. var _this = _super.call(this) || this;
  48576. _this.oscillations = oscillations;
  48577. _this.springiness = springiness;
  48578. return _this;
  48579. }
  48580. ElasticEase.prototype.easeInCore = function (gradient) {
  48581. var num2;
  48582. var num3 = Math.max(0.0, this.oscillations);
  48583. var num = Math.max(0.0, this.springiness);
  48584. if (num == 0) {
  48585. num2 = gradient;
  48586. }
  48587. else {
  48588. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  48589. }
  48590. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  48591. };
  48592. return ElasticEase;
  48593. }(EasingFunction));
  48594. BABYLON.ElasticEase = ElasticEase;
  48595. var ExponentialEase = /** @class */ (function (_super) {
  48596. __extends(ExponentialEase, _super);
  48597. function ExponentialEase(exponent) {
  48598. if (exponent === void 0) { exponent = 2; }
  48599. var _this = _super.call(this) || this;
  48600. _this.exponent = exponent;
  48601. return _this;
  48602. }
  48603. ExponentialEase.prototype.easeInCore = function (gradient) {
  48604. if (this.exponent <= 0) {
  48605. return gradient;
  48606. }
  48607. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  48608. };
  48609. return ExponentialEase;
  48610. }(EasingFunction));
  48611. BABYLON.ExponentialEase = ExponentialEase;
  48612. var PowerEase = /** @class */ (function (_super) {
  48613. __extends(PowerEase, _super);
  48614. function PowerEase(power) {
  48615. if (power === void 0) { power = 2; }
  48616. var _this = _super.call(this) || this;
  48617. _this.power = power;
  48618. return _this;
  48619. }
  48620. PowerEase.prototype.easeInCore = function (gradient) {
  48621. var y = Math.max(0.0, this.power);
  48622. return Math.pow(gradient, y);
  48623. };
  48624. return PowerEase;
  48625. }(EasingFunction));
  48626. BABYLON.PowerEase = PowerEase;
  48627. var QuadraticEase = /** @class */ (function (_super) {
  48628. __extends(QuadraticEase, _super);
  48629. function QuadraticEase() {
  48630. return _super !== null && _super.apply(this, arguments) || this;
  48631. }
  48632. QuadraticEase.prototype.easeInCore = function (gradient) {
  48633. return (gradient * gradient);
  48634. };
  48635. return QuadraticEase;
  48636. }(EasingFunction));
  48637. BABYLON.QuadraticEase = QuadraticEase;
  48638. var QuarticEase = /** @class */ (function (_super) {
  48639. __extends(QuarticEase, _super);
  48640. function QuarticEase() {
  48641. return _super !== null && _super.apply(this, arguments) || this;
  48642. }
  48643. QuarticEase.prototype.easeInCore = function (gradient) {
  48644. return (gradient * gradient * gradient * gradient);
  48645. };
  48646. return QuarticEase;
  48647. }(EasingFunction));
  48648. BABYLON.QuarticEase = QuarticEase;
  48649. var QuinticEase = /** @class */ (function (_super) {
  48650. __extends(QuinticEase, _super);
  48651. function QuinticEase() {
  48652. return _super !== null && _super.apply(this, arguments) || this;
  48653. }
  48654. QuinticEase.prototype.easeInCore = function (gradient) {
  48655. return (gradient * gradient * gradient * gradient * gradient);
  48656. };
  48657. return QuinticEase;
  48658. }(EasingFunction));
  48659. BABYLON.QuinticEase = QuinticEase;
  48660. var SineEase = /** @class */ (function (_super) {
  48661. __extends(SineEase, _super);
  48662. function SineEase() {
  48663. return _super !== null && _super.apply(this, arguments) || this;
  48664. }
  48665. SineEase.prototype.easeInCore = function (gradient) {
  48666. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  48667. };
  48668. return SineEase;
  48669. }(EasingFunction));
  48670. BABYLON.SineEase = SineEase;
  48671. var BezierCurveEase = /** @class */ (function (_super) {
  48672. __extends(BezierCurveEase, _super);
  48673. function BezierCurveEase(x1, y1, x2, y2) {
  48674. if (x1 === void 0) { x1 = 0; }
  48675. if (y1 === void 0) { y1 = 0; }
  48676. if (x2 === void 0) { x2 = 1; }
  48677. if (y2 === void 0) { y2 = 1; }
  48678. var _this = _super.call(this) || this;
  48679. _this.x1 = x1;
  48680. _this.y1 = y1;
  48681. _this.x2 = x2;
  48682. _this.y2 = y2;
  48683. return _this;
  48684. }
  48685. BezierCurveEase.prototype.easeInCore = function (gradient) {
  48686. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  48687. };
  48688. return BezierCurveEase;
  48689. }(EasingFunction));
  48690. BABYLON.BezierCurveEase = BezierCurveEase;
  48691. })(BABYLON || (BABYLON = {}));
  48692. //# sourceMappingURL=babylon.easing.js.map
  48693. "use strict";
  48694. var BABYLON;
  48695. (function (BABYLON) {
  48696. var Condition = /** @class */ (function () {
  48697. function Condition(actionManager) {
  48698. this._actionManager = actionManager;
  48699. }
  48700. Condition.prototype.isValid = function () {
  48701. return true;
  48702. };
  48703. Condition.prototype._getProperty = function (propertyPath) {
  48704. return this._actionManager._getProperty(propertyPath);
  48705. };
  48706. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  48707. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48708. };
  48709. Condition.prototype.serialize = function () {
  48710. };
  48711. Condition.prototype._serialize = function (serializedCondition) {
  48712. return {
  48713. type: 2,
  48714. children: [],
  48715. name: serializedCondition.name,
  48716. properties: serializedCondition.properties
  48717. };
  48718. };
  48719. return Condition;
  48720. }());
  48721. BABYLON.Condition = Condition;
  48722. var ValueCondition = /** @class */ (function (_super) {
  48723. __extends(ValueCondition, _super);
  48724. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  48725. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  48726. var _this = _super.call(this, actionManager) || this;
  48727. _this.propertyPath = propertyPath;
  48728. _this.value = value;
  48729. _this.operator = operator;
  48730. _this._target = target;
  48731. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  48732. _this._property = _this._getProperty(_this.propertyPath);
  48733. return _this;
  48734. }
  48735. Object.defineProperty(ValueCondition, "IsEqual", {
  48736. get: function () {
  48737. return ValueCondition._IsEqual;
  48738. },
  48739. enumerable: true,
  48740. configurable: true
  48741. });
  48742. Object.defineProperty(ValueCondition, "IsDifferent", {
  48743. get: function () {
  48744. return ValueCondition._IsDifferent;
  48745. },
  48746. enumerable: true,
  48747. configurable: true
  48748. });
  48749. Object.defineProperty(ValueCondition, "IsGreater", {
  48750. get: function () {
  48751. return ValueCondition._IsGreater;
  48752. },
  48753. enumerable: true,
  48754. configurable: true
  48755. });
  48756. Object.defineProperty(ValueCondition, "IsLesser", {
  48757. get: function () {
  48758. return ValueCondition._IsLesser;
  48759. },
  48760. enumerable: true,
  48761. configurable: true
  48762. });
  48763. // Methods
  48764. ValueCondition.prototype.isValid = function () {
  48765. switch (this.operator) {
  48766. case ValueCondition.IsGreater:
  48767. return this._effectiveTarget[this._property] > this.value;
  48768. case ValueCondition.IsLesser:
  48769. return this._effectiveTarget[this._property] < this.value;
  48770. case ValueCondition.IsEqual:
  48771. case ValueCondition.IsDifferent:
  48772. var check;
  48773. if (this.value.equals) {
  48774. check = this.value.equals(this._effectiveTarget[this._property]);
  48775. }
  48776. else {
  48777. check = this.value === this._effectiveTarget[this._property];
  48778. }
  48779. return this.operator === ValueCondition.IsEqual ? check : !check;
  48780. }
  48781. return false;
  48782. };
  48783. ValueCondition.prototype.serialize = function () {
  48784. return this._serialize({
  48785. name: "ValueCondition",
  48786. properties: [
  48787. BABYLON.Action._GetTargetProperty(this._target),
  48788. { name: "propertyPath", value: this.propertyPath },
  48789. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48790. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  48791. ]
  48792. });
  48793. };
  48794. ValueCondition.GetOperatorName = function (operator) {
  48795. switch (operator) {
  48796. case ValueCondition._IsEqual: return "IsEqual";
  48797. case ValueCondition._IsDifferent: return "IsDifferent";
  48798. case ValueCondition._IsGreater: return "IsGreater";
  48799. case ValueCondition._IsLesser: return "IsLesser";
  48800. default: return "";
  48801. }
  48802. };
  48803. // Statics
  48804. ValueCondition._IsEqual = 0;
  48805. ValueCondition._IsDifferent = 1;
  48806. ValueCondition._IsGreater = 2;
  48807. ValueCondition._IsLesser = 3;
  48808. return ValueCondition;
  48809. }(Condition));
  48810. BABYLON.ValueCondition = ValueCondition;
  48811. var PredicateCondition = /** @class */ (function (_super) {
  48812. __extends(PredicateCondition, _super);
  48813. function PredicateCondition(actionManager, predicate) {
  48814. var _this = _super.call(this, actionManager) || this;
  48815. _this.predicate = predicate;
  48816. return _this;
  48817. }
  48818. PredicateCondition.prototype.isValid = function () {
  48819. return this.predicate();
  48820. };
  48821. return PredicateCondition;
  48822. }(Condition));
  48823. BABYLON.PredicateCondition = PredicateCondition;
  48824. var StateCondition = /** @class */ (function (_super) {
  48825. __extends(StateCondition, _super);
  48826. function StateCondition(actionManager, target, value) {
  48827. var _this = _super.call(this, actionManager) || this;
  48828. _this.value = value;
  48829. _this._target = target;
  48830. return _this;
  48831. }
  48832. // Methods
  48833. StateCondition.prototype.isValid = function () {
  48834. return this._target.state === this.value;
  48835. };
  48836. StateCondition.prototype.serialize = function () {
  48837. return this._serialize({
  48838. name: "StateCondition",
  48839. properties: [
  48840. BABYLON.Action._GetTargetProperty(this._target),
  48841. { name: "value", value: this.value }
  48842. ]
  48843. });
  48844. };
  48845. return StateCondition;
  48846. }(Condition));
  48847. BABYLON.StateCondition = StateCondition;
  48848. })(BABYLON || (BABYLON = {}));
  48849. //# sourceMappingURL=babylon.condition.js.map
  48850. "use strict";
  48851. var BABYLON;
  48852. (function (BABYLON) {
  48853. var Action = /** @class */ (function () {
  48854. function Action(triggerOptions, condition) {
  48855. this.triggerOptions = triggerOptions;
  48856. this.onBeforeExecuteObservable = new BABYLON.Observable();
  48857. if (triggerOptions.parameter) {
  48858. this.trigger = triggerOptions.trigger;
  48859. this._triggerParameter = triggerOptions.parameter;
  48860. }
  48861. else {
  48862. this.trigger = triggerOptions;
  48863. }
  48864. this._nextActiveAction = this;
  48865. this._condition = condition;
  48866. }
  48867. // Methods
  48868. Action.prototype._prepare = function () {
  48869. };
  48870. Action.prototype.getTriggerParameter = function () {
  48871. return this._triggerParameter;
  48872. };
  48873. Action.prototype._executeCurrent = function (evt) {
  48874. if (this._nextActiveAction._condition) {
  48875. var condition = this._nextActiveAction._condition;
  48876. var currentRenderId = this._actionManager.getScene().getRenderId();
  48877. // We cache the current evaluation for the current frame
  48878. if (condition._evaluationId === currentRenderId) {
  48879. if (!condition._currentResult) {
  48880. return;
  48881. }
  48882. }
  48883. else {
  48884. condition._evaluationId = currentRenderId;
  48885. if (!condition.isValid()) {
  48886. condition._currentResult = false;
  48887. return;
  48888. }
  48889. condition._currentResult = true;
  48890. }
  48891. }
  48892. this.onBeforeExecuteObservable.notifyObservers(this);
  48893. this._nextActiveAction.execute(evt);
  48894. this.skipToNextActiveAction();
  48895. };
  48896. Action.prototype.execute = function (evt) {
  48897. };
  48898. Action.prototype.skipToNextActiveAction = function () {
  48899. if (this._nextActiveAction._child) {
  48900. if (!this._nextActiveAction._child._actionManager) {
  48901. this._nextActiveAction._child._actionManager = this._actionManager;
  48902. }
  48903. this._nextActiveAction = this._nextActiveAction._child;
  48904. }
  48905. else {
  48906. this._nextActiveAction = this;
  48907. }
  48908. };
  48909. Action.prototype.then = function (action) {
  48910. this._child = action;
  48911. action._actionManager = this._actionManager;
  48912. action._prepare();
  48913. return action;
  48914. };
  48915. Action.prototype._getProperty = function (propertyPath) {
  48916. return this._actionManager._getProperty(propertyPath);
  48917. };
  48918. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  48919. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48920. };
  48921. Action.prototype.serialize = function (parent) {
  48922. };
  48923. // Called by BABYLON.Action objects in serialize(...). Internal use
  48924. Action.prototype._serialize = function (serializedAction, parent) {
  48925. var serializationObject = {
  48926. type: 1,
  48927. children: [],
  48928. name: serializedAction.name,
  48929. properties: serializedAction.properties || []
  48930. };
  48931. // Serialize child
  48932. if (this._child) {
  48933. this._child.serialize(serializationObject);
  48934. }
  48935. // Check if "this" has a condition
  48936. if (this._condition) {
  48937. var serializedCondition = this._condition.serialize();
  48938. serializedCondition.children.push(serializationObject);
  48939. if (parent) {
  48940. parent.children.push(serializedCondition);
  48941. }
  48942. return serializedCondition;
  48943. }
  48944. if (parent) {
  48945. parent.children.push(serializationObject);
  48946. }
  48947. return serializationObject;
  48948. };
  48949. Action._SerializeValueAsString = function (value) {
  48950. if (typeof value === "number") {
  48951. return value.toString();
  48952. }
  48953. if (typeof value === "boolean") {
  48954. return value ? "true" : "false";
  48955. }
  48956. if (value instanceof BABYLON.Vector2) {
  48957. return value.x + ", " + value.y;
  48958. }
  48959. if (value instanceof BABYLON.Vector3) {
  48960. return value.x + ", " + value.y + ", " + value.z;
  48961. }
  48962. if (value instanceof BABYLON.Color3) {
  48963. return value.r + ", " + value.g + ", " + value.b;
  48964. }
  48965. if (value instanceof BABYLON.Color4) {
  48966. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  48967. }
  48968. return value; // string
  48969. };
  48970. Action._GetTargetProperty = function (target) {
  48971. return {
  48972. name: "target",
  48973. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  48974. : target instanceof BABYLON.Light ? "LightProperties"
  48975. : target instanceof BABYLON.Camera ? "CameraProperties"
  48976. : "SceneProperties",
  48977. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  48978. };
  48979. };
  48980. return Action;
  48981. }());
  48982. BABYLON.Action = Action;
  48983. })(BABYLON || (BABYLON = {}));
  48984. //# sourceMappingURL=babylon.action.js.map
  48985. "use strict";
  48986. var BABYLON;
  48987. (function (BABYLON) {
  48988. /**
  48989. * ActionEvent is the event beint sent when an action is triggered.
  48990. */
  48991. var ActionEvent = /** @class */ (function () {
  48992. /**
  48993. * @param source The mesh or sprite that triggered the action.
  48994. * @param pointerX The X mouse cursor position at the time of the event
  48995. * @param pointerY The Y mouse cursor position at the time of the event
  48996. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  48997. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  48998. */
  48999. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  49000. this.source = source;
  49001. this.pointerX = pointerX;
  49002. this.pointerY = pointerY;
  49003. this.meshUnderPointer = meshUnderPointer;
  49004. this.sourceEvent = sourceEvent;
  49005. this.additionalData = additionalData;
  49006. }
  49007. /**
  49008. * Helper function to auto-create an ActionEvent from a source mesh.
  49009. * @param source The source mesh that triggered the event
  49010. * @param evt {Event} The original (browser) event
  49011. */
  49012. ActionEvent.CreateNew = function (source, evt, additionalData) {
  49013. var scene = source.getScene();
  49014. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  49015. };
  49016. /**
  49017. * Helper function to auto-create an ActionEvent from a source mesh.
  49018. * @param source The source sprite that triggered the event
  49019. * @param scene Scene associated with the sprite
  49020. * @param evt {Event} The original (browser) event
  49021. */
  49022. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  49023. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  49024. };
  49025. /**
  49026. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  49027. * @param scene the scene where the event occurred
  49028. * @param evt {Event} The original (browser) event
  49029. */
  49030. ActionEvent.CreateNewFromScene = function (scene, evt) {
  49031. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  49032. };
  49033. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  49034. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  49035. };
  49036. return ActionEvent;
  49037. }());
  49038. BABYLON.ActionEvent = ActionEvent;
  49039. /**
  49040. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  49041. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  49042. */
  49043. var ActionManager = /** @class */ (function () {
  49044. function ActionManager(scene) {
  49045. // Members
  49046. this.actions = new Array();
  49047. this.hoverCursor = '';
  49048. this._scene = scene;
  49049. scene._actionManagers.push(this);
  49050. }
  49051. Object.defineProperty(ActionManager, "NothingTrigger", {
  49052. get: function () {
  49053. return ActionManager._NothingTrigger;
  49054. },
  49055. enumerable: true,
  49056. configurable: true
  49057. });
  49058. Object.defineProperty(ActionManager, "OnPickTrigger", {
  49059. get: function () {
  49060. return ActionManager._OnPickTrigger;
  49061. },
  49062. enumerable: true,
  49063. configurable: true
  49064. });
  49065. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  49066. get: function () {
  49067. return ActionManager._OnLeftPickTrigger;
  49068. },
  49069. enumerable: true,
  49070. configurable: true
  49071. });
  49072. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  49073. get: function () {
  49074. return ActionManager._OnRightPickTrigger;
  49075. },
  49076. enumerable: true,
  49077. configurable: true
  49078. });
  49079. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  49080. get: function () {
  49081. return ActionManager._OnCenterPickTrigger;
  49082. },
  49083. enumerable: true,
  49084. configurable: true
  49085. });
  49086. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  49087. get: function () {
  49088. return ActionManager._OnPickDownTrigger;
  49089. },
  49090. enumerable: true,
  49091. configurable: true
  49092. });
  49093. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  49094. get: function () {
  49095. return ActionManager._OnDoublePickTrigger;
  49096. },
  49097. enumerable: true,
  49098. configurable: true
  49099. });
  49100. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  49101. get: function () {
  49102. return ActionManager._OnPickUpTrigger;
  49103. },
  49104. enumerable: true,
  49105. configurable: true
  49106. });
  49107. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  49108. /// This trigger will only be raised if you also declared a OnPickDown
  49109. get: function () {
  49110. return ActionManager._OnPickOutTrigger;
  49111. },
  49112. enumerable: true,
  49113. configurable: true
  49114. });
  49115. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  49116. get: function () {
  49117. return ActionManager._OnLongPressTrigger;
  49118. },
  49119. enumerable: true,
  49120. configurable: true
  49121. });
  49122. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  49123. get: function () {
  49124. return ActionManager._OnPointerOverTrigger;
  49125. },
  49126. enumerable: true,
  49127. configurable: true
  49128. });
  49129. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  49130. get: function () {
  49131. return ActionManager._OnPointerOutTrigger;
  49132. },
  49133. enumerable: true,
  49134. configurable: true
  49135. });
  49136. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  49137. get: function () {
  49138. return ActionManager._OnEveryFrameTrigger;
  49139. },
  49140. enumerable: true,
  49141. configurable: true
  49142. });
  49143. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  49144. get: function () {
  49145. return ActionManager._OnIntersectionEnterTrigger;
  49146. },
  49147. enumerable: true,
  49148. configurable: true
  49149. });
  49150. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  49151. get: function () {
  49152. return ActionManager._OnIntersectionExitTrigger;
  49153. },
  49154. enumerable: true,
  49155. configurable: true
  49156. });
  49157. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  49158. get: function () {
  49159. return ActionManager._OnKeyDownTrigger;
  49160. },
  49161. enumerable: true,
  49162. configurable: true
  49163. });
  49164. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  49165. get: function () {
  49166. return ActionManager._OnKeyUpTrigger;
  49167. },
  49168. enumerable: true,
  49169. configurable: true
  49170. });
  49171. // Methods
  49172. ActionManager.prototype.dispose = function () {
  49173. var index = this._scene._actionManagers.indexOf(this);
  49174. for (var i = 0; i < this.actions.length; i++) {
  49175. var action = this.actions[i];
  49176. ActionManager.Triggers[action.trigger]--;
  49177. if (ActionManager.Triggers[action.trigger] === 0) {
  49178. delete ActionManager.Triggers[action.trigger];
  49179. }
  49180. }
  49181. if (index > -1) {
  49182. this._scene._actionManagers.splice(index, 1);
  49183. }
  49184. };
  49185. ActionManager.prototype.getScene = function () {
  49186. return this._scene;
  49187. };
  49188. /**
  49189. * Does this action manager handles actions of any of the given triggers
  49190. * @param {number[]} triggers - the triggers to be tested
  49191. * @return {boolean} whether one (or more) of the triggers is handeled
  49192. */
  49193. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  49194. for (var index = 0; index < this.actions.length; index++) {
  49195. var action = this.actions[index];
  49196. if (triggers.indexOf(action.trigger) > -1) {
  49197. return true;
  49198. }
  49199. }
  49200. return false;
  49201. };
  49202. /**
  49203. * Does this action manager handles actions of a given trigger
  49204. * @param {number} trigger - the trigger to be tested
  49205. * @return {boolean} whether the trigger is handeled
  49206. */
  49207. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  49208. for (var index = 0; index < this.actions.length; index++) {
  49209. var action = this.actions[index];
  49210. if (action.trigger === trigger) {
  49211. return true;
  49212. }
  49213. }
  49214. return false;
  49215. };
  49216. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  49217. /**
  49218. * Does this action manager has pointer triggers
  49219. * @return {boolean} whether or not it has pointer triggers
  49220. */
  49221. get: function () {
  49222. for (var index = 0; index < this.actions.length; index++) {
  49223. var action = this.actions[index];
  49224. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  49225. return true;
  49226. }
  49227. }
  49228. return false;
  49229. },
  49230. enumerable: true,
  49231. configurable: true
  49232. });
  49233. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  49234. /**
  49235. * Does this action manager has pick triggers
  49236. * @return {boolean} whether or not it has pick triggers
  49237. */
  49238. get: function () {
  49239. for (var index = 0; index < this.actions.length; index++) {
  49240. var action = this.actions[index];
  49241. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  49242. return true;
  49243. }
  49244. }
  49245. return false;
  49246. },
  49247. enumerable: true,
  49248. configurable: true
  49249. });
  49250. Object.defineProperty(ActionManager, "HasTriggers", {
  49251. /**
  49252. * Does exist one action manager with at least one trigger
  49253. * @return {boolean} whether or not it exists one action manager with one trigger
  49254. **/
  49255. get: function () {
  49256. for (var t in ActionManager.Triggers) {
  49257. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49258. return true;
  49259. }
  49260. }
  49261. return false;
  49262. },
  49263. enumerable: true,
  49264. configurable: true
  49265. });
  49266. Object.defineProperty(ActionManager, "HasPickTriggers", {
  49267. /**
  49268. * Does exist one action manager with at least one pick trigger
  49269. * @return {boolean} whether or not it exists one action manager with one pick trigger
  49270. **/
  49271. get: function () {
  49272. for (var t in ActionManager.Triggers) {
  49273. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49274. var t_int = parseInt(t);
  49275. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  49276. return true;
  49277. }
  49278. }
  49279. }
  49280. return false;
  49281. },
  49282. enumerable: true,
  49283. configurable: true
  49284. });
  49285. /**
  49286. * Does exist one action manager that handles actions of a given trigger
  49287. * @param {number} trigger - the trigger to be tested
  49288. * @return {boolean} whether the trigger is handeled by at least one action manager
  49289. **/
  49290. ActionManager.HasSpecificTrigger = function (trigger) {
  49291. for (var t in ActionManager.Triggers) {
  49292. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49293. var t_int = parseInt(t);
  49294. if (t_int === trigger) {
  49295. return true;
  49296. }
  49297. }
  49298. }
  49299. return false;
  49300. };
  49301. /**
  49302. * Registers an action to this action manager
  49303. * @param {BABYLON.Action} action - the action to be registered
  49304. * @return {BABYLON.Action} the action amended (prepared) after registration
  49305. */
  49306. ActionManager.prototype.registerAction = function (action) {
  49307. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  49308. if (this.getScene().actionManager !== this) {
  49309. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  49310. return null;
  49311. }
  49312. }
  49313. this.actions.push(action);
  49314. if (ActionManager.Triggers[action.trigger]) {
  49315. ActionManager.Triggers[action.trigger]++;
  49316. }
  49317. else {
  49318. ActionManager.Triggers[action.trigger] = 1;
  49319. }
  49320. action._actionManager = this;
  49321. action._prepare();
  49322. return action;
  49323. };
  49324. /**
  49325. * Unregisters an action to this action manager
  49326. * @param action The action to be unregistered
  49327. * @return whether the action has been unregistered
  49328. */
  49329. ActionManager.prototype.unregisterAction = function (action) {
  49330. var index = this.actions.indexOf(action);
  49331. if (index !== -1) {
  49332. this.actions.splice(index, 1);
  49333. ActionManager.Triggers[action.trigger] -= 1;
  49334. if (ActionManager.Triggers[action.trigger] === 0) {
  49335. delete ActionManager.Triggers[action.trigger];
  49336. }
  49337. delete action._actionManager;
  49338. return true;
  49339. }
  49340. return false;
  49341. };
  49342. /**
  49343. * Process a specific trigger
  49344. * @param {number} trigger - the trigger to process
  49345. * @param evt {BABYLON.ActionEvent} the event details to be processed
  49346. */
  49347. ActionManager.prototype.processTrigger = function (trigger, evt) {
  49348. for (var index = 0; index < this.actions.length; index++) {
  49349. var action = this.actions[index];
  49350. if (action.trigger === trigger) {
  49351. if (evt) {
  49352. if (trigger === ActionManager.OnKeyUpTrigger
  49353. || trigger === ActionManager.OnKeyDownTrigger) {
  49354. var parameter = action.getTriggerParameter();
  49355. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  49356. if (!parameter.toLowerCase) {
  49357. continue;
  49358. }
  49359. var lowerCase = parameter.toLowerCase();
  49360. if (lowerCase !== evt.sourceEvent.key) {
  49361. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  49362. var actualkey = String.fromCharCode(unicode).toLowerCase();
  49363. if (actualkey !== lowerCase) {
  49364. continue;
  49365. }
  49366. }
  49367. }
  49368. }
  49369. }
  49370. action._executeCurrent(evt);
  49371. }
  49372. }
  49373. };
  49374. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  49375. var properties = propertyPath.split(".");
  49376. for (var index = 0; index < properties.length - 1; index++) {
  49377. target = target[properties[index]];
  49378. }
  49379. return target;
  49380. };
  49381. ActionManager.prototype._getProperty = function (propertyPath) {
  49382. var properties = propertyPath.split(".");
  49383. return properties[properties.length - 1];
  49384. };
  49385. ActionManager.prototype.serialize = function (name) {
  49386. var root = {
  49387. children: new Array(),
  49388. name: name,
  49389. type: 3,
  49390. properties: new Array() // Empty for root but required
  49391. };
  49392. for (var i = 0; i < this.actions.length; i++) {
  49393. var triggerObject = {
  49394. type: 0,
  49395. children: new Array(),
  49396. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  49397. properties: new Array()
  49398. };
  49399. var triggerOptions = this.actions[i].triggerOptions;
  49400. if (triggerOptions && typeof triggerOptions !== "number") {
  49401. if (triggerOptions.parameter instanceof BABYLON.Node) {
  49402. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  49403. }
  49404. else {
  49405. var parameter = {};
  49406. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  49407. if (triggerOptions.parameter.mesh) {
  49408. parameter._meshId = triggerOptions.parameter.mesh.id;
  49409. }
  49410. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  49411. }
  49412. }
  49413. // Serialize child action, recursively
  49414. this.actions[i].serialize(triggerObject);
  49415. // Add serialized trigger
  49416. root.children.push(triggerObject);
  49417. }
  49418. return root;
  49419. };
  49420. ActionManager.Parse = function (parsedActions, object, scene) {
  49421. var actionManager = new ActionManager(scene);
  49422. if (object === null)
  49423. scene.actionManager = actionManager;
  49424. else
  49425. object.actionManager = actionManager;
  49426. // instanciate a new object
  49427. var instanciate = function (name, params) {
  49428. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  49429. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  49430. newInstance.constructor.apply(newInstance, params);
  49431. return newInstance;
  49432. };
  49433. var parseParameter = function (name, value, target, propertyPath) {
  49434. if (propertyPath === null) {
  49435. // String, boolean or float
  49436. var floatValue = parseFloat(value);
  49437. if (value === "true" || value === "false")
  49438. return value === "true";
  49439. else
  49440. return isNaN(floatValue) ? value : floatValue;
  49441. }
  49442. var effectiveTarget = propertyPath.split(".");
  49443. var values = value.split(",");
  49444. // Get effective Target
  49445. for (var i = 0; i < effectiveTarget.length; i++) {
  49446. target = target[effectiveTarget[i]];
  49447. }
  49448. // Return appropriate value with its type
  49449. if (typeof (target) === "boolean")
  49450. return values[0] === "true";
  49451. if (typeof (target) === "string")
  49452. return values[0];
  49453. // Parameters with multiple values such as Vector3 etc.
  49454. var split = new Array();
  49455. for (var i = 0; i < values.length; i++)
  49456. split.push(parseFloat(values[i]));
  49457. if (target instanceof BABYLON.Vector3)
  49458. return BABYLON.Vector3.FromArray(split);
  49459. if (target instanceof BABYLON.Vector4)
  49460. return BABYLON.Vector4.FromArray(split);
  49461. if (target instanceof BABYLON.Color3)
  49462. return BABYLON.Color3.FromArray(split);
  49463. if (target instanceof BABYLON.Color4)
  49464. return BABYLON.Color4.FromArray(split);
  49465. return parseFloat(values[0]);
  49466. };
  49467. // traverse graph per trigger
  49468. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  49469. if (combineArray === void 0) { combineArray = null; }
  49470. if (parsedAction.detached)
  49471. return;
  49472. var parameters = new Array();
  49473. var target = null;
  49474. var propertyPath = null;
  49475. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  49476. // Parameters
  49477. if (parsedAction.type === 2)
  49478. parameters.push(actionManager);
  49479. else
  49480. parameters.push(trigger);
  49481. if (combine) {
  49482. var actions = new Array();
  49483. for (var j = 0; j < parsedAction.combine.length; j++) {
  49484. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  49485. }
  49486. parameters.push(actions);
  49487. }
  49488. else {
  49489. for (var i = 0; i < parsedAction.properties.length; i++) {
  49490. var value = parsedAction.properties[i].value;
  49491. var name = parsedAction.properties[i].name;
  49492. var targetType = parsedAction.properties[i].targetType;
  49493. if (name === "target")
  49494. if (targetType !== null && targetType === "SceneProperties")
  49495. value = target = scene;
  49496. else
  49497. value = target = scene.getNodeByName(value);
  49498. else if (name === "parent")
  49499. value = scene.getNodeByName(value);
  49500. else if (name === "sound")
  49501. value = scene.getSoundByName(value);
  49502. else if (name !== "propertyPath") {
  49503. if (parsedAction.type === 2 && name === "operator")
  49504. value = BABYLON.ValueCondition[value];
  49505. else
  49506. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  49507. }
  49508. else {
  49509. propertyPath = value;
  49510. }
  49511. parameters.push(value);
  49512. }
  49513. }
  49514. if (combineArray === null) {
  49515. parameters.push(condition);
  49516. }
  49517. else {
  49518. parameters.push(null);
  49519. }
  49520. // If interpolate value action
  49521. if (parsedAction.name === "InterpolateValueAction") {
  49522. var param = parameters[parameters.length - 2];
  49523. parameters[parameters.length - 1] = param;
  49524. parameters[parameters.length - 2] = condition;
  49525. }
  49526. // Action or condition(s) and not CombineAction
  49527. var newAction = instanciate(parsedAction.name, parameters);
  49528. if (newAction instanceof BABYLON.Condition && condition !== null) {
  49529. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  49530. if (action)
  49531. action.then(nothing);
  49532. else
  49533. actionManager.registerAction(nothing);
  49534. action = nothing;
  49535. }
  49536. if (combineArray === null) {
  49537. if (newAction instanceof BABYLON.Condition) {
  49538. condition = newAction;
  49539. newAction = action;
  49540. }
  49541. else {
  49542. condition = null;
  49543. if (action)
  49544. action.then(newAction);
  49545. else
  49546. actionManager.registerAction(newAction);
  49547. }
  49548. }
  49549. else {
  49550. combineArray.push(newAction);
  49551. }
  49552. for (var i = 0; i < parsedAction.children.length; i++)
  49553. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  49554. };
  49555. // triggers
  49556. for (var i = 0; i < parsedActions.children.length; i++) {
  49557. var triggerParams;
  49558. var trigger = parsedActions.children[i];
  49559. if (trigger.properties.length > 0) {
  49560. var param = trigger.properties[0].value;
  49561. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  49562. if (value._meshId) {
  49563. value.mesh = scene.getMeshByID(value._meshId);
  49564. }
  49565. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  49566. }
  49567. else
  49568. triggerParams = ActionManager[trigger.name];
  49569. for (var j = 0; j < trigger.children.length; j++) {
  49570. if (!trigger.detached)
  49571. traverse(trigger.children[j], triggerParams, null, null);
  49572. }
  49573. }
  49574. };
  49575. ActionManager.GetTriggerName = function (trigger) {
  49576. switch (trigger) {
  49577. case 0: return "NothingTrigger";
  49578. case 1: return "OnPickTrigger";
  49579. case 2: return "OnLeftPickTrigger";
  49580. case 3: return "OnRightPickTrigger";
  49581. case 4: return "OnCenterPickTrigger";
  49582. case 5: return "OnPickDownTrigger";
  49583. case 6: return "OnPickUpTrigger";
  49584. case 7: return "OnLongPressTrigger";
  49585. case 8: return "OnPointerOverTrigger";
  49586. case 9: return "OnPointerOutTrigger";
  49587. case 10: return "OnEveryFrameTrigger";
  49588. case 11: return "OnIntersectionEnterTrigger";
  49589. case 12: return "OnIntersectionExitTrigger";
  49590. case 13: return "OnKeyDownTrigger";
  49591. case 14: return "OnKeyUpTrigger";
  49592. case 15: return "OnPickOutTrigger";
  49593. default: return "";
  49594. }
  49595. };
  49596. // Statics
  49597. ActionManager._NothingTrigger = 0;
  49598. ActionManager._OnPickTrigger = 1;
  49599. ActionManager._OnLeftPickTrigger = 2;
  49600. ActionManager._OnRightPickTrigger = 3;
  49601. ActionManager._OnCenterPickTrigger = 4;
  49602. ActionManager._OnPickDownTrigger = 5;
  49603. ActionManager._OnDoublePickTrigger = 6;
  49604. ActionManager._OnPickUpTrigger = 7;
  49605. ActionManager._OnLongPressTrigger = 8;
  49606. ActionManager._OnPointerOverTrigger = 9;
  49607. ActionManager._OnPointerOutTrigger = 10;
  49608. ActionManager._OnEveryFrameTrigger = 11;
  49609. ActionManager._OnIntersectionEnterTrigger = 12;
  49610. ActionManager._OnIntersectionExitTrigger = 13;
  49611. ActionManager._OnKeyDownTrigger = 14;
  49612. ActionManager._OnKeyUpTrigger = 15;
  49613. ActionManager._OnPickOutTrigger = 16;
  49614. ActionManager.Triggers = {};
  49615. return ActionManager;
  49616. }());
  49617. BABYLON.ActionManager = ActionManager;
  49618. })(BABYLON || (BABYLON = {}));
  49619. //# sourceMappingURL=babylon.actionManager.js.map
  49620. "use strict";
  49621. var BABYLON;
  49622. (function (BABYLON) {
  49623. var InterpolateValueAction = /** @class */ (function (_super) {
  49624. __extends(InterpolateValueAction, _super);
  49625. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  49626. if (duration === void 0) { duration = 1000; }
  49627. var _this = _super.call(this, triggerOptions, condition) || this;
  49628. _this.propertyPath = propertyPath;
  49629. _this.value = value;
  49630. _this.duration = duration;
  49631. _this.stopOtherAnimations = stopOtherAnimations;
  49632. _this.onInterpolationDone = onInterpolationDone;
  49633. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  49634. _this._target = _this._effectiveTarget = target;
  49635. return _this;
  49636. }
  49637. InterpolateValueAction.prototype._prepare = function () {
  49638. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49639. this._property = this._getProperty(this.propertyPath);
  49640. };
  49641. InterpolateValueAction.prototype.execute = function () {
  49642. var _this = this;
  49643. var scene = this._actionManager.getScene();
  49644. var keys = [
  49645. {
  49646. frame: 0,
  49647. value: this._effectiveTarget[this._property]
  49648. }, {
  49649. frame: 100,
  49650. value: this.value
  49651. }
  49652. ];
  49653. var dataType;
  49654. if (typeof this.value === "number") {
  49655. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  49656. }
  49657. else if (this.value instanceof BABYLON.Color3) {
  49658. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  49659. }
  49660. else if (this.value instanceof BABYLON.Vector3) {
  49661. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  49662. }
  49663. else if (this.value instanceof BABYLON.Matrix) {
  49664. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  49665. }
  49666. else if (this.value instanceof BABYLON.Quaternion) {
  49667. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  49668. }
  49669. else {
  49670. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  49671. return;
  49672. }
  49673. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  49674. animation.setKeys(keys);
  49675. if (this.stopOtherAnimations) {
  49676. scene.stopAnimation(this._effectiveTarget);
  49677. }
  49678. var wrapper = function () {
  49679. _this.onInterpolationDoneObservable.notifyObservers(_this);
  49680. if (_this.onInterpolationDone) {
  49681. _this.onInterpolationDone();
  49682. }
  49683. };
  49684. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  49685. };
  49686. InterpolateValueAction.prototype.serialize = function (parent) {
  49687. return _super.prototype._serialize.call(this, {
  49688. name: "InterpolateValueAction",
  49689. properties: [
  49690. BABYLON.Action._GetTargetProperty(this._target),
  49691. { name: "propertyPath", value: this.propertyPath },
  49692. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  49693. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  49694. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  49695. ]
  49696. }, parent);
  49697. };
  49698. return InterpolateValueAction;
  49699. }(BABYLON.Action));
  49700. BABYLON.InterpolateValueAction = InterpolateValueAction;
  49701. })(BABYLON || (BABYLON = {}));
  49702. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  49703. "use strict";
  49704. var BABYLON;
  49705. (function (BABYLON) {
  49706. var SwitchBooleanAction = /** @class */ (function (_super) {
  49707. __extends(SwitchBooleanAction, _super);
  49708. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  49709. var _this = _super.call(this, triggerOptions, condition) || this;
  49710. _this.propertyPath = propertyPath;
  49711. _this._target = _this._effectiveTarget = target;
  49712. return _this;
  49713. }
  49714. SwitchBooleanAction.prototype._prepare = function () {
  49715. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49716. this._property = this._getProperty(this.propertyPath);
  49717. };
  49718. SwitchBooleanAction.prototype.execute = function () {
  49719. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  49720. };
  49721. SwitchBooleanAction.prototype.serialize = function (parent) {
  49722. return _super.prototype._serialize.call(this, {
  49723. name: "SwitchBooleanAction",
  49724. properties: [
  49725. BABYLON.Action._GetTargetProperty(this._target),
  49726. { name: "propertyPath", value: this.propertyPath }
  49727. ]
  49728. }, parent);
  49729. };
  49730. return SwitchBooleanAction;
  49731. }(BABYLON.Action));
  49732. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  49733. var SetStateAction = /** @class */ (function (_super) {
  49734. __extends(SetStateAction, _super);
  49735. function SetStateAction(triggerOptions, target, value, condition) {
  49736. var _this = _super.call(this, triggerOptions, condition) || this;
  49737. _this.value = value;
  49738. _this._target = target;
  49739. return _this;
  49740. }
  49741. SetStateAction.prototype.execute = function () {
  49742. this._target.state = this.value;
  49743. };
  49744. SetStateAction.prototype.serialize = function (parent) {
  49745. return _super.prototype._serialize.call(this, {
  49746. name: "SetStateAction",
  49747. properties: [
  49748. BABYLON.Action._GetTargetProperty(this._target),
  49749. { name: "value", value: this.value }
  49750. ]
  49751. }, parent);
  49752. };
  49753. return SetStateAction;
  49754. }(BABYLON.Action));
  49755. BABYLON.SetStateAction = SetStateAction;
  49756. var SetValueAction = /** @class */ (function (_super) {
  49757. __extends(SetValueAction, _super);
  49758. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  49759. var _this = _super.call(this, triggerOptions, condition) || this;
  49760. _this.propertyPath = propertyPath;
  49761. _this.value = value;
  49762. _this._target = _this._effectiveTarget = target;
  49763. return _this;
  49764. }
  49765. SetValueAction.prototype._prepare = function () {
  49766. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49767. this._property = this._getProperty(this.propertyPath);
  49768. };
  49769. SetValueAction.prototype.execute = function () {
  49770. this._effectiveTarget[this._property] = this.value;
  49771. if (this._target.markAsDirty) {
  49772. this._target.markAsDirty(this._property);
  49773. }
  49774. };
  49775. SetValueAction.prototype.serialize = function (parent) {
  49776. return _super.prototype._serialize.call(this, {
  49777. name: "SetValueAction",
  49778. properties: [
  49779. BABYLON.Action._GetTargetProperty(this._target),
  49780. { name: "propertyPath", value: this.propertyPath },
  49781. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49782. ]
  49783. }, parent);
  49784. };
  49785. return SetValueAction;
  49786. }(BABYLON.Action));
  49787. BABYLON.SetValueAction = SetValueAction;
  49788. var IncrementValueAction = /** @class */ (function (_super) {
  49789. __extends(IncrementValueAction, _super);
  49790. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  49791. var _this = _super.call(this, triggerOptions, condition) || this;
  49792. _this.propertyPath = propertyPath;
  49793. _this.value = value;
  49794. _this._target = _this._effectiveTarget = target;
  49795. return _this;
  49796. }
  49797. IncrementValueAction.prototype._prepare = function () {
  49798. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49799. this._property = this._getProperty(this.propertyPath);
  49800. if (typeof this._effectiveTarget[this._property] !== "number") {
  49801. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  49802. }
  49803. };
  49804. IncrementValueAction.prototype.execute = function () {
  49805. this._effectiveTarget[this._property] += this.value;
  49806. if (this._target.markAsDirty) {
  49807. this._target.markAsDirty(this._property);
  49808. }
  49809. };
  49810. IncrementValueAction.prototype.serialize = function (parent) {
  49811. return _super.prototype._serialize.call(this, {
  49812. name: "IncrementValueAction",
  49813. properties: [
  49814. BABYLON.Action._GetTargetProperty(this._target),
  49815. { name: "propertyPath", value: this.propertyPath },
  49816. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49817. ]
  49818. }, parent);
  49819. };
  49820. return IncrementValueAction;
  49821. }(BABYLON.Action));
  49822. BABYLON.IncrementValueAction = IncrementValueAction;
  49823. var PlayAnimationAction = /** @class */ (function (_super) {
  49824. __extends(PlayAnimationAction, _super);
  49825. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  49826. var _this = _super.call(this, triggerOptions, condition) || this;
  49827. _this.from = from;
  49828. _this.to = to;
  49829. _this.loop = loop;
  49830. _this._target = target;
  49831. return _this;
  49832. }
  49833. PlayAnimationAction.prototype._prepare = function () {
  49834. };
  49835. PlayAnimationAction.prototype.execute = function () {
  49836. var scene = this._actionManager.getScene();
  49837. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  49838. };
  49839. PlayAnimationAction.prototype.serialize = function (parent) {
  49840. return _super.prototype._serialize.call(this, {
  49841. name: "PlayAnimationAction",
  49842. properties: [
  49843. BABYLON.Action._GetTargetProperty(this._target),
  49844. { name: "from", value: String(this.from) },
  49845. { name: "to", value: String(this.to) },
  49846. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  49847. ]
  49848. }, parent);
  49849. };
  49850. return PlayAnimationAction;
  49851. }(BABYLON.Action));
  49852. BABYLON.PlayAnimationAction = PlayAnimationAction;
  49853. var StopAnimationAction = /** @class */ (function (_super) {
  49854. __extends(StopAnimationAction, _super);
  49855. function StopAnimationAction(triggerOptions, target, condition) {
  49856. var _this = _super.call(this, triggerOptions, condition) || this;
  49857. _this._target = target;
  49858. return _this;
  49859. }
  49860. StopAnimationAction.prototype._prepare = function () {
  49861. };
  49862. StopAnimationAction.prototype.execute = function () {
  49863. var scene = this._actionManager.getScene();
  49864. scene.stopAnimation(this._target);
  49865. };
  49866. StopAnimationAction.prototype.serialize = function (parent) {
  49867. return _super.prototype._serialize.call(this, {
  49868. name: "StopAnimationAction",
  49869. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  49870. }, parent);
  49871. };
  49872. return StopAnimationAction;
  49873. }(BABYLON.Action));
  49874. BABYLON.StopAnimationAction = StopAnimationAction;
  49875. var DoNothingAction = /** @class */ (function (_super) {
  49876. __extends(DoNothingAction, _super);
  49877. function DoNothingAction(triggerOptions, condition) {
  49878. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  49879. return _super.call(this, triggerOptions, condition) || this;
  49880. }
  49881. DoNothingAction.prototype.execute = function () {
  49882. };
  49883. DoNothingAction.prototype.serialize = function (parent) {
  49884. return _super.prototype._serialize.call(this, {
  49885. name: "DoNothingAction",
  49886. properties: []
  49887. }, parent);
  49888. };
  49889. return DoNothingAction;
  49890. }(BABYLON.Action));
  49891. BABYLON.DoNothingAction = DoNothingAction;
  49892. var CombineAction = /** @class */ (function (_super) {
  49893. __extends(CombineAction, _super);
  49894. function CombineAction(triggerOptions, children, condition) {
  49895. var _this = _super.call(this, triggerOptions, condition) || this;
  49896. _this.children = children;
  49897. return _this;
  49898. }
  49899. CombineAction.prototype._prepare = function () {
  49900. for (var index = 0; index < this.children.length; index++) {
  49901. this.children[index]._actionManager = this._actionManager;
  49902. this.children[index]._prepare();
  49903. }
  49904. };
  49905. CombineAction.prototype.execute = function (evt) {
  49906. for (var index = 0; index < this.children.length; index++) {
  49907. this.children[index].execute(evt);
  49908. }
  49909. };
  49910. CombineAction.prototype.serialize = function (parent) {
  49911. var serializationObject = _super.prototype._serialize.call(this, {
  49912. name: "CombineAction",
  49913. properties: [],
  49914. combine: []
  49915. }, parent);
  49916. for (var i = 0; i < this.children.length; i++) {
  49917. serializationObject.combine.push(this.children[i].serialize(null));
  49918. }
  49919. return serializationObject;
  49920. };
  49921. return CombineAction;
  49922. }(BABYLON.Action));
  49923. BABYLON.CombineAction = CombineAction;
  49924. var ExecuteCodeAction = /** @class */ (function (_super) {
  49925. __extends(ExecuteCodeAction, _super);
  49926. function ExecuteCodeAction(triggerOptions, func, condition) {
  49927. var _this = _super.call(this, triggerOptions, condition) || this;
  49928. _this.func = func;
  49929. return _this;
  49930. }
  49931. ExecuteCodeAction.prototype.execute = function (evt) {
  49932. this.func(evt);
  49933. };
  49934. return ExecuteCodeAction;
  49935. }(BABYLON.Action));
  49936. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  49937. var SetParentAction = /** @class */ (function (_super) {
  49938. __extends(SetParentAction, _super);
  49939. function SetParentAction(triggerOptions, target, parent, condition) {
  49940. var _this = _super.call(this, triggerOptions, condition) || this;
  49941. _this._target = target;
  49942. _this._parent = parent;
  49943. return _this;
  49944. }
  49945. SetParentAction.prototype._prepare = function () {
  49946. };
  49947. SetParentAction.prototype.execute = function () {
  49948. if (this._target.parent === this._parent) {
  49949. return;
  49950. }
  49951. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  49952. invertParentWorldMatrix.invert();
  49953. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  49954. this._target.parent = this._parent;
  49955. };
  49956. SetParentAction.prototype.serialize = function (parent) {
  49957. return _super.prototype._serialize.call(this, {
  49958. name: "SetParentAction",
  49959. properties: [
  49960. BABYLON.Action._GetTargetProperty(this._target),
  49961. BABYLON.Action._GetTargetProperty(this._parent),
  49962. ]
  49963. }, parent);
  49964. };
  49965. return SetParentAction;
  49966. }(BABYLON.Action));
  49967. BABYLON.SetParentAction = SetParentAction;
  49968. var PlaySoundAction = /** @class */ (function (_super) {
  49969. __extends(PlaySoundAction, _super);
  49970. function PlaySoundAction(triggerOptions, sound, condition) {
  49971. var _this = _super.call(this, triggerOptions, condition) || this;
  49972. _this._sound = sound;
  49973. return _this;
  49974. }
  49975. PlaySoundAction.prototype._prepare = function () {
  49976. };
  49977. PlaySoundAction.prototype.execute = function () {
  49978. if (this._sound !== undefined)
  49979. this._sound.play();
  49980. };
  49981. PlaySoundAction.prototype.serialize = function (parent) {
  49982. return _super.prototype._serialize.call(this, {
  49983. name: "PlaySoundAction",
  49984. properties: [{ name: "sound", value: this._sound.name }]
  49985. }, parent);
  49986. };
  49987. return PlaySoundAction;
  49988. }(BABYLON.Action));
  49989. BABYLON.PlaySoundAction = PlaySoundAction;
  49990. var StopSoundAction = /** @class */ (function (_super) {
  49991. __extends(StopSoundAction, _super);
  49992. function StopSoundAction(triggerOptions, sound, condition) {
  49993. var _this = _super.call(this, triggerOptions, condition) || this;
  49994. _this._sound = sound;
  49995. return _this;
  49996. }
  49997. StopSoundAction.prototype._prepare = function () {
  49998. };
  49999. StopSoundAction.prototype.execute = function () {
  50000. if (this._sound !== undefined)
  50001. this._sound.stop();
  50002. };
  50003. StopSoundAction.prototype.serialize = function (parent) {
  50004. return _super.prototype._serialize.call(this, {
  50005. name: "StopSoundAction",
  50006. properties: [{ name: "sound", value: this._sound.name }]
  50007. }, parent);
  50008. };
  50009. return StopSoundAction;
  50010. }(BABYLON.Action));
  50011. BABYLON.StopSoundAction = StopSoundAction;
  50012. })(BABYLON || (BABYLON = {}));
  50013. //# sourceMappingURL=babylon.directActions.js.map
  50014. "use strict";
  50015. var BABYLON;
  50016. (function (BABYLON) {
  50017. var SpriteManager = /** @class */ (function () {
  50018. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  50019. if (epsilon === void 0) { epsilon = 0.01; }
  50020. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50021. this.name = name;
  50022. this.sprites = new Array();
  50023. this.renderingGroupId = 0;
  50024. this.layerMask = 0x0FFFFFFF;
  50025. this.fogEnabled = true;
  50026. this.isPickable = false;
  50027. /**
  50028. * An event triggered when the manager is disposed.
  50029. * @type {BABYLON.Observable}
  50030. */
  50031. this.onDisposeObservable = new BABYLON.Observable();
  50032. this._vertexBuffers = {};
  50033. this._capacity = capacity;
  50034. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  50035. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50036. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50037. if (cellSize.width && cellSize.height) {
  50038. this.cellWidth = cellSize.width;
  50039. this.cellHeight = cellSize.height;
  50040. }
  50041. else if (cellSize !== undefined) {
  50042. this.cellWidth = cellSize;
  50043. this.cellHeight = cellSize;
  50044. }
  50045. else {
  50046. return;
  50047. }
  50048. this._epsilon = epsilon;
  50049. this._scene = scene;
  50050. this._scene.spriteManagers.push(this);
  50051. var indices = [];
  50052. var index = 0;
  50053. for (var count = 0; count < capacity; count++) {
  50054. indices.push(index);
  50055. indices.push(index + 1);
  50056. indices.push(index + 2);
  50057. indices.push(index);
  50058. indices.push(index + 2);
  50059. indices.push(index + 3);
  50060. index += 4;
  50061. }
  50062. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  50063. // VBO
  50064. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  50065. this._vertexData = new Float32Array(capacity * 16 * 4);
  50066. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  50067. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  50068. var options = this._buffer.createVertexBuffer("options", 4, 4);
  50069. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  50070. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  50071. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50072. this._vertexBuffers["options"] = options;
  50073. this._vertexBuffers["cellInfo"] = cellInfo;
  50074. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50075. // Effects
  50076. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  50077. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  50078. }
  50079. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  50080. set: function (callback) {
  50081. if (this._onDisposeObserver) {
  50082. this.onDisposeObservable.remove(this._onDisposeObserver);
  50083. }
  50084. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50085. },
  50086. enumerable: true,
  50087. configurable: true
  50088. });
  50089. Object.defineProperty(SpriteManager.prototype, "texture", {
  50090. get: function () {
  50091. return this._spriteTexture;
  50092. },
  50093. set: function (value) {
  50094. this._spriteTexture = value;
  50095. },
  50096. enumerable: true,
  50097. configurable: true
  50098. });
  50099. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  50100. var arrayOffset = index * 16;
  50101. if (offsetX === 0)
  50102. offsetX = this._epsilon;
  50103. else if (offsetX === 1)
  50104. offsetX = 1 - this._epsilon;
  50105. if (offsetY === 0)
  50106. offsetY = this._epsilon;
  50107. else if (offsetY === 1)
  50108. offsetY = 1 - this._epsilon;
  50109. this._vertexData[arrayOffset] = sprite.position.x;
  50110. this._vertexData[arrayOffset + 1] = sprite.position.y;
  50111. this._vertexData[arrayOffset + 2] = sprite.position.z;
  50112. this._vertexData[arrayOffset + 3] = sprite.angle;
  50113. this._vertexData[arrayOffset + 4] = sprite.width;
  50114. this._vertexData[arrayOffset + 5] = sprite.height;
  50115. this._vertexData[arrayOffset + 6] = offsetX;
  50116. this._vertexData[arrayOffset + 7] = offsetY;
  50117. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  50118. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  50119. var offset = (sprite.cellIndex / rowSize) >> 0;
  50120. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  50121. this._vertexData[arrayOffset + 11] = offset;
  50122. // Color
  50123. this._vertexData[arrayOffset + 12] = sprite.color.r;
  50124. this._vertexData[arrayOffset + 13] = sprite.color.g;
  50125. this._vertexData[arrayOffset + 14] = sprite.color.b;
  50126. this._vertexData[arrayOffset + 15] = sprite.color.a;
  50127. };
  50128. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  50129. var count = Math.min(this._capacity, this.sprites.length);
  50130. var min = BABYLON.Vector3.Zero();
  50131. var max = BABYLON.Vector3.Zero();
  50132. var distance = Number.MAX_VALUE;
  50133. var currentSprite = null;
  50134. var cameraSpacePosition = BABYLON.Vector3.Zero();
  50135. var cameraView = camera.getViewMatrix();
  50136. for (var index = 0; index < count; index++) {
  50137. var sprite = this.sprites[index];
  50138. if (!sprite) {
  50139. continue;
  50140. }
  50141. if (predicate) {
  50142. if (!predicate(sprite)) {
  50143. continue;
  50144. }
  50145. }
  50146. else if (!sprite.isPickable) {
  50147. continue;
  50148. }
  50149. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  50150. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  50151. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  50152. if (ray.intersectsBoxMinMax(min, max)) {
  50153. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  50154. if (distance > currentDistance) {
  50155. distance = currentDistance;
  50156. currentSprite = sprite;
  50157. if (fastCheck) {
  50158. break;
  50159. }
  50160. }
  50161. }
  50162. }
  50163. if (currentSprite) {
  50164. var result = new BABYLON.PickingInfo();
  50165. result.hit = true;
  50166. result.pickedSprite = currentSprite;
  50167. result.distance = distance;
  50168. return result;
  50169. }
  50170. return null;
  50171. };
  50172. SpriteManager.prototype.render = function () {
  50173. // Check
  50174. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  50175. return;
  50176. var engine = this._scene.getEngine();
  50177. var baseSize = this._spriteTexture.getBaseSize();
  50178. // Sprites
  50179. var deltaTime = engine.getDeltaTime();
  50180. var max = Math.min(this._capacity, this.sprites.length);
  50181. var rowSize = baseSize.width / this.cellWidth;
  50182. var offset = 0;
  50183. for (var index = 0; index < max; index++) {
  50184. var sprite = this.sprites[index];
  50185. if (!sprite) {
  50186. continue;
  50187. }
  50188. sprite._animate(deltaTime);
  50189. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  50190. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  50191. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  50192. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  50193. }
  50194. this._buffer.update(this._vertexData);
  50195. // Render
  50196. var effect = this._effectBase;
  50197. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50198. effect = this._effectFog;
  50199. }
  50200. engine.enableEffect(effect);
  50201. var viewMatrix = this._scene.getViewMatrix();
  50202. effect.setTexture("diffuseSampler", this._spriteTexture);
  50203. effect.setMatrix("view", viewMatrix);
  50204. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  50205. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  50206. // Fog
  50207. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50208. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  50209. effect.setColor3("vFogColor", this._scene.fogColor);
  50210. }
  50211. // VBOs
  50212. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  50213. // Draw order
  50214. engine.setDepthFunctionToLessOrEqual();
  50215. effect.setBool("alphaTest", true);
  50216. engine.setColorWrite(false);
  50217. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50218. engine.setColorWrite(true);
  50219. effect.setBool("alphaTest", false);
  50220. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50221. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50222. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50223. };
  50224. SpriteManager.prototype.dispose = function () {
  50225. if (this._buffer) {
  50226. this._buffer.dispose();
  50227. this._buffer = null;
  50228. }
  50229. if (this._indexBuffer) {
  50230. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50231. this._indexBuffer = null;
  50232. }
  50233. if (this._spriteTexture) {
  50234. this._spriteTexture.dispose();
  50235. this._spriteTexture = null;
  50236. }
  50237. // Remove from scene
  50238. var index = this._scene.spriteManagers.indexOf(this);
  50239. this._scene.spriteManagers.splice(index, 1);
  50240. // Callback
  50241. this.onDisposeObservable.notifyObservers(this);
  50242. this.onDisposeObservable.clear();
  50243. };
  50244. return SpriteManager;
  50245. }());
  50246. BABYLON.SpriteManager = SpriteManager;
  50247. })(BABYLON || (BABYLON = {}));
  50248. //# sourceMappingURL=babylon.spriteManager.js.map
  50249. "use strict";
  50250. var BABYLON;
  50251. (function (BABYLON) {
  50252. var Sprite = /** @class */ (function () {
  50253. function Sprite(name, manager) {
  50254. this.name = name;
  50255. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50256. this.width = 1.0;
  50257. this.height = 1.0;
  50258. this.angle = 0;
  50259. this.cellIndex = 0;
  50260. this.invertU = 0;
  50261. this.invertV = 0;
  50262. this.animations = new Array();
  50263. this.isPickable = false;
  50264. this._animationStarted = false;
  50265. this._loopAnimation = false;
  50266. this._fromIndex = 0;
  50267. this._toIndex = 0;
  50268. this._delay = 0;
  50269. this._direction = 1;
  50270. this._time = 0;
  50271. this._manager = manager;
  50272. this._manager.sprites.push(this);
  50273. this.position = BABYLON.Vector3.Zero();
  50274. }
  50275. Object.defineProperty(Sprite.prototype, "size", {
  50276. get: function () {
  50277. return this.width;
  50278. },
  50279. set: function (value) {
  50280. this.width = value;
  50281. this.height = value;
  50282. },
  50283. enumerable: true,
  50284. configurable: true
  50285. });
  50286. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  50287. this._fromIndex = from;
  50288. this._toIndex = to;
  50289. this._loopAnimation = loop;
  50290. this._delay = delay;
  50291. this._animationStarted = true;
  50292. this._direction = from < to ? 1 : -1;
  50293. this.cellIndex = from;
  50294. this._time = 0;
  50295. this._onAnimationEnd = onAnimationEnd;
  50296. };
  50297. Sprite.prototype.stopAnimation = function () {
  50298. this._animationStarted = false;
  50299. };
  50300. Sprite.prototype._animate = function (deltaTime) {
  50301. if (!this._animationStarted)
  50302. return;
  50303. this._time += deltaTime;
  50304. if (this._time > this._delay) {
  50305. this._time = this._time % this._delay;
  50306. this.cellIndex += this._direction;
  50307. if (this.cellIndex > this._toIndex) {
  50308. if (this._loopAnimation) {
  50309. this.cellIndex = this._fromIndex;
  50310. }
  50311. else {
  50312. this.cellIndex = this._toIndex;
  50313. this._animationStarted = false;
  50314. if (this._onAnimationEnd) {
  50315. this._onAnimationEnd();
  50316. }
  50317. if (this.disposeWhenFinishedAnimating) {
  50318. this.dispose();
  50319. }
  50320. }
  50321. }
  50322. }
  50323. };
  50324. Sprite.prototype.dispose = function () {
  50325. for (var i = 0; i < this._manager.sprites.length; i++) {
  50326. if (this._manager.sprites[i] == this) {
  50327. this._manager.sprites.splice(i, 1);
  50328. }
  50329. }
  50330. };
  50331. return Sprite;
  50332. }());
  50333. BABYLON.Sprite = Sprite;
  50334. })(BABYLON || (BABYLON = {}));
  50335. //# sourceMappingURL=babylon.sprite.js.map
  50336. "use strict";
  50337. var BABYLON;
  50338. (function (BABYLON) {
  50339. var IntersectionInfo = /** @class */ (function () {
  50340. function IntersectionInfo(bu, bv, distance) {
  50341. this.bu = bu;
  50342. this.bv = bv;
  50343. this.distance = distance;
  50344. this.faceId = 0;
  50345. this.subMeshId = 0;
  50346. }
  50347. return IntersectionInfo;
  50348. }());
  50349. BABYLON.IntersectionInfo = IntersectionInfo;
  50350. var PickingInfo = /** @class */ (function () {
  50351. function PickingInfo() {
  50352. this.hit = false;
  50353. this.distance = 0;
  50354. this.pickedPoint = null;
  50355. this.pickedMesh = null;
  50356. this.bu = 0;
  50357. this.bv = 0;
  50358. this.faceId = -1;
  50359. this.subMeshId = 0;
  50360. this.pickedSprite = null;
  50361. }
  50362. // Methods
  50363. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  50364. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  50365. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  50366. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  50367. return null;
  50368. }
  50369. var indices = this.pickedMesh.getIndices();
  50370. if (!indices) {
  50371. return null;
  50372. }
  50373. var result;
  50374. if (useVerticesNormals) {
  50375. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50376. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  50377. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  50378. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  50379. normal0 = normal0.scale(this.bu);
  50380. normal1 = normal1.scale(this.bv);
  50381. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  50382. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  50383. }
  50384. else {
  50385. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50386. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  50387. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  50388. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  50389. var p1p2 = vertex1.subtract(vertex2);
  50390. var p3p2 = vertex3.subtract(vertex2);
  50391. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  50392. }
  50393. if (useWorldCoordinates) {
  50394. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  50395. }
  50396. return BABYLON.Vector3.Normalize(result);
  50397. };
  50398. PickingInfo.prototype.getTextureCoordinates = function () {
  50399. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50400. return null;
  50401. }
  50402. var indices = this.pickedMesh.getIndices();
  50403. if (!indices) {
  50404. return null;
  50405. }
  50406. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50407. if (!uvs) {
  50408. return null;
  50409. }
  50410. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  50411. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  50412. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  50413. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  50414. uv1 = uv1.scale(this.bu);
  50415. uv2 = uv2.scale(this.bv);
  50416. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  50417. };
  50418. return PickingInfo;
  50419. }());
  50420. BABYLON.PickingInfo = PickingInfo;
  50421. })(BABYLON || (BABYLON = {}));
  50422. //# sourceMappingURL=babylon.pickingInfo.js.map
  50423. "use strict";
  50424. var BABYLON;
  50425. (function (BABYLON) {
  50426. var Ray = /** @class */ (function () {
  50427. function Ray(origin, direction, length) {
  50428. if (length === void 0) { length = Number.MAX_VALUE; }
  50429. this.origin = origin;
  50430. this.direction = direction;
  50431. this.length = length;
  50432. }
  50433. // Methods
  50434. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  50435. var d = 0.0;
  50436. var maxValue = Number.MAX_VALUE;
  50437. var inv;
  50438. var min;
  50439. var max;
  50440. var temp;
  50441. if (Math.abs(this.direction.x) < 0.0000001) {
  50442. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  50443. return false;
  50444. }
  50445. }
  50446. else {
  50447. inv = 1.0 / this.direction.x;
  50448. min = (minimum.x - this.origin.x) * inv;
  50449. max = (maximum.x - this.origin.x) * inv;
  50450. if (max === -Infinity) {
  50451. max = Infinity;
  50452. }
  50453. if (min > max) {
  50454. temp = min;
  50455. min = max;
  50456. max = temp;
  50457. }
  50458. d = Math.max(min, d);
  50459. maxValue = Math.min(max, maxValue);
  50460. if (d > maxValue) {
  50461. return false;
  50462. }
  50463. }
  50464. if (Math.abs(this.direction.y) < 0.0000001) {
  50465. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  50466. return false;
  50467. }
  50468. }
  50469. else {
  50470. inv = 1.0 / this.direction.y;
  50471. min = (minimum.y - this.origin.y) * inv;
  50472. max = (maximum.y - this.origin.y) * inv;
  50473. if (max === -Infinity) {
  50474. max = Infinity;
  50475. }
  50476. if (min > max) {
  50477. temp = min;
  50478. min = max;
  50479. max = temp;
  50480. }
  50481. d = Math.max(min, d);
  50482. maxValue = Math.min(max, maxValue);
  50483. if (d > maxValue) {
  50484. return false;
  50485. }
  50486. }
  50487. if (Math.abs(this.direction.z) < 0.0000001) {
  50488. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  50489. return false;
  50490. }
  50491. }
  50492. else {
  50493. inv = 1.0 / this.direction.z;
  50494. min = (minimum.z - this.origin.z) * inv;
  50495. max = (maximum.z - this.origin.z) * inv;
  50496. if (max === -Infinity) {
  50497. max = Infinity;
  50498. }
  50499. if (min > max) {
  50500. temp = min;
  50501. min = max;
  50502. max = temp;
  50503. }
  50504. d = Math.max(min, d);
  50505. maxValue = Math.min(max, maxValue);
  50506. if (d > maxValue) {
  50507. return false;
  50508. }
  50509. }
  50510. return true;
  50511. };
  50512. Ray.prototype.intersectsBox = function (box) {
  50513. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  50514. };
  50515. Ray.prototype.intersectsSphere = function (sphere) {
  50516. var x = sphere.center.x - this.origin.x;
  50517. var y = sphere.center.y - this.origin.y;
  50518. var z = sphere.center.z - this.origin.z;
  50519. var pyth = (x * x) + (y * y) + (z * z);
  50520. var rr = sphere.radius * sphere.radius;
  50521. if (pyth <= rr) {
  50522. return true;
  50523. }
  50524. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  50525. if (dot < 0.0) {
  50526. return false;
  50527. }
  50528. var temp = pyth - (dot * dot);
  50529. return temp <= rr;
  50530. };
  50531. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  50532. if (!this._edge1) {
  50533. this._edge1 = BABYLON.Vector3.Zero();
  50534. this._edge2 = BABYLON.Vector3.Zero();
  50535. this._pvec = BABYLON.Vector3.Zero();
  50536. this._tvec = BABYLON.Vector3.Zero();
  50537. this._qvec = BABYLON.Vector3.Zero();
  50538. }
  50539. vertex1.subtractToRef(vertex0, this._edge1);
  50540. vertex2.subtractToRef(vertex0, this._edge2);
  50541. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  50542. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  50543. if (det === 0) {
  50544. return null;
  50545. }
  50546. var invdet = 1 / det;
  50547. this.origin.subtractToRef(vertex0, this._tvec);
  50548. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  50549. if (bu < 0 || bu > 1.0) {
  50550. return null;
  50551. }
  50552. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  50553. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  50554. if (bv < 0 || bu + bv > 1.0) {
  50555. return null;
  50556. }
  50557. //check if the distance is longer than the predefined length.
  50558. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  50559. if (distance > this.length) {
  50560. return null;
  50561. }
  50562. return new BABYLON.IntersectionInfo(bu, bv, distance);
  50563. };
  50564. Ray.prototype.intersectsPlane = function (plane) {
  50565. var distance;
  50566. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  50567. if (Math.abs(result1) < 9.99999997475243E-07) {
  50568. return null;
  50569. }
  50570. else {
  50571. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  50572. distance = (-plane.d - result2) / result1;
  50573. if (distance < 0.0) {
  50574. if (distance < -9.99999997475243E-07) {
  50575. return null;
  50576. }
  50577. else {
  50578. return 0;
  50579. }
  50580. }
  50581. return distance;
  50582. }
  50583. };
  50584. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  50585. var tm = BABYLON.Tmp.Matrix[0];
  50586. mesh.getWorldMatrix().invertToRef(tm);
  50587. if (this._tmpRay) {
  50588. Ray.TransformToRef(this, tm, this._tmpRay);
  50589. }
  50590. else {
  50591. this._tmpRay = Ray.Transform(this, tm);
  50592. }
  50593. return mesh.intersects(this._tmpRay, fastCheck);
  50594. };
  50595. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  50596. if (results) {
  50597. results.length = 0;
  50598. }
  50599. else {
  50600. results = [];
  50601. }
  50602. for (var i = 0; i < meshes.length; i++) {
  50603. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  50604. if (pickInfo.hit) {
  50605. results.push(pickInfo);
  50606. }
  50607. }
  50608. results.sort(this._comparePickingInfo);
  50609. return results;
  50610. };
  50611. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  50612. if (pickingInfoA.distance < pickingInfoB.distance) {
  50613. return -1;
  50614. }
  50615. else if (pickingInfoA.distance > pickingInfoB.distance) {
  50616. return 1;
  50617. }
  50618. else {
  50619. return 0;
  50620. }
  50621. };
  50622. /**
  50623. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  50624. * @param sega the first point of the segment to test the intersection against
  50625. * @param segb the second point of the segment to test the intersection against
  50626. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  50627. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  50628. */
  50629. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  50630. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  50631. var u = segb.subtract(sega);
  50632. var v = rsegb.subtract(this.origin);
  50633. var w = sega.subtract(this.origin);
  50634. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  50635. var b = BABYLON.Vector3.Dot(u, v);
  50636. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  50637. var d = BABYLON.Vector3.Dot(u, w);
  50638. var e = BABYLON.Vector3.Dot(v, w);
  50639. var D = a * c - b * b; // always >= 0
  50640. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  50641. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  50642. // compute the line parameters of the two closest points
  50643. if (D < Ray.smallnum) {
  50644. sN = 0.0; // force using point P0 on segment S1
  50645. sD = 1.0; // to prevent possible division by 0.0 later
  50646. tN = e;
  50647. tD = c;
  50648. }
  50649. else {
  50650. sN = (b * e - c * d);
  50651. tN = (a * e - b * d);
  50652. if (sN < 0.0) {
  50653. sN = 0.0;
  50654. tN = e;
  50655. tD = c;
  50656. }
  50657. else if (sN > sD) {
  50658. sN = sD;
  50659. tN = e + b;
  50660. tD = c;
  50661. }
  50662. }
  50663. if (tN < 0.0) {
  50664. tN = 0.0;
  50665. // recompute sc for this edge
  50666. if (-d < 0.0) {
  50667. sN = 0.0;
  50668. }
  50669. else if (-d > a)
  50670. sN = sD;
  50671. else {
  50672. sN = -d;
  50673. sD = a;
  50674. }
  50675. }
  50676. else if (tN > tD) {
  50677. tN = tD;
  50678. // recompute sc for this edge
  50679. if ((-d + b) < 0.0) {
  50680. sN = 0;
  50681. }
  50682. else if ((-d + b) > a) {
  50683. sN = sD;
  50684. }
  50685. else {
  50686. sN = (-d + b);
  50687. sD = a;
  50688. }
  50689. }
  50690. // finally do the division to get sc and tc
  50691. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  50692. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  50693. // get the difference of the two closest points
  50694. var qtc = v.multiplyByFloats(tc, tc, tc);
  50695. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  50696. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  50697. if (isIntersected) {
  50698. return qtc.length();
  50699. }
  50700. return -1;
  50701. };
  50702. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50703. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  50704. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  50705. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  50706. this.direction.normalize();
  50707. return this;
  50708. };
  50709. // Statics
  50710. Ray.Zero = function () {
  50711. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  50712. };
  50713. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50714. var result = Ray.Zero();
  50715. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  50716. };
  50717. /**
  50718. * 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
  50719. * transformed to the given world matrix.
  50720. * @param origin The origin point
  50721. * @param end The end point
  50722. * @param world a matrix to transform the ray to. Default is the identity matrix.
  50723. */
  50724. Ray.CreateNewFromTo = function (origin, end, world) {
  50725. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  50726. var direction = end.subtract(origin);
  50727. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  50728. direction.normalize();
  50729. return Ray.Transform(new Ray(origin, direction, length), world);
  50730. };
  50731. Ray.Transform = function (ray, matrix) {
  50732. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  50733. Ray.TransformToRef(ray, matrix, result);
  50734. return result;
  50735. };
  50736. Ray.TransformToRef = function (ray, matrix, result) {
  50737. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  50738. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  50739. result.length = ray.length;
  50740. var dir = result.direction;
  50741. var len = dir.length();
  50742. if (!(len === 0 || len === 1)) {
  50743. var num = 1.0 / len;
  50744. dir.x *= num;
  50745. dir.y *= num;
  50746. dir.z *= num;
  50747. result.length *= len;
  50748. }
  50749. };
  50750. Ray.smallnum = 0.00000001;
  50751. Ray.rayl = 10e8;
  50752. return Ray;
  50753. }());
  50754. BABYLON.Ray = Ray;
  50755. })(BABYLON || (BABYLON = {}));
  50756. //# sourceMappingURL=babylon.ray.js.map
  50757. "use strict";
  50758. var BABYLON;
  50759. (function (BABYLON) {
  50760. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  50761. if (boxMin.x > sphereCenter.x + sphereRadius)
  50762. return false;
  50763. if (sphereCenter.x - sphereRadius > boxMax.x)
  50764. return false;
  50765. if (boxMin.y > sphereCenter.y + sphereRadius)
  50766. return false;
  50767. if (sphereCenter.y - sphereRadius > boxMax.y)
  50768. return false;
  50769. if (boxMin.z > sphereCenter.z + sphereRadius)
  50770. return false;
  50771. if (sphereCenter.z - sphereRadius > boxMax.z)
  50772. return false;
  50773. return true;
  50774. };
  50775. var getLowestRoot = (function () {
  50776. var result = { root: 0, found: false };
  50777. return function (a, b, c, maxR) {
  50778. result.root = 0;
  50779. result.found = false;
  50780. var determinant = b * b - 4.0 * a * c;
  50781. if (determinant < 0)
  50782. return result;
  50783. var sqrtD = Math.sqrt(determinant);
  50784. var r1 = (-b - sqrtD) / (2.0 * a);
  50785. var r2 = (-b + sqrtD) / (2.0 * a);
  50786. if (r1 > r2) {
  50787. var temp = r2;
  50788. r2 = r1;
  50789. r1 = temp;
  50790. }
  50791. if (r1 > 0 && r1 < maxR) {
  50792. result.root = r1;
  50793. result.found = true;
  50794. return result;
  50795. }
  50796. if (r2 > 0 && r2 < maxR) {
  50797. result.root = r2;
  50798. result.found = true;
  50799. return result;
  50800. }
  50801. return result;
  50802. };
  50803. })();
  50804. var Collider = /** @class */ (function () {
  50805. function Collider() {
  50806. this._collisionPoint = BABYLON.Vector3.Zero();
  50807. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  50808. this._tempVector = BABYLON.Vector3.Zero();
  50809. this._tempVector2 = BABYLON.Vector3.Zero();
  50810. this._tempVector3 = BABYLON.Vector3.Zero();
  50811. this._tempVector4 = BABYLON.Vector3.Zero();
  50812. this._edge = BABYLON.Vector3.Zero();
  50813. this._baseToVertex = BABYLON.Vector3.Zero();
  50814. this._destinationPoint = BABYLON.Vector3.Zero();
  50815. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  50816. this._displacementVector = BABYLON.Vector3.Zero();
  50817. this._radius = BABYLON.Vector3.One();
  50818. this._retry = 0;
  50819. this._basePointWorld = BABYLON.Vector3.Zero();
  50820. this._velocityWorld = BABYLON.Vector3.Zero();
  50821. this._normalizedVelocity = BABYLON.Vector3.Zero();
  50822. this._collisionMask = -1;
  50823. }
  50824. Object.defineProperty(Collider.prototype, "collisionMask", {
  50825. get: function () {
  50826. return this._collisionMask;
  50827. },
  50828. set: function (mask) {
  50829. this._collisionMask = !isNaN(mask) ? mask : -1;
  50830. },
  50831. enumerable: true,
  50832. configurable: true
  50833. });
  50834. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  50835. /**
  50836. * Gets the plane normal used to compute the sliding response (in local space)
  50837. */
  50838. get: function () {
  50839. return this._slidePlaneNormal;
  50840. },
  50841. enumerable: true,
  50842. configurable: true
  50843. });
  50844. // Methods
  50845. Collider.prototype._initialize = function (source, dir, e) {
  50846. this._velocity = dir;
  50847. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  50848. this._basePoint = source;
  50849. source.multiplyToRef(this._radius, this._basePointWorld);
  50850. dir.multiplyToRef(this._radius, this._velocityWorld);
  50851. this._velocityWorldLength = this._velocityWorld.length();
  50852. this._epsilon = e;
  50853. this.collisionFound = false;
  50854. };
  50855. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  50856. pa.subtractToRef(point, this._tempVector);
  50857. pb.subtractToRef(point, this._tempVector2);
  50858. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  50859. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50860. if (d < 0)
  50861. return false;
  50862. pc.subtractToRef(point, this._tempVector3);
  50863. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  50864. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50865. if (d < 0)
  50866. return false;
  50867. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  50868. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50869. return d >= 0;
  50870. };
  50871. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  50872. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  50873. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  50874. if (distance > this._velocityWorldLength + max + sphereRadius) {
  50875. return false;
  50876. }
  50877. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  50878. return false;
  50879. return true;
  50880. };
  50881. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  50882. var t0;
  50883. var embeddedInPlane = false;
  50884. //defensive programming, actually not needed.
  50885. if (!trianglePlaneArray) {
  50886. trianglePlaneArray = [];
  50887. }
  50888. if (!trianglePlaneArray[faceIndex]) {
  50889. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  50890. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  50891. }
  50892. var trianglePlane = trianglePlaneArray[faceIndex];
  50893. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  50894. return;
  50895. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  50896. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  50897. if (normalDotVelocity == 0) {
  50898. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  50899. return;
  50900. embeddedInPlane = true;
  50901. t0 = 0;
  50902. }
  50903. else {
  50904. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50905. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50906. if (t0 > t1) {
  50907. var temp = t1;
  50908. t1 = t0;
  50909. t0 = temp;
  50910. }
  50911. if (t0 > 1.0 || t1 < 0.0)
  50912. return;
  50913. if (t0 < 0)
  50914. t0 = 0;
  50915. if (t0 > 1.0)
  50916. t0 = 1.0;
  50917. }
  50918. this._collisionPoint.copyFromFloats(0, 0, 0);
  50919. var found = false;
  50920. var t = 1.0;
  50921. if (!embeddedInPlane) {
  50922. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  50923. this._velocity.scaleToRef(t0, this._tempVector);
  50924. this._planeIntersectionPoint.addInPlace(this._tempVector);
  50925. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  50926. found = true;
  50927. t = t0;
  50928. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  50929. }
  50930. }
  50931. if (!found) {
  50932. var velocitySquaredLength = this._velocity.lengthSquared();
  50933. var a = velocitySquaredLength;
  50934. this._basePoint.subtractToRef(p1, this._tempVector);
  50935. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50936. var c = this._tempVector.lengthSquared() - 1.0;
  50937. var lowestRoot = getLowestRoot(a, b, c, t);
  50938. if (lowestRoot.found) {
  50939. t = lowestRoot.root;
  50940. found = true;
  50941. this._collisionPoint.copyFrom(p1);
  50942. }
  50943. this._basePoint.subtractToRef(p2, this._tempVector);
  50944. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50945. c = this._tempVector.lengthSquared() - 1.0;
  50946. lowestRoot = getLowestRoot(a, b, c, t);
  50947. if (lowestRoot.found) {
  50948. t = lowestRoot.root;
  50949. found = true;
  50950. this._collisionPoint.copyFrom(p2);
  50951. }
  50952. this._basePoint.subtractToRef(p3, this._tempVector);
  50953. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50954. c = this._tempVector.lengthSquared() - 1.0;
  50955. lowestRoot = getLowestRoot(a, b, c, t);
  50956. if (lowestRoot.found) {
  50957. t = lowestRoot.root;
  50958. found = true;
  50959. this._collisionPoint.copyFrom(p3);
  50960. }
  50961. p2.subtractToRef(p1, this._edge);
  50962. p1.subtractToRef(this._basePoint, this._baseToVertex);
  50963. var edgeSquaredLength = this._edge.lengthSquared();
  50964. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50965. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50966. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50967. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50968. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50969. lowestRoot = getLowestRoot(a, b, c, t);
  50970. if (lowestRoot.found) {
  50971. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50972. if (f >= 0.0 && f <= 1.0) {
  50973. t = lowestRoot.root;
  50974. found = true;
  50975. this._edge.scaleInPlace(f);
  50976. p1.addToRef(this._edge, this._collisionPoint);
  50977. }
  50978. }
  50979. p3.subtractToRef(p2, this._edge);
  50980. p2.subtractToRef(this._basePoint, this._baseToVertex);
  50981. edgeSquaredLength = this._edge.lengthSquared();
  50982. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50983. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50984. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50985. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50986. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50987. lowestRoot = getLowestRoot(a, b, c, t);
  50988. if (lowestRoot.found) {
  50989. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50990. if (f >= 0.0 && f <= 1.0) {
  50991. t = lowestRoot.root;
  50992. found = true;
  50993. this._edge.scaleInPlace(f);
  50994. p2.addToRef(this._edge, this._collisionPoint);
  50995. }
  50996. }
  50997. p1.subtractToRef(p3, this._edge);
  50998. p3.subtractToRef(this._basePoint, this._baseToVertex);
  50999. edgeSquaredLength = this._edge.lengthSquared();
  51000. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  51001. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  51002. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  51003. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  51004. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  51005. lowestRoot = getLowestRoot(a, b, c, t);
  51006. if (lowestRoot.found) {
  51007. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  51008. if (f >= 0.0 && f <= 1.0) {
  51009. t = lowestRoot.root;
  51010. found = true;
  51011. this._edge.scaleInPlace(f);
  51012. p3.addToRef(this._edge, this._collisionPoint);
  51013. }
  51014. }
  51015. }
  51016. if (found) {
  51017. var distToCollision = t * this._velocity.length();
  51018. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  51019. if (!this.intersectionPoint) {
  51020. this.intersectionPoint = this._collisionPoint.clone();
  51021. }
  51022. else {
  51023. this.intersectionPoint.copyFrom(this._collisionPoint);
  51024. }
  51025. this._nearestDistance = distToCollision;
  51026. this.collisionFound = true;
  51027. }
  51028. }
  51029. };
  51030. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  51031. for (var i = indexStart; i < indexEnd; i += 3) {
  51032. var p1 = pts[indices[i] - decal];
  51033. var p2 = pts[indices[i + 1] - decal];
  51034. var p3 = pts[indices[i + 2] - decal];
  51035. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  51036. }
  51037. };
  51038. Collider.prototype._getResponse = function (pos, vel) {
  51039. pos.addToRef(vel, this._destinationPoint);
  51040. vel.scaleInPlace((this._nearestDistance / vel.length()));
  51041. this._basePoint.addToRef(vel, pos);
  51042. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  51043. this._slidePlaneNormal.normalize();
  51044. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  51045. pos.addInPlace(this._displacementVector);
  51046. this.intersectionPoint.addInPlace(this._displacementVector);
  51047. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  51048. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  51049. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  51050. };
  51051. return Collider;
  51052. }());
  51053. BABYLON.Collider = Collider;
  51054. })(BABYLON || (BABYLON = {}));
  51055. //# sourceMappingURL=babylon.collider.js.map
  51056. "use strict";
  51057. var BABYLON;
  51058. (function (BABYLON) {
  51059. //WebWorker code will be inserted to this variable.
  51060. BABYLON.CollisionWorker = "";
  51061. var WorkerTaskType;
  51062. (function (WorkerTaskType) {
  51063. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  51064. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  51065. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  51066. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  51067. var WorkerReplyType;
  51068. (function (WorkerReplyType) {
  51069. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  51070. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  51071. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  51072. var CollisionCoordinatorWorker = /** @class */ (function () {
  51073. function CollisionCoordinatorWorker() {
  51074. var _this = this;
  51075. this._scaledPosition = BABYLON.Vector3.Zero();
  51076. this._scaledVelocity = BABYLON.Vector3.Zero();
  51077. this.onMeshUpdated = function (transformNode) {
  51078. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  51079. };
  51080. this.onGeometryUpdated = function (geometry) {
  51081. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  51082. };
  51083. this._afterRender = function () {
  51084. if (!_this._init)
  51085. return;
  51086. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  51087. return;
  51088. }
  51089. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  51090. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  51091. if (_this._runningUpdated > 4) {
  51092. return;
  51093. }
  51094. ++_this._runningUpdated;
  51095. var payload = {
  51096. updatedMeshes: _this._addUpdateMeshesList,
  51097. updatedGeometries: _this._addUpdateGeometriesList,
  51098. removedGeometries: _this._toRemoveGeometryArray,
  51099. removedMeshes: _this._toRemoveMeshesArray
  51100. };
  51101. var message = {
  51102. payload: payload,
  51103. taskType: WorkerTaskType.UPDATE
  51104. };
  51105. var serializable = [];
  51106. for (var id in payload.updatedGeometries) {
  51107. if (payload.updatedGeometries.hasOwnProperty(id)) {
  51108. //prepare transferables
  51109. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  51110. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  51111. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  51112. }
  51113. }
  51114. _this._worker.postMessage(message, serializable);
  51115. _this._addUpdateMeshesList = {};
  51116. _this._addUpdateGeometriesList = {};
  51117. _this._toRemoveGeometryArray = [];
  51118. _this._toRemoveMeshesArray = [];
  51119. };
  51120. this._onMessageFromWorker = function (e) {
  51121. var returnData = e.data;
  51122. if (returnData.error != WorkerReplyType.SUCCESS) {
  51123. //TODO what errors can be returned from the worker?
  51124. BABYLON.Tools.Warn("error returned from worker!");
  51125. return;
  51126. }
  51127. switch (returnData.taskType) {
  51128. case WorkerTaskType.INIT:
  51129. _this._init = true;
  51130. //Update the worked with ALL of the scene's current state
  51131. _this._scene.meshes.forEach(function (mesh) {
  51132. _this.onMeshAdded(mesh);
  51133. });
  51134. _this._scene.getGeometries().forEach(function (geometry) {
  51135. _this.onGeometryAdded(geometry);
  51136. });
  51137. break;
  51138. case WorkerTaskType.UPDATE:
  51139. _this._runningUpdated--;
  51140. break;
  51141. case WorkerTaskType.COLLIDE:
  51142. var returnPayload = returnData.payload;
  51143. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  51144. return;
  51145. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  51146. if (callback) {
  51147. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  51148. if (mesh) {
  51149. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  51150. }
  51151. }
  51152. //cleanup
  51153. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  51154. break;
  51155. }
  51156. };
  51157. this._collisionsCallbackArray = [];
  51158. this._init = false;
  51159. this._runningUpdated = 0;
  51160. this._addUpdateMeshesList = {};
  51161. this._addUpdateGeometriesList = {};
  51162. this._toRemoveGeometryArray = [];
  51163. this._toRemoveMeshesArray = [];
  51164. }
  51165. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51166. if (!this._init)
  51167. return;
  51168. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  51169. return;
  51170. position.divideToRef(collider._radius, this._scaledPosition);
  51171. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51172. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  51173. var payload = {
  51174. collider: {
  51175. position: this._scaledPosition.asArray(),
  51176. velocity: this._scaledVelocity.asArray(),
  51177. radius: collider._radius.asArray()
  51178. },
  51179. collisionId: collisionIndex,
  51180. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  51181. maximumRetry: maximumRetry
  51182. };
  51183. var message = {
  51184. payload: payload,
  51185. taskType: WorkerTaskType.COLLIDE
  51186. };
  51187. this._worker.postMessage(message);
  51188. };
  51189. CollisionCoordinatorWorker.prototype.init = function (scene) {
  51190. this._scene = scene;
  51191. this._scene.registerAfterRender(this._afterRender);
  51192. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  51193. this._worker = new Worker(workerUrl);
  51194. this._worker.onmessage = this._onMessageFromWorker;
  51195. var message = {
  51196. payload: {},
  51197. taskType: WorkerTaskType.INIT
  51198. };
  51199. this._worker.postMessage(message);
  51200. };
  51201. CollisionCoordinatorWorker.prototype.destroy = function () {
  51202. this._scene.unregisterAfterRender(this._afterRender);
  51203. this._worker.terminate();
  51204. };
  51205. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  51206. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  51207. this.onMeshUpdated(mesh);
  51208. };
  51209. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  51210. this._toRemoveMeshesArray.push(mesh.uniqueId);
  51211. };
  51212. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  51213. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  51214. geometry.onGeometryUpdated = this.onGeometryUpdated;
  51215. this.onGeometryUpdated(geometry);
  51216. };
  51217. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  51218. this._toRemoveGeometryArray.push(geometry.id);
  51219. };
  51220. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  51221. var submeshes = [];
  51222. if (mesh.subMeshes) {
  51223. submeshes = mesh.subMeshes.map(function (sm, idx) {
  51224. var boundingInfo = sm.getBoundingInfo();
  51225. return {
  51226. position: idx,
  51227. verticesStart: sm.verticesStart,
  51228. verticesCount: sm.verticesCount,
  51229. indexStart: sm.indexStart,
  51230. indexCount: sm.indexCount,
  51231. hasMaterial: !!sm.getMaterial(),
  51232. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51233. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51234. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51235. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  51236. };
  51237. });
  51238. }
  51239. var geometryId = null;
  51240. if (mesh instanceof BABYLON.Mesh) {
  51241. var geometry = mesh.geometry;
  51242. geometryId = geometry ? geometry.id : null;
  51243. }
  51244. else if (mesh instanceof BABYLON.InstancedMesh) {
  51245. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  51246. geometryId = geometry ? geometry.id : null;
  51247. }
  51248. var boundingInfo = mesh.getBoundingInfo();
  51249. return {
  51250. uniqueId: mesh.uniqueId,
  51251. id: mesh.id,
  51252. name: mesh.name,
  51253. geometryId: geometryId,
  51254. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51255. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51256. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51257. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  51258. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  51259. subMeshes: submeshes,
  51260. checkCollisions: mesh.checkCollisions
  51261. };
  51262. };
  51263. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  51264. return {
  51265. id: geometry.id,
  51266. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  51267. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  51268. indices: new Uint32Array(geometry.getIndices() || []),
  51269. };
  51270. };
  51271. return CollisionCoordinatorWorker;
  51272. }());
  51273. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  51274. var CollisionCoordinatorLegacy = /** @class */ (function () {
  51275. function CollisionCoordinatorLegacy() {
  51276. this._scaledPosition = BABYLON.Vector3.Zero();
  51277. this._scaledVelocity = BABYLON.Vector3.Zero();
  51278. this._finalPosition = BABYLON.Vector3.Zero();
  51279. }
  51280. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51281. position.divideToRef(collider._radius, this._scaledPosition);
  51282. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51283. collider.collidedMesh = null;
  51284. collider._retry = 0;
  51285. collider._initialVelocity = this._scaledVelocity;
  51286. collider._initialPosition = this._scaledPosition;
  51287. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  51288. this._finalPosition.multiplyInPlace(collider._radius);
  51289. //run the callback
  51290. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  51291. };
  51292. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  51293. this._scene = scene;
  51294. };
  51295. CollisionCoordinatorLegacy.prototype.destroy = function () {
  51296. //Legacy need no destruction method.
  51297. };
  51298. //No update in legacy mode
  51299. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  51300. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  51301. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  51302. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  51303. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  51304. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  51305. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  51306. if (excludedMesh === void 0) { excludedMesh = null; }
  51307. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  51308. if (collider._retry >= maximumRetry) {
  51309. finalPosition.copyFrom(position);
  51310. return;
  51311. }
  51312. // Check if this is a mesh else camera or -1
  51313. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  51314. collider._initialize(position, velocity, closeDistance);
  51315. // Check all meshes
  51316. for (var index = 0; index < this._scene.meshes.length; index++) {
  51317. var mesh = this._scene.meshes[index];
  51318. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  51319. mesh._checkCollision(collider);
  51320. }
  51321. }
  51322. if (!collider.collisionFound) {
  51323. position.addToRef(velocity, finalPosition);
  51324. return;
  51325. }
  51326. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  51327. collider._getResponse(position, velocity);
  51328. }
  51329. if (velocity.length() <= closeDistance) {
  51330. finalPosition.copyFrom(position);
  51331. return;
  51332. }
  51333. collider._retry++;
  51334. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  51335. };
  51336. return CollisionCoordinatorLegacy;
  51337. }());
  51338. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  51339. })(BABYLON || (BABYLON = {}));
  51340. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  51341. "use strict";
  51342. var BABYLON;
  51343. (function (BABYLON) {
  51344. /**
  51345. * A particle represents one of the element emitted by a particle system.
  51346. * This is mainly define by its coordinates, direction, velocity and age.
  51347. */
  51348. var Particle = /** @class */ (function () {
  51349. /**
  51350. * Creates a new instance of @see Particle
  51351. * @param particleSystem the particle system the particle belongs to
  51352. */
  51353. function Particle(
  51354. /**
  51355. * particleSystem the particle system the particle belongs to.
  51356. */
  51357. particleSystem) {
  51358. this.particleSystem = particleSystem;
  51359. /**
  51360. * The world position of the particle in the scene.
  51361. */
  51362. this.position = BABYLON.Vector3.Zero();
  51363. /**
  51364. * The world direction of the particle in the scene.
  51365. */
  51366. this.direction = BABYLON.Vector3.Zero();
  51367. /**
  51368. * The color of the particle.
  51369. */
  51370. this.color = new BABYLON.Color4(0, 0, 0, 0);
  51371. /**
  51372. * The color change of the particle per step.
  51373. */
  51374. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  51375. /**
  51376. * Defines how long will the life of the particle be.
  51377. */
  51378. this.lifeTime = 1.0;
  51379. /**
  51380. * The current age of the particle.
  51381. */
  51382. this.age = 0;
  51383. /**
  51384. * The current size of the particle.
  51385. */
  51386. this.size = 0;
  51387. /**
  51388. * The current angle of the particle.
  51389. */
  51390. this.angle = 0;
  51391. /**
  51392. * Defines how fast is the angle changing.
  51393. */
  51394. this.angularSpeed = 0;
  51395. /**
  51396. * Defines the cell index used by the particle to be rendered from a sprite.
  51397. */
  51398. this.cellIndex = 0;
  51399. this._currentFrameCounter = 0;
  51400. if (!this.particleSystem.isAnimationSheetEnabled) {
  51401. return;
  51402. }
  51403. this.updateCellInfoFromSystem();
  51404. }
  51405. Particle.prototype.updateCellInfoFromSystem = function () {
  51406. this.cellIndex = this.particleSystem.startSpriteCellID;
  51407. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  51408. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  51409. }
  51410. else {
  51411. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  51412. }
  51413. };
  51414. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  51415. // (ageOffset / scaledUpdateSpeed) / available cells
  51416. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  51417. this._currentFrameCounter += scaledUpdateSpeed;
  51418. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  51419. this._currentFrameCounter = 0;
  51420. this.cellIndex++;
  51421. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51422. this.cellIndex = this.particleSystem.endSpriteCellID;
  51423. }
  51424. }
  51425. };
  51426. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  51427. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  51428. this.cellIndex++;
  51429. this._currentFrameCounter = 0;
  51430. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51431. if (this.particleSystem.spriteCellLoop) {
  51432. this.cellIndex = this.particleSystem.startSpriteCellID;
  51433. }
  51434. else {
  51435. this.cellIndex = this.particleSystem.endSpriteCellID;
  51436. }
  51437. }
  51438. }
  51439. else {
  51440. this._currentFrameCounter++;
  51441. }
  51442. };
  51443. /**
  51444. * Copy the properties of particle to another one.
  51445. * @param other the particle to copy the information to.
  51446. */
  51447. Particle.prototype.copyTo = function (other) {
  51448. other.position.copyFrom(this.position);
  51449. other.direction.copyFrom(this.direction);
  51450. other.color.copyFrom(this.color);
  51451. other.colorStep.copyFrom(this.colorStep);
  51452. other.lifeTime = this.lifeTime;
  51453. other.age = this.age;
  51454. other.size = this.size;
  51455. other.angle = this.angle;
  51456. other.angularSpeed = this.angularSpeed;
  51457. other.particleSystem = this.particleSystem;
  51458. other.cellIndex = this.cellIndex;
  51459. };
  51460. return Particle;
  51461. }());
  51462. BABYLON.Particle = Particle;
  51463. })(BABYLON || (BABYLON = {}));
  51464. //# sourceMappingURL=babylon.particle.js.map
  51465. "use strict";
  51466. var BABYLON;
  51467. (function (BABYLON) {
  51468. /**
  51469. * This represents a particle system in Babylon.
  51470. * 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.
  51471. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  51472. * @example https://doc.babylonjs.com/babylon101/particles
  51473. */
  51474. var ParticleSystem = /** @class */ (function () {
  51475. /**
  51476. * Instantiates a particle system.
  51477. * 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.
  51478. * @param name The name of the particle system
  51479. * @param capacity The max number of particles alive at the same time
  51480. * @param scene The scene the particle system belongs to
  51481. * @param customEffect a custom effect used to change the way particles are rendered by default
  51482. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  51483. * @param epsilon Offset used to render the particles
  51484. */
  51485. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  51486. if (customEffect === void 0) { customEffect = null; }
  51487. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  51488. if (epsilon === void 0) { epsilon = 0.01; }
  51489. var _this = this;
  51490. /**
  51491. * List of animations used by the particle system.
  51492. */
  51493. this.animations = [];
  51494. /**
  51495. * The rendering group used by the Particle system to chose when to render.
  51496. */
  51497. this.renderingGroupId = 0;
  51498. /**
  51499. * The emitter represents the Mesh or position we are attaching the particle system to.
  51500. */
  51501. this.emitter = null;
  51502. /**
  51503. * The maximum number of particles to emit per frame
  51504. */
  51505. this.emitRate = 10;
  51506. /**
  51507. * If you want to launch only a few particles at once, that can be done, as well.
  51508. */
  51509. this.manualEmitCount = -1;
  51510. /**
  51511. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  51512. */
  51513. this.updateSpeed = 0.01;
  51514. /**
  51515. * The amount of time the particle system is running (depends of the overall update speed).
  51516. */
  51517. this.targetStopDuration = 0;
  51518. /**
  51519. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  51520. */
  51521. this.disposeOnStop = false;
  51522. /**
  51523. * Minimum power of emitting particles.
  51524. */
  51525. this.minEmitPower = 1;
  51526. /**
  51527. * Maximum power of emitting particles.
  51528. */
  51529. this.maxEmitPower = 1;
  51530. /**
  51531. * Minimum life time of emitting particles.
  51532. */
  51533. this.minLifeTime = 1;
  51534. /**
  51535. * Maximum life time of emitting particles.
  51536. */
  51537. this.maxLifeTime = 1;
  51538. /**
  51539. * Minimum Size of emitting particles.
  51540. */
  51541. this.minSize = 1;
  51542. /**
  51543. * Maximum Size of emitting particles.
  51544. */
  51545. this.maxSize = 1;
  51546. /**
  51547. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  51548. */
  51549. this.minAngularSpeed = 0;
  51550. /**
  51551. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  51552. */
  51553. this.maxAngularSpeed = 0;
  51554. /**
  51555. * The layer mask we are rendering the particles through.
  51556. */
  51557. this.layerMask = 0x0FFFFFFF;
  51558. /**
  51559. * This can help using your own shader to render the particle system.
  51560. * The according effect will be created
  51561. */
  51562. this.customShader = null;
  51563. /**
  51564. * By default particle system starts as soon as they are created. This prevents the
  51565. * automatic start to happen and let you decide when to start emitting particles.
  51566. */
  51567. this.preventAutoStart = false;
  51568. /**
  51569. * Callback triggered when the particle animation is ending.
  51570. */
  51571. this.onAnimationEnd = null;
  51572. /**
  51573. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  51574. */
  51575. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  51576. /**
  51577. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  51578. * to override the particles.
  51579. */
  51580. this.forceDepthWrite = false;
  51581. /**
  51582. * You can use gravity if you want to give an orientation to your particles.
  51583. */
  51584. this.gravity = BABYLON.Vector3.Zero();
  51585. /**
  51586. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51587. */
  51588. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51589. /**
  51590. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51591. */
  51592. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51593. /**
  51594. * Color the particle will have at the end of its lifetime.
  51595. */
  51596. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  51597. /**
  51598. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  51599. */
  51600. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51601. /**
  51602. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  51603. */
  51604. this.spriteCellLoop = true;
  51605. /**
  51606. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  51607. */
  51608. this.spriteCellChangeSpeed = 0;
  51609. /**
  51610. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  51611. */
  51612. this.startSpriteCellID = 0;
  51613. /**
  51614. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  51615. */
  51616. this.endSpriteCellID = 0;
  51617. /**
  51618. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  51619. */
  51620. this.spriteCellWidth = 0;
  51621. /**
  51622. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  51623. */
  51624. this.spriteCellHeight = 0;
  51625. /**
  51626. * An event triggered when the system is disposed.
  51627. */
  51628. this.onDisposeObservable = new BABYLON.Observable();
  51629. this._particles = new Array();
  51630. this._stockParticles = new Array();
  51631. this._newPartsExcess = 0;
  51632. this._vertexBuffers = {};
  51633. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  51634. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  51635. this._scaledDirection = BABYLON.Vector3.Zero();
  51636. this._scaledGravity = BABYLON.Vector3.Zero();
  51637. this._currentRenderId = -1;
  51638. this._started = false;
  51639. this._stopped = false;
  51640. this._actualFrame = 0;
  51641. this._vertexBufferSize = 11;
  51642. // start of sub system methods
  51643. /**
  51644. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  51645. * Its lifetime will start back at 0.
  51646. */
  51647. this.recycleParticle = function (particle) {
  51648. var lastParticle = _this._particles.pop();
  51649. if (lastParticle !== particle) {
  51650. lastParticle.copyTo(particle);
  51651. }
  51652. _this._stockParticles.push(lastParticle);
  51653. };
  51654. this._createParticle = function () {
  51655. var particle;
  51656. if (_this._stockParticles.length !== 0) {
  51657. particle = _this._stockParticles.pop();
  51658. particle.age = 0;
  51659. particle.cellIndex = _this.startSpriteCellID;
  51660. }
  51661. else {
  51662. particle = new BABYLON.Particle(_this);
  51663. }
  51664. return particle;
  51665. };
  51666. this._emitFromParticle = function (particle) {
  51667. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  51668. return;
  51669. }
  51670. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  51671. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  51672. subSystem._rootParticleSystem = _this;
  51673. _this.activeSubSystems.push(subSystem);
  51674. subSystem.start();
  51675. };
  51676. this._appendParticleVertexes = null;
  51677. this.id = name;
  51678. this.name = name;
  51679. this._capacity = capacity;
  51680. this._epsilon = epsilon;
  51681. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  51682. if (isAnimationSheetEnabled) {
  51683. this._vertexBufferSize = 12;
  51684. }
  51685. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51686. this._customEffect = customEffect;
  51687. scene.particleSystems.push(this);
  51688. this._createIndexBuffer();
  51689. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  51690. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  51691. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  51692. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  51693. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  51694. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  51695. if (this._isAnimationSheetEnabled) {
  51696. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  51697. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  51698. }
  51699. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  51700. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  51701. this._vertexBuffers["options"] = options;
  51702. // Default emitter type
  51703. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  51704. this.updateFunction = function (particles) {
  51705. for (var index = 0; index < particles.length; index++) {
  51706. var particle = particles[index];
  51707. particle.age += _this._scaledUpdateSpeed;
  51708. if (particle.age >= particle.lifeTime) {
  51709. _this._emitFromParticle(particle);
  51710. _this.recycleParticle(particle);
  51711. index--;
  51712. continue;
  51713. }
  51714. else {
  51715. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  51716. particle.color.addInPlace(_this._scaledColorStep);
  51717. if (particle.color.a < 0)
  51718. particle.color.a = 0;
  51719. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  51720. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  51721. particle.position.addInPlace(_this._scaledDirection);
  51722. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  51723. particle.direction.addInPlace(_this._scaledGravity);
  51724. if (_this._isAnimationSheetEnabled) {
  51725. particle.updateCellIndex(_this._scaledUpdateSpeed);
  51726. }
  51727. }
  51728. }
  51729. };
  51730. }
  51731. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  51732. /**
  51733. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51734. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51735. */
  51736. get: function () {
  51737. if (this.particleEmitterType.direction1) {
  51738. return this.particleEmitterType.direction1;
  51739. }
  51740. return BABYLON.Vector3.Zero();
  51741. },
  51742. set: function (value) {
  51743. if (this.particleEmitterType.direction1) {
  51744. this.particleEmitterType.direction1 = value;
  51745. }
  51746. },
  51747. enumerable: true,
  51748. configurable: true
  51749. });
  51750. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  51751. /**
  51752. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51753. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51754. */
  51755. get: function () {
  51756. if (this.particleEmitterType.direction2) {
  51757. return this.particleEmitterType.direction2;
  51758. }
  51759. return BABYLON.Vector3.Zero();
  51760. },
  51761. set: function (value) {
  51762. if (this.particleEmitterType.direction2) {
  51763. this.particleEmitterType.direction2 = value;
  51764. }
  51765. },
  51766. enumerable: true,
  51767. configurable: true
  51768. });
  51769. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  51770. /**
  51771. * 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.
  51772. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51773. */
  51774. get: function () {
  51775. if (this.particleEmitterType.minEmitBox) {
  51776. return this.particleEmitterType.minEmitBox;
  51777. }
  51778. return BABYLON.Vector3.Zero();
  51779. },
  51780. set: function (value) {
  51781. if (this.particleEmitterType.minEmitBox) {
  51782. this.particleEmitterType.minEmitBox = value;
  51783. }
  51784. },
  51785. enumerable: true,
  51786. configurable: true
  51787. });
  51788. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  51789. /**
  51790. * 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.
  51791. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51792. */
  51793. get: function () {
  51794. if (this.particleEmitterType.maxEmitBox) {
  51795. return this.particleEmitterType.maxEmitBox;
  51796. }
  51797. return BABYLON.Vector3.Zero();
  51798. },
  51799. set: function (value) {
  51800. if (this.particleEmitterType.maxEmitBox) {
  51801. this.particleEmitterType.maxEmitBox = value;
  51802. }
  51803. },
  51804. enumerable: true,
  51805. configurable: true
  51806. });
  51807. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  51808. /**
  51809. * Sets a callback that will be triggered when the system is disposed.
  51810. */
  51811. set: function (callback) {
  51812. if (this._onDisposeObserver) {
  51813. this.onDisposeObservable.remove(this._onDisposeObserver);
  51814. }
  51815. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  51816. },
  51817. enumerable: true,
  51818. configurable: true
  51819. });
  51820. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  51821. /**
  51822. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  51823. */
  51824. get: function () {
  51825. return this._isAnimationSheetEnabled;
  51826. },
  51827. enumerable: true,
  51828. configurable: true
  51829. });
  51830. Object.defineProperty(ParticleSystem.prototype, "particles", {
  51831. //end of Sub-emitter
  51832. /**
  51833. * Gets the current list of active particles
  51834. */
  51835. get: function () {
  51836. return this._particles;
  51837. },
  51838. enumerable: true,
  51839. configurable: true
  51840. });
  51841. /**
  51842. * Returns the string "ParticleSystem"
  51843. * @returns a string containing the class name
  51844. */
  51845. ParticleSystem.prototype.getClassName = function () {
  51846. return "ParticleSystem";
  51847. };
  51848. ParticleSystem.prototype._createIndexBuffer = function () {
  51849. var indices = [];
  51850. var index = 0;
  51851. for (var count = 0; count < this._capacity; count++) {
  51852. indices.push(index);
  51853. indices.push(index + 1);
  51854. indices.push(index + 2);
  51855. indices.push(index);
  51856. indices.push(index + 2);
  51857. indices.push(index + 3);
  51858. index += 4;
  51859. }
  51860. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  51861. };
  51862. /**
  51863. * Gets the maximum number of particles active at the same time.
  51864. * @returns The max number of active particles.
  51865. */
  51866. ParticleSystem.prototype.getCapacity = function () {
  51867. return this._capacity;
  51868. };
  51869. /**
  51870. * Gets Wether there are still active particles in the system.
  51871. * @returns True if it is alive, otherwise false.
  51872. */
  51873. ParticleSystem.prototype.isAlive = function () {
  51874. return this._alive;
  51875. };
  51876. /**
  51877. * Gets Wether the system has been started.
  51878. * @returns True if it has been started, otherwise false.
  51879. */
  51880. ParticleSystem.prototype.isStarted = function () {
  51881. return this._started;
  51882. };
  51883. /**
  51884. * Starts the particle system and begins to emit.
  51885. */
  51886. ParticleSystem.prototype.start = function () {
  51887. this._started = true;
  51888. this._stopped = false;
  51889. this._actualFrame = 0;
  51890. if (this.subEmitters && this.subEmitters.length != 0) {
  51891. this.activeSubSystems = new Array();
  51892. }
  51893. };
  51894. /**
  51895. * Stops the particle system.
  51896. * @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.
  51897. */
  51898. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  51899. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  51900. this._stopped = true;
  51901. if (stopSubEmitters) {
  51902. this._stopSubEmitters();
  51903. }
  51904. };
  51905. // animation sheet
  51906. /**
  51907. * Remove all active particles
  51908. */
  51909. ParticleSystem.prototype.reset = function () {
  51910. this._stockParticles = [];
  51911. this._particles = [];
  51912. };
  51913. /**
  51914. * @ignore (for internal use only)
  51915. */
  51916. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  51917. var offset = index * this._vertexBufferSize;
  51918. this._vertexData[offset] = particle.position.x;
  51919. this._vertexData[offset + 1] = particle.position.y;
  51920. this._vertexData[offset + 2] = particle.position.z;
  51921. this._vertexData[offset + 3] = particle.color.r;
  51922. this._vertexData[offset + 4] = particle.color.g;
  51923. this._vertexData[offset + 5] = particle.color.b;
  51924. this._vertexData[offset + 6] = particle.color.a;
  51925. this._vertexData[offset + 7] = particle.angle;
  51926. this._vertexData[offset + 8] = particle.size;
  51927. this._vertexData[offset + 9] = offsetX;
  51928. this._vertexData[offset + 10] = offsetY;
  51929. };
  51930. /**
  51931. * @ignore (for internal use only)
  51932. */
  51933. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  51934. if (offsetX === 0)
  51935. offsetX = this._epsilon;
  51936. else if (offsetX === 1)
  51937. offsetX = 1 - this._epsilon;
  51938. if (offsetY === 0)
  51939. offsetY = this._epsilon;
  51940. else if (offsetY === 1)
  51941. offsetY = 1 - this._epsilon;
  51942. var offset = index * this._vertexBufferSize;
  51943. this._vertexData[offset] = particle.position.x;
  51944. this._vertexData[offset + 1] = particle.position.y;
  51945. this._vertexData[offset + 2] = particle.position.z;
  51946. this._vertexData[offset + 3] = particle.color.r;
  51947. this._vertexData[offset + 4] = particle.color.g;
  51948. this._vertexData[offset + 5] = particle.color.b;
  51949. this._vertexData[offset + 6] = particle.color.a;
  51950. this._vertexData[offset + 7] = particle.angle;
  51951. this._vertexData[offset + 8] = particle.size;
  51952. this._vertexData[offset + 9] = offsetX;
  51953. this._vertexData[offset + 10] = offsetY;
  51954. this._vertexData[offset + 11] = particle.cellIndex;
  51955. };
  51956. ParticleSystem.prototype._stopSubEmitters = function () {
  51957. if (!this.activeSubSystems) {
  51958. return;
  51959. }
  51960. this.activeSubSystems.forEach(function (subSystem) {
  51961. subSystem.stop(true);
  51962. });
  51963. this.activeSubSystems = new Array();
  51964. };
  51965. ParticleSystem.prototype._removeFromRoot = function () {
  51966. if (!this._rootParticleSystem) {
  51967. return;
  51968. }
  51969. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  51970. if (index !== -1) {
  51971. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  51972. }
  51973. };
  51974. // end of sub system methods
  51975. ParticleSystem.prototype._update = function (newParticles) {
  51976. // Update current
  51977. this._alive = this._particles.length > 0;
  51978. this.updateFunction(this._particles);
  51979. // Add new ones
  51980. var worldMatrix;
  51981. if (this.emitter.position) {
  51982. var emitterMesh = this.emitter;
  51983. worldMatrix = emitterMesh.getWorldMatrix();
  51984. }
  51985. else {
  51986. var emitterPosition = this.emitter;
  51987. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  51988. }
  51989. var particle;
  51990. for (var index = 0; index < newParticles; index++) {
  51991. if (this._particles.length === this._capacity) {
  51992. break;
  51993. }
  51994. particle = this._createParticle();
  51995. this._particles.push(particle);
  51996. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  51997. if (this.startPositionFunction) {
  51998. this.startPositionFunction(worldMatrix, particle.position, particle);
  51999. }
  52000. else {
  52001. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  52002. }
  52003. if (this.startDirectionFunction) {
  52004. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  52005. }
  52006. else {
  52007. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  52008. }
  52009. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  52010. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  52011. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  52012. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  52013. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  52014. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  52015. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  52016. }
  52017. };
  52018. ParticleSystem.prototype._getEffect = function () {
  52019. if (this._customEffect) {
  52020. return this._customEffect;
  52021. }
  52022. ;
  52023. var defines = [];
  52024. if (this._scene.clipPlane) {
  52025. defines.push("#define CLIPPLANE");
  52026. }
  52027. if (this._isAnimationSheetEnabled) {
  52028. defines.push("#define ANIMATESHEET");
  52029. }
  52030. // Effect
  52031. var join = defines.join("\n");
  52032. if (this._cachedDefines !== join) {
  52033. this._cachedDefines = join;
  52034. var attributesNamesOrOptions;
  52035. var effectCreationOption;
  52036. if (this._isAnimationSheetEnabled) {
  52037. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  52038. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  52039. }
  52040. else {
  52041. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  52042. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  52043. }
  52044. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  52045. }
  52046. return this._effect;
  52047. };
  52048. /**
  52049. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  52050. */
  52051. ParticleSystem.prototype.animate = function () {
  52052. if (!this._started)
  52053. return;
  52054. var effect = this._getEffect();
  52055. // Check
  52056. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  52057. return;
  52058. if (this._currentRenderId === this._scene.getRenderId()) {
  52059. return;
  52060. }
  52061. this._currentRenderId = this._scene.getRenderId();
  52062. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  52063. // determine the number of particles we need to create
  52064. var newParticles;
  52065. if (this.manualEmitCount > -1) {
  52066. newParticles = this.manualEmitCount;
  52067. this._newPartsExcess = 0;
  52068. this.manualEmitCount = 0;
  52069. }
  52070. else {
  52071. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  52072. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  52073. }
  52074. if (this._newPartsExcess > 1.0) {
  52075. newParticles += this._newPartsExcess >> 0;
  52076. this._newPartsExcess -= this._newPartsExcess >> 0;
  52077. }
  52078. this._alive = false;
  52079. if (!this._stopped) {
  52080. this._actualFrame += this._scaledUpdateSpeed;
  52081. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  52082. this.stop();
  52083. }
  52084. else {
  52085. newParticles = 0;
  52086. }
  52087. this._update(newParticles);
  52088. // Stopped?
  52089. if (this._stopped) {
  52090. if (!this._alive) {
  52091. this._started = false;
  52092. if (this.onAnimationEnd) {
  52093. this.onAnimationEnd();
  52094. }
  52095. if (this.disposeOnStop) {
  52096. this._scene._toBeDisposed.push(this);
  52097. }
  52098. }
  52099. }
  52100. // Animation sheet
  52101. if (this._isAnimationSheetEnabled) {
  52102. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  52103. }
  52104. else {
  52105. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  52106. }
  52107. // Update VBO
  52108. var offset = 0;
  52109. for (var index = 0; index < this._particles.length; index++) {
  52110. var particle = this._particles[index];
  52111. this._appendParticleVertexes(offset, particle);
  52112. offset += 4;
  52113. }
  52114. if (this._vertexBuffer) {
  52115. this._vertexBuffer.update(this._vertexData);
  52116. }
  52117. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  52118. this.stop();
  52119. }
  52120. };
  52121. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  52122. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  52123. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  52124. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  52125. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  52126. };
  52127. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  52128. this._appendParticleVertex(offset++, particle, 0, 0);
  52129. this._appendParticleVertex(offset++, particle, 1, 0);
  52130. this._appendParticleVertex(offset++, particle, 1, 1);
  52131. this._appendParticleVertex(offset++, particle, 0, 1);
  52132. };
  52133. /**
  52134. * Rebuilds the particle system.
  52135. */
  52136. ParticleSystem.prototype.rebuild = function () {
  52137. this._createIndexBuffer();
  52138. if (this._vertexBuffer) {
  52139. this._vertexBuffer._rebuild();
  52140. }
  52141. };
  52142. /**
  52143. * Is this system ready to be used/rendered
  52144. * @return true if the system is ready
  52145. */
  52146. ParticleSystem.prototype.isReady = function () {
  52147. var effect = this._getEffect();
  52148. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  52149. return false;
  52150. }
  52151. return true;
  52152. };
  52153. /**
  52154. * Renders the particle system in its current state.
  52155. * @returns the current number of particles
  52156. */
  52157. ParticleSystem.prototype.render = function () {
  52158. var effect = this._getEffect();
  52159. // Check
  52160. if (!this.isReady() || !this._particles.length) {
  52161. return 0;
  52162. }
  52163. var engine = this._scene.getEngine();
  52164. // Render
  52165. engine.enableEffect(effect);
  52166. engine.setState(false);
  52167. var viewMatrix = this._scene.getViewMatrix();
  52168. effect.setTexture("diffuseSampler", this.particleTexture);
  52169. effect.setMatrix("view", viewMatrix);
  52170. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  52171. if (this._isAnimationSheetEnabled && this.particleTexture) {
  52172. var baseSize = this.particleTexture.getBaseSize();
  52173. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  52174. }
  52175. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  52176. if (this._scene.clipPlane) {
  52177. var clipPlane = this._scene.clipPlane;
  52178. var invView = viewMatrix.clone();
  52179. invView.invert();
  52180. effect.setMatrix("invView", invView);
  52181. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  52182. }
  52183. // VBOs
  52184. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  52185. // Draw order
  52186. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  52187. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  52188. }
  52189. else {
  52190. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52191. }
  52192. if (this.forceDepthWrite) {
  52193. engine.setDepthWrite(true);
  52194. }
  52195. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  52196. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52197. return this._particles.length;
  52198. };
  52199. /**
  52200. * Disposes the particle system and free the associated resources
  52201. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  52202. */
  52203. ParticleSystem.prototype.dispose = function (disposeTexture) {
  52204. if (disposeTexture === void 0) { disposeTexture = true; }
  52205. if (this._vertexBuffer) {
  52206. this._vertexBuffer.dispose();
  52207. this._vertexBuffer = null;
  52208. }
  52209. if (this._indexBuffer) {
  52210. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  52211. this._indexBuffer = null;
  52212. }
  52213. if (disposeTexture && this.particleTexture) {
  52214. this.particleTexture.dispose();
  52215. this.particleTexture = null;
  52216. }
  52217. this._removeFromRoot();
  52218. // Remove from scene
  52219. var index = this._scene.particleSystems.indexOf(this);
  52220. if (index > -1) {
  52221. this._scene.particleSystems.splice(index, 1);
  52222. }
  52223. // Callback
  52224. this.onDisposeObservable.notifyObservers(this);
  52225. this.onDisposeObservable.clear();
  52226. };
  52227. /**
  52228. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  52229. * @param radius The radius of the sphere to emit from
  52230. * @returns the emitter
  52231. */
  52232. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  52233. if (radius === void 0) { radius = 1; }
  52234. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  52235. this.particleEmitterType = particleEmitter;
  52236. return particleEmitter;
  52237. };
  52238. /**
  52239. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  52240. * @param radius The radius of the sphere to emit from
  52241. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  52242. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  52243. * @returns the emitter
  52244. */
  52245. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  52246. if (radius === void 0) { radius = 1; }
  52247. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  52248. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  52249. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  52250. this.particleEmitterType = particleEmitter;
  52251. return particleEmitter;
  52252. };
  52253. /**
  52254. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  52255. * @param radius The radius of the cone to emit from
  52256. * @param angle The base angle of the cone
  52257. * @returns the emitter
  52258. */
  52259. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  52260. if (radius === void 0) { radius = 1; }
  52261. if (angle === void 0) { angle = Math.PI / 4; }
  52262. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  52263. this.particleEmitterType = particleEmitter;
  52264. return particleEmitter;
  52265. };
  52266. // 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.
  52267. /**
  52268. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  52269. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  52270. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  52271. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52272. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52273. * @returns the emitter
  52274. */
  52275. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  52276. var particleEmitter = new BABYLON.BoxParticleEmitter();
  52277. this.direction1 = direction1;
  52278. this.direction2 = direction2;
  52279. this.minEmitBox = minEmitBox;
  52280. this.maxEmitBox = maxEmitBox;
  52281. this.particleEmitterType = particleEmitter;
  52282. return particleEmitter;
  52283. };
  52284. // Clone
  52285. /**
  52286. * Clones the particle system.
  52287. * @param name The name of the cloned object
  52288. * @param newEmitter The new emitter to use
  52289. * @returns the cloned particle system
  52290. */
  52291. ParticleSystem.prototype.clone = function (name, newEmitter) {
  52292. var custom = null;
  52293. var program = null;
  52294. if (this.customShader != null) {
  52295. program = this.customShader;
  52296. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52297. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52298. }
  52299. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  52300. result.customShader = program;
  52301. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  52302. if (newEmitter === undefined) {
  52303. newEmitter = this.emitter;
  52304. }
  52305. result.emitter = newEmitter;
  52306. if (this.particleTexture) {
  52307. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  52308. }
  52309. if (!this.preventAutoStart) {
  52310. result.start();
  52311. }
  52312. return result;
  52313. };
  52314. /**
  52315. * Serializes the particle system to a JSON object.
  52316. * @returns the JSON object
  52317. */
  52318. ParticleSystem.prototype.serialize = function () {
  52319. var serializationObject = {};
  52320. serializationObject.name = this.name;
  52321. serializationObject.id = this.id;
  52322. // Emitter
  52323. if (this.emitter.position) {
  52324. var emitterMesh = this.emitter;
  52325. serializationObject.emitterId = emitterMesh.id;
  52326. }
  52327. else {
  52328. var emitterPosition = this.emitter;
  52329. serializationObject.emitter = emitterPosition.asArray();
  52330. }
  52331. serializationObject.capacity = this.getCapacity();
  52332. if (this.particleTexture) {
  52333. serializationObject.textureName = this.particleTexture.name;
  52334. }
  52335. // Animations
  52336. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  52337. // Particle system
  52338. serializationObject.minAngularSpeed = this.minAngularSpeed;
  52339. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  52340. serializationObject.minSize = this.minSize;
  52341. serializationObject.maxSize = this.maxSize;
  52342. serializationObject.minEmitPower = this.minEmitPower;
  52343. serializationObject.maxEmitPower = this.maxEmitPower;
  52344. serializationObject.minLifeTime = this.minLifeTime;
  52345. serializationObject.maxLifeTime = this.maxLifeTime;
  52346. serializationObject.emitRate = this.emitRate;
  52347. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52348. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52349. serializationObject.gravity = this.gravity.asArray();
  52350. serializationObject.direction1 = this.direction1.asArray();
  52351. serializationObject.direction2 = this.direction2.asArray();
  52352. serializationObject.color1 = this.color1.asArray();
  52353. serializationObject.color2 = this.color2.asArray();
  52354. serializationObject.colorDead = this.colorDead.asArray();
  52355. serializationObject.updateSpeed = this.updateSpeed;
  52356. serializationObject.targetStopDuration = this.targetStopDuration;
  52357. serializationObject.textureMask = this.textureMask.asArray();
  52358. serializationObject.blendMode = this.blendMode;
  52359. serializationObject.customShader = this.customShader;
  52360. serializationObject.preventAutoStart = this.preventAutoStart;
  52361. serializationObject.startSpriteCellID = this.startSpriteCellID;
  52362. serializationObject.endSpriteCellID = this.endSpriteCellID;
  52363. serializationObject.spriteCellLoop = this.spriteCellLoop;
  52364. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  52365. serializationObject.spriteCellWidth = this.spriteCellWidth;
  52366. serializationObject.spriteCellHeight = this.spriteCellHeight;
  52367. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  52368. // Emitter
  52369. if (this.particleEmitterType) {
  52370. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  52371. }
  52372. return serializationObject;
  52373. };
  52374. /**
  52375. * Parses a JSON object to create a particle system.
  52376. * @param parsedParticleSystem The JSON object to parse
  52377. * @param scene The scene to create the particle system in
  52378. * @param rootUrl The root url to use to load external dependencies like texture
  52379. * @returns the Parsed particle system
  52380. */
  52381. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  52382. var name = parsedParticleSystem.name;
  52383. var custom = null;
  52384. var program = null;
  52385. if (parsedParticleSystem.customShader) {
  52386. program = parsedParticleSystem.customShader;
  52387. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52388. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52389. }
  52390. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  52391. particleSystem.customShader = program;
  52392. if (parsedParticleSystem.id) {
  52393. particleSystem.id = parsedParticleSystem.id;
  52394. }
  52395. // Auto start
  52396. if (parsedParticleSystem.preventAutoStart) {
  52397. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  52398. }
  52399. // Texture
  52400. if (parsedParticleSystem.textureName) {
  52401. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  52402. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  52403. }
  52404. // Emitter
  52405. if (parsedParticleSystem.emitterId) {
  52406. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  52407. }
  52408. else {
  52409. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  52410. }
  52411. // Animations
  52412. if (parsedParticleSystem.animations) {
  52413. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  52414. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  52415. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  52416. }
  52417. }
  52418. if (parsedParticleSystem.autoAnimate) {
  52419. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  52420. }
  52421. // Particle system
  52422. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  52423. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  52424. particleSystem.minSize = parsedParticleSystem.minSize;
  52425. particleSystem.maxSize = parsedParticleSystem.maxSize;
  52426. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  52427. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  52428. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  52429. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  52430. particleSystem.emitRate = parsedParticleSystem.emitRate;
  52431. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  52432. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  52433. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  52434. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  52435. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  52436. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  52437. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  52438. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  52439. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  52440. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  52441. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  52442. particleSystem.blendMode = parsedParticleSystem.blendMode;
  52443. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  52444. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  52445. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  52446. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  52447. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  52448. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  52449. if (!particleSystem.preventAutoStart) {
  52450. particleSystem.start();
  52451. }
  52452. return particleSystem;
  52453. };
  52454. /**
  52455. * Source color is added to the destination color without alpha affecting the result.
  52456. */
  52457. ParticleSystem.BLENDMODE_ONEONE = 0;
  52458. /**
  52459. * Blend current color and particle color using particle’s alpha.
  52460. */
  52461. ParticleSystem.BLENDMODE_STANDARD = 1;
  52462. return ParticleSystem;
  52463. }());
  52464. BABYLON.ParticleSystem = ParticleSystem;
  52465. })(BABYLON || (BABYLON = {}));
  52466. //# sourceMappingURL=babylon.particleSystem.js.map
  52467. "use strict";
  52468. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  52469. "use strict";
  52470. var BABYLON;
  52471. (function (BABYLON) {
  52472. /**
  52473. * Particle emitter emitting particles from the inside of a box.
  52474. * It emits the particles randomly between 2 given directions.
  52475. */
  52476. var BoxParticleEmitter = /** @class */ (function () {
  52477. /**
  52478. * Creates a new instance of @see BoxParticleEmitter
  52479. */
  52480. function BoxParticleEmitter() {
  52481. /**
  52482. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52483. */
  52484. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  52485. /**
  52486. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52487. */
  52488. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  52489. /**
  52490. * 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.
  52491. */
  52492. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  52493. /**
  52494. * 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.
  52495. */
  52496. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  52497. }
  52498. /**
  52499. * Called by the particle System when the direction is computed for the created particle.
  52500. * @param emitPower is the power of the particle (speed)
  52501. * @param worldMatrix is the world matrix of the particle system
  52502. * @param directionToUpdate is the direction vector to update with the result
  52503. * @param particle is the particle we are computed the direction for
  52504. */
  52505. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52506. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52507. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52508. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52509. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52510. };
  52511. /**
  52512. * Called by the particle System when the position is computed for the created particle.
  52513. * @param worldMatrix is the world matrix of the particle system
  52514. * @param positionToUpdate is the position vector to update with the result
  52515. * @param particle is the particle we are computed the position for
  52516. */
  52517. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52518. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  52519. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  52520. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  52521. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52522. };
  52523. /**
  52524. * Clones the current emitter and returns a copy of it
  52525. * @returns the new emitter
  52526. */
  52527. BoxParticleEmitter.prototype.clone = function () {
  52528. var newOne = new BoxParticleEmitter();
  52529. BABYLON.Tools.DeepCopy(this, newOne);
  52530. return newOne;
  52531. };
  52532. /**
  52533. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52534. * @param effect defines the update shader
  52535. */
  52536. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  52537. effect.setVector3("direction1", this.direction1);
  52538. effect.setVector3("direction2", this.direction2);
  52539. effect.setVector3("minEmitBox", this.minEmitBox);
  52540. effect.setVector3("maxEmitBox", this.maxEmitBox);
  52541. };
  52542. /**
  52543. * Returns a string to use to update the GPU particles update shader
  52544. * @returns a string containng the defines string
  52545. */
  52546. BoxParticleEmitter.prototype.getEffectDefines = function () {
  52547. return "#define BOXEMITTER";
  52548. };
  52549. /**
  52550. * Returns the string "BoxEmitter"
  52551. * @returns a string containing the class name
  52552. */
  52553. BoxParticleEmitter.prototype.getClassName = function () {
  52554. return "BoxEmitter";
  52555. };
  52556. /**
  52557. * Serializes the particle system to a JSON object.
  52558. * @returns the JSON object
  52559. */
  52560. BoxParticleEmitter.prototype.serialize = function () {
  52561. var serializationObject = {};
  52562. serializationObject.type = this.getClassName();
  52563. serializationObject.direction1 = this.direction1.asArray();
  52564. ;
  52565. serializationObject.direction2 = this.direction2.asArray();
  52566. ;
  52567. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52568. ;
  52569. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52570. ;
  52571. return serializationObject;
  52572. };
  52573. /**
  52574. * Parse properties from a JSON object
  52575. * @param serializationObject defines the JSON object
  52576. */
  52577. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  52578. this.direction1.copyFrom(serializationObject.direction1);
  52579. this.direction2.copyFrom(serializationObject.direction2);
  52580. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  52581. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  52582. };
  52583. return BoxParticleEmitter;
  52584. }());
  52585. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  52586. })(BABYLON || (BABYLON = {}));
  52587. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  52588. "use strict";
  52589. var BABYLON;
  52590. (function (BABYLON) {
  52591. /**
  52592. * Particle emitter emitting particles from the inside of a cone.
  52593. * It emits the particles alongside the cone volume from the base to the particle.
  52594. * The emission direction might be randomized.
  52595. */
  52596. var ConeParticleEmitter = /** @class */ (function () {
  52597. /**
  52598. * Creates a new instance of @see ConeParticleEmitter
  52599. * @param radius the radius of the emission cone (1 by default)
  52600. * @param angles the cone base angle (PI by default)
  52601. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52602. */
  52603. function ConeParticleEmitter(radius,
  52604. /**
  52605. * The radius of the emission cone.
  52606. */
  52607. angle,
  52608. /**
  52609. * The cone base angle.
  52610. */
  52611. directionRandomizer) {
  52612. if (radius === void 0) { radius = 1; }
  52613. if (angle === void 0) { angle = Math.PI; }
  52614. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52615. this.angle = angle;
  52616. this.directionRandomizer = directionRandomizer;
  52617. this.radius = radius;
  52618. }
  52619. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  52620. /**
  52621. * Gets the radius of the emission cone.
  52622. */
  52623. get: function () {
  52624. return this._radius;
  52625. },
  52626. /**
  52627. * Sets the radius of the emission cone.
  52628. */
  52629. set: function (value) {
  52630. this._radius = value;
  52631. if (this.angle !== 0) {
  52632. this._height = value / Math.tan(this.angle / 2);
  52633. }
  52634. else {
  52635. this._height = 1;
  52636. }
  52637. },
  52638. enumerable: true,
  52639. configurable: true
  52640. });
  52641. /**
  52642. * Called by the particle System when the direction is computed for the created particle.
  52643. * @param emitPower is the power of the particle (speed)
  52644. * @param worldMatrix is the world matrix of the particle system
  52645. * @param directionToUpdate is the direction vector to update with the result
  52646. * @param particle is the particle we are computed the direction for
  52647. */
  52648. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52649. if (this.angle === 0) {
  52650. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  52651. }
  52652. else {
  52653. // measure the direction Vector from the emitter to the particle.
  52654. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52655. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52656. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52657. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52658. direction.x += randX;
  52659. direction.y += randY;
  52660. direction.z += randZ;
  52661. direction.normalize();
  52662. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52663. }
  52664. };
  52665. /**
  52666. * Called by the particle System when the position is computed for the created particle.
  52667. * @param worldMatrix is the world matrix of the particle system
  52668. * @param positionToUpdate is the position vector to update with the result
  52669. * @param particle is the particle we are computed the position for
  52670. */
  52671. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52672. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  52673. var h = BABYLON.Scalar.RandomRange(0, 1);
  52674. // Better distribution in a cone at normal angles.
  52675. h = 1 - h * h;
  52676. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  52677. radius = radius * h / this._height;
  52678. var randX = radius * Math.sin(s);
  52679. var randZ = radius * Math.cos(s);
  52680. var randY = h * this._height;
  52681. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52682. };
  52683. /**
  52684. * Clones the current emitter and returns a copy of it
  52685. * @returns the new emitter
  52686. */
  52687. ConeParticleEmitter.prototype.clone = function () {
  52688. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  52689. BABYLON.Tools.DeepCopy(this, newOne);
  52690. return newOne;
  52691. };
  52692. /**
  52693. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52694. * @param effect defines the update shader
  52695. */
  52696. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  52697. effect.setFloat("radius", this.radius);
  52698. effect.setFloat("angle", this.angle);
  52699. effect.setFloat("height", this._height);
  52700. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52701. };
  52702. /**
  52703. * Returns a string to use to update the GPU particles update shader
  52704. * @returns a string containng the defines string
  52705. */
  52706. ConeParticleEmitter.prototype.getEffectDefines = function () {
  52707. return "#define CONEEMITTER";
  52708. };
  52709. /**
  52710. * Returns the string "BoxEmitter"
  52711. * @returns a string containing the class name
  52712. */
  52713. ConeParticleEmitter.prototype.getClassName = function () {
  52714. return "ConeEmitter";
  52715. };
  52716. /**
  52717. * Serializes the particle system to a JSON object.
  52718. * @returns the JSON object
  52719. */
  52720. ConeParticleEmitter.prototype.serialize = function () {
  52721. var serializationObject = {};
  52722. serializationObject.type = this.getClassName();
  52723. serializationObject.radius = this.radius;
  52724. serializationObject.angle = this.angle;
  52725. serializationObject.directionRandomizer = this.directionRandomizer;
  52726. return serializationObject;
  52727. };
  52728. /**
  52729. * Parse properties from a JSON object
  52730. * @param serializationObject defines the JSON object
  52731. */
  52732. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  52733. this.radius = serializationObject.radius;
  52734. this.angle = serializationObject.angle;
  52735. this.directionRandomizer = serializationObject.directionRandomizer;
  52736. };
  52737. return ConeParticleEmitter;
  52738. }());
  52739. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  52740. })(BABYLON || (BABYLON = {}));
  52741. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  52742. "use strict";
  52743. var BABYLON;
  52744. (function (BABYLON) {
  52745. /**
  52746. * Particle emitter emitting particles from the inside of a sphere.
  52747. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  52748. */
  52749. var SphereParticleEmitter = /** @class */ (function () {
  52750. /**
  52751. * Creates a new instance of @see SphereParticleEmitter
  52752. * @param radius the radius of the emission sphere (1 by default)
  52753. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52754. */
  52755. function SphereParticleEmitter(
  52756. /**
  52757. * The radius of the emission sphere.
  52758. */
  52759. radius,
  52760. /**
  52761. * How much to randomize the particle direction [0-1].
  52762. */
  52763. directionRandomizer) {
  52764. if (radius === void 0) { radius = 1; }
  52765. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52766. this.radius = radius;
  52767. this.directionRandomizer = directionRandomizer;
  52768. }
  52769. /**
  52770. * Called by the particle System when the direction is computed for the created particle.
  52771. * @param emitPower is the power of the particle (speed)
  52772. * @param worldMatrix is the world matrix of the particle system
  52773. * @param directionToUpdate is the direction vector to update with the result
  52774. * @param particle is the particle we are computed the direction for
  52775. */
  52776. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52777. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52778. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52779. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52780. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52781. direction.x += randX;
  52782. direction.y += randY;
  52783. direction.z += randZ;
  52784. direction.normalize();
  52785. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52786. };
  52787. /**
  52788. * Called by the particle System when the position is computed for the created particle.
  52789. * @param worldMatrix is the world matrix of the particle system
  52790. * @param positionToUpdate is the position vector to update with the result
  52791. * @param particle is the particle we are computed the position for
  52792. */
  52793. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52794. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  52795. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  52796. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  52797. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  52798. var randY = randRadius * Math.cos(theta);
  52799. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  52800. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52801. };
  52802. /**
  52803. * Clones the current emitter and returns a copy of it
  52804. * @returns the new emitter
  52805. */
  52806. SphereParticleEmitter.prototype.clone = function () {
  52807. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  52808. BABYLON.Tools.DeepCopy(this, newOne);
  52809. return newOne;
  52810. };
  52811. /**
  52812. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52813. * @param effect defines the update shader
  52814. */
  52815. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  52816. effect.setFloat("radius", this.radius);
  52817. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52818. };
  52819. /**
  52820. * Returns a string to use to update the GPU particles update shader
  52821. * @returns a string containng the defines string
  52822. */
  52823. SphereParticleEmitter.prototype.getEffectDefines = function () {
  52824. return "#define SPHEREEMITTER";
  52825. };
  52826. /**
  52827. * Returns the string "SphereParticleEmitter"
  52828. * @returns a string containing the class name
  52829. */
  52830. SphereParticleEmitter.prototype.getClassName = function () {
  52831. return "SphereParticleEmitter";
  52832. };
  52833. /**
  52834. * Serializes the particle system to a JSON object.
  52835. * @returns the JSON object
  52836. */
  52837. SphereParticleEmitter.prototype.serialize = function () {
  52838. var serializationObject = {};
  52839. serializationObject.type = this.getClassName();
  52840. serializationObject.radius = this.radius;
  52841. serializationObject.directionRandomizer = this.directionRandomizer;
  52842. return serializationObject;
  52843. };
  52844. /**
  52845. * Parse properties from a JSON object
  52846. * @param serializationObject defines the JSON object
  52847. */
  52848. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  52849. this.radius = serializationObject.radius;
  52850. this.directionRandomizer = serializationObject.directionRandomizer;
  52851. };
  52852. return SphereParticleEmitter;
  52853. }());
  52854. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  52855. /**
  52856. * Particle emitter emitting particles from the inside of a sphere.
  52857. * It emits the particles randomly between two vectors.
  52858. */
  52859. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  52860. __extends(SphereDirectedParticleEmitter, _super);
  52861. /**
  52862. * Creates a new instance of @see SphereDirectedParticleEmitter
  52863. * @param radius the radius of the emission sphere (1 by default)
  52864. * @param direction1 the min limit of the emission direction (up vector by default)
  52865. * @param direction2 the max limit of the emission direction (up vector by default)
  52866. */
  52867. function SphereDirectedParticleEmitter(radius,
  52868. /**
  52869. * The min limit of the emission direction.
  52870. */
  52871. direction1,
  52872. /**
  52873. * The max limit of the emission direction.
  52874. */
  52875. direction2) {
  52876. if (radius === void 0) { radius = 1; }
  52877. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  52878. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  52879. var _this = _super.call(this, radius) || this;
  52880. _this.direction1 = direction1;
  52881. _this.direction2 = direction2;
  52882. return _this;
  52883. }
  52884. /**
  52885. * Called by the particle System when the direction is computed for the created particle.
  52886. * @param emitPower is the power of the particle (speed)
  52887. * @param worldMatrix is the world matrix of the particle system
  52888. * @param directionToUpdate is the direction vector to update with the result
  52889. * @param particle is the particle we are computed the direction for
  52890. */
  52891. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52892. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52893. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52894. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52895. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52896. };
  52897. /**
  52898. * Clones the current emitter and returns a copy of it
  52899. * @returns the new emitter
  52900. */
  52901. SphereDirectedParticleEmitter.prototype.clone = function () {
  52902. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  52903. BABYLON.Tools.DeepCopy(this, newOne);
  52904. return newOne;
  52905. };
  52906. /**
  52907. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52908. * @param effect defines the update shader
  52909. */
  52910. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  52911. effect.setFloat("radius", this.radius);
  52912. effect.setVector3("direction1", this.direction1);
  52913. effect.setVector3("direction2", this.direction2);
  52914. };
  52915. /**
  52916. * Returns a string to use to update the GPU particles update shader
  52917. * @returns a string containng the defines string
  52918. */
  52919. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  52920. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  52921. };
  52922. /**
  52923. * Returns the string "SphereDirectedParticleEmitter"
  52924. * @returns a string containing the class name
  52925. */
  52926. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  52927. return "SphereDirectedParticleEmitter";
  52928. };
  52929. /**
  52930. * Serializes the particle system to a JSON object.
  52931. * @returns the JSON object
  52932. */
  52933. SphereDirectedParticleEmitter.prototype.serialize = function () {
  52934. var serializationObject = _super.prototype.serialize.call(this);
  52935. ;
  52936. serializationObject.direction1 = this.direction1.asArray();
  52937. ;
  52938. serializationObject.direction2 = this.direction2.asArray();
  52939. ;
  52940. return serializationObject;
  52941. };
  52942. /**
  52943. * Parse properties from a JSON object
  52944. * @param serializationObject defines the JSON object
  52945. */
  52946. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  52947. _super.prototype.parse.call(this, serializationObject);
  52948. this.direction1.copyFrom(serializationObject.direction1);
  52949. this.direction2.copyFrom(serializationObject.direction2);
  52950. };
  52951. return SphereDirectedParticleEmitter;
  52952. }(SphereParticleEmitter));
  52953. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  52954. })(BABYLON || (BABYLON = {}));
  52955. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  52956. "use strict";
  52957. var __assign = (this && this.__assign) || Object.assign || function(t) {
  52958. for (var s, i = 1, n = arguments.length; i < n; i++) {
  52959. s = arguments[i];
  52960. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  52961. t[p] = s[p];
  52962. }
  52963. return t;
  52964. };
  52965. var BABYLON;
  52966. (function (BABYLON) {
  52967. /**
  52968. * This represents a GPU particle system in Babylon
  52969. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  52970. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  52971. */
  52972. var GPUParticleSystem = /** @class */ (function () {
  52973. /**
  52974. * Instantiates a GPU particle system.
  52975. * 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.
  52976. * @param name The name of the particle system
  52977. * @param capacity The max number of particles alive at the same time
  52978. * @param scene The scene the particle system belongs to
  52979. */
  52980. function GPUParticleSystem(name, options, scene) {
  52981. /**
  52982. * The emitter represents the Mesh or position we are attaching the particle system to.
  52983. */
  52984. this.emitter = null;
  52985. /**
  52986. * The rendering group used by the Particle system to chose when to render.
  52987. */
  52988. this.renderingGroupId = 0;
  52989. /**
  52990. * The layer mask we are rendering the particles through.
  52991. */
  52992. this.layerMask = 0x0FFFFFFF;
  52993. this._targetIndex = 0;
  52994. this._currentRenderId = -1;
  52995. this._started = false;
  52996. this._stopped = false;
  52997. this._timeDelta = 0;
  52998. this._attributesStrideSize = 14;
  52999. this._actualFrame = 0;
  53000. /**
  53001. * List of animations used by the particle system.
  53002. */
  53003. this.animations = [];
  53004. /**
  53005. * An event triggered when the system is disposed.
  53006. */
  53007. this.onDisposeObservable = new BABYLON.Observable();
  53008. /**
  53009. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  53010. */
  53011. this.updateSpeed = 0.01;
  53012. /**
  53013. * The amount of time the particle system is running (depends of the overall update speed).
  53014. */
  53015. this.targetStopDuration = 0;
  53016. /**
  53017. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  53018. */
  53019. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  53020. /**
  53021. * Minimum life time of emitting particles.
  53022. */
  53023. this.minLifeTime = 1;
  53024. /**
  53025. * Maximum life time of emitting particles.
  53026. */
  53027. this.maxLifeTime = 1;
  53028. /**
  53029. * Minimum Size of emitting particles.
  53030. */
  53031. this.minSize = 1;
  53032. /**
  53033. * Maximum Size of emitting particles.
  53034. */
  53035. this.maxSize = 1;
  53036. /**
  53037. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  53038. */
  53039. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53040. /**
  53041. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  53042. */
  53043. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53044. /**
  53045. * Color the particle will have at the end of its lifetime.
  53046. */
  53047. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  53048. /**
  53049. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  53050. */
  53051. this.emitRate = 100;
  53052. /**
  53053. * You can use gravity if you want to give an orientation to your particles.
  53054. */
  53055. this.gravity = BABYLON.Vector3.Zero();
  53056. /**
  53057. * Minimum power of emitting particles.
  53058. */
  53059. this.minEmitPower = 1;
  53060. /**
  53061. * Maximum power of emitting particles.
  53062. */
  53063. this.maxEmitPower = 1;
  53064. /**
  53065. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  53066. * to override the particles.
  53067. */
  53068. this.forceDepthWrite = false;
  53069. this.id = name;
  53070. this.name = name;
  53071. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53072. this._engine = this._scene.getEngine();
  53073. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  53074. this._capacity = fullOptions.capacity;
  53075. this._activeCount = fullOptions.capacity;
  53076. this._currentActiveCount = 0;
  53077. this._scene.particleSystems.push(this);
  53078. this._updateEffectOptions = {
  53079. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  53080. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  53081. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  53082. uniformBuffersNames: [],
  53083. samplers: ["randomSampler"],
  53084. defines: "",
  53085. fallbacks: null,
  53086. onCompiled: null,
  53087. onError: null,
  53088. indexParameters: null,
  53089. maxSimultaneousLights: 0,
  53090. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  53091. };
  53092. // Random data
  53093. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  53094. var d = [];
  53095. for (var i = 0; i < maxTextureSize; ++i) {
  53096. d.push(Math.random());
  53097. d.push(Math.random());
  53098. d.push(Math.random());
  53099. d.push(Math.random());
  53100. }
  53101. 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);
  53102. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53103. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53104. this._randomTextureSize = maxTextureSize;
  53105. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  53106. }
  53107. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  53108. /**
  53109. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  53110. */
  53111. get: function () {
  53112. if (!BABYLON.Engine.LastCreatedEngine) {
  53113. return false;
  53114. }
  53115. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  53116. },
  53117. enumerable: true,
  53118. configurable: true
  53119. });
  53120. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  53121. /**
  53122. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  53123. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53124. */
  53125. get: function () {
  53126. if (this.particleEmitterType.direction1) {
  53127. return this.particleEmitterType.direction1;
  53128. }
  53129. return BABYLON.Vector3.Zero();
  53130. },
  53131. set: function (value) {
  53132. if (this.particleEmitterType.direction1) {
  53133. this.particleEmitterType.direction1 = value;
  53134. }
  53135. },
  53136. enumerable: true,
  53137. configurable: true
  53138. });
  53139. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  53140. /**
  53141. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  53142. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53143. */
  53144. get: function () {
  53145. if (this.particleEmitterType.direction2) {
  53146. return this.particleEmitterType.direction2;
  53147. }
  53148. return BABYLON.Vector3.Zero();
  53149. },
  53150. set: function (value) {
  53151. if (this.particleEmitterType.direction2) {
  53152. this.particleEmitterType.direction2 = value;
  53153. }
  53154. },
  53155. enumerable: true,
  53156. configurable: true
  53157. });
  53158. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  53159. /**
  53160. * 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.
  53161. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53162. */
  53163. get: function () {
  53164. if (this.particleEmitterType.minEmitBox) {
  53165. return this.particleEmitterType.minEmitBox;
  53166. }
  53167. return BABYLON.Vector3.Zero();
  53168. },
  53169. set: function (value) {
  53170. if (this.particleEmitterType.minEmitBox) {
  53171. this.particleEmitterType.minEmitBox = value;
  53172. }
  53173. },
  53174. enumerable: true,
  53175. configurable: true
  53176. });
  53177. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  53178. /**
  53179. * 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.
  53180. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53181. */
  53182. get: function () {
  53183. if (this.particleEmitterType.maxEmitBox) {
  53184. return this.particleEmitterType.maxEmitBox;
  53185. }
  53186. return BABYLON.Vector3.Zero();
  53187. },
  53188. set: function (value) {
  53189. if (this.particleEmitterType.maxEmitBox) {
  53190. this.particleEmitterType.maxEmitBox = value;
  53191. }
  53192. },
  53193. enumerable: true,
  53194. configurable: true
  53195. });
  53196. /**
  53197. * Gets the maximum number of particles active at the same time.
  53198. * @returns The max number of active particles.
  53199. */
  53200. GPUParticleSystem.prototype.getCapacity = function () {
  53201. return this._capacity;
  53202. };
  53203. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  53204. /**
  53205. * Gets or set the number of active particles
  53206. */
  53207. get: function () {
  53208. return this._activeCount;
  53209. },
  53210. set: function (value) {
  53211. this._activeCount = Math.min(value, this._capacity);
  53212. },
  53213. enumerable: true,
  53214. configurable: true
  53215. });
  53216. /**
  53217. * Is this system ready to be used/rendered
  53218. * @return true if the system is ready
  53219. */
  53220. GPUParticleSystem.prototype.isReady = function () {
  53221. if (!this.emitter || !this._updateEffect || !this._renderEffect ||
  53222. !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  53223. return false;
  53224. }
  53225. return true;
  53226. };
  53227. /**
  53228. * Gets Wether the system has been started.
  53229. * @returns True if it has been started, otherwise false.
  53230. */
  53231. GPUParticleSystem.prototype.isStarted = function () {
  53232. return this._started;
  53233. };
  53234. /**
  53235. * Starts the particle system and begins to emit.
  53236. */
  53237. GPUParticleSystem.prototype.start = function () {
  53238. this._started = true;
  53239. this._stopped = false;
  53240. };
  53241. /**
  53242. * Stops the particle system.
  53243. */
  53244. GPUParticleSystem.prototype.stop = function () {
  53245. this._stopped = true;
  53246. };
  53247. /**
  53248. * Remove all active particles
  53249. */
  53250. GPUParticleSystem.prototype.reset = function () {
  53251. this._releaseBuffers();
  53252. this._releaseVAOs();
  53253. this._currentActiveCount = 0;
  53254. this._targetIndex = 0;
  53255. };
  53256. /**
  53257. * Returns the string "GPUParticleSystem"
  53258. * @returns a string containing the class name
  53259. */
  53260. GPUParticleSystem.prototype.getClassName = function () {
  53261. return "GPUParticleSystem";
  53262. };
  53263. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  53264. var updateVertexBuffers = {};
  53265. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  53266. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  53267. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  53268. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  53269. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  53270. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  53271. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  53272. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  53273. this._engine.bindArrayBuffer(null);
  53274. return vao;
  53275. };
  53276. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  53277. var renderVertexBuffers = {};
  53278. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  53279. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  53280. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  53281. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  53282. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  53283. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  53284. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  53285. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  53286. this._engine.bindArrayBuffer(null);
  53287. return vao;
  53288. };
  53289. GPUParticleSystem.prototype._initialize = function (force) {
  53290. if (force === void 0) { force = false; }
  53291. if (this._buffer0 && !force) {
  53292. return;
  53293. }
  53294. var engine = this._scene.getEngine();
  53295. var data = new Array();
  53296. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  53297. // position
  53298. data.push(0.0);
  53299. data.push(0.0);
  53300. data.push(0.0);
  53301. // Age and life
  53302. data.push(0.0); // create the particle as a dead one to create a new one at start
  53303. data.push(0.0);
  53304. // Seed
  53305. data.push(Math.random());
  53306. // Size
  53307. data.push(0.0);
  53308. // color
  53309. data.push(0.0);
  53310. data.push(0.0);
  53311. data.push(0.0);
  53312. data.push(0.0);
  53313. // direction
  53314. data.push(0.0);
  53315. data.push(0.0);
  53316. data.push(0.0);
  53317. }
  53318. // Sprite data
  53319. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  53320. -0.5, 0.5, 0, 1,
  53321. -0.5, -0.5, 0, 0,
  53322. 0.5, -0.5, 1, 0]);
  53323. // Buffers
  53324. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  53325. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  53326. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  53327. // Update VAO
  53328. this._updateVAO = [];
  53329. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  53330. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  53331. // Render VAO
  53332. this._renderVAO = [];
  53333. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  53334. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  53335. // Links
  53336. this._sourceBuffer = this._buffer0;
  53337. this._targetBuffer = this._buffer1;
  53338. };
  53339. /** @ignore */
  53340. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  53341. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  53342. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  53343. return;
  53344. }
  53345. this._updateEffectOptions.defines = defines;
  53346. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  53347. };
  53348. /** @ignore */
  53349. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  53350. var defines = "";
  53351. if (this._scene.clipPlane) {
  53352. defines = "\n#define CLIPPLANE";
  53353. }
  53354. if (this._renderEffect && this._renderEffect.defines === defines) {
  53355. return;
  53356. }
  53357. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  53358. };
  53359. /**
  53360. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  53361. */
  53362. GPUParticleSystem.prototype.animate = function () {
  53363. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  53364. this._actualFrame += this._timeDelta;
  53365. if (!this._stopped) {
  53366. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  53367. this.stop();
  53368. }
  53369. }
  53370. };
  53371. /**
  53372. * Renders the particle system in its current state.
  53373. * @returns the current number of particles
  53374. */
  53375. GPUParticleSystem.prototype.render = function () {
  53376. if (!this._started) {
  53377. return 0;
  53378. }
  53379. this._recreateUpdateEffect();
  53380. this._recreateRenderEffect();
  53381. if (!this.isReady()) {
  53382. return 0;
  53383. }
  53384. if (this._currentRenderId === this._scene.getRenderId()) {
  53385. return 0;
  53386. }
  53387. this._currentRenderId = this._scene.getRenderId();
  53388. // Get everything ready to render
  53389. this._initialize();
  53390. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  53391. // Enable update effect
  53392. this._engine.enableEffect(this._updateEffect);
  53393. this._engine.setState(false);
  53394. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  53395. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  53396. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  53397. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  53398. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  53399. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  53400. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  53401. this._updateEffect.setDirectColor4("color1", this.color1);
  53402. this._updateEffect.setDirectColor4("color2", this.color2);
  53403. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  53404. this._updateEffect.setVector3("gravity", this.gravity);
  53405. if (this.particleEmitterType) {
  53406. this.particleEmitterType.applyToShader(this._updateEffect);
  53407. }
  53408. var emitterWM;
  53409. if (this.emitter.position) {
  53410. var emitterMesh = this.emitter;
  53411. emitterWM = emitterMesh.getWorldMatrix();
  53412. }
  53413. else {
  53414. var emitterPosition = this.emitter;
  53415. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  53416. }
  53417. this._updateEffect.setMatrix("emitterWM", emitterWM);
  53418. // Bind source VAO
  53419. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  53420. // Update
  53421. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  53422. this._engine.setRasterizerState(false);
  53423. this._engine.beginTransformFeedback();
  53424. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  53425. this._engine.endTransformFeedback();
  53426. this._engine.setRasterizerState(true);
  53427. this._engine.bindTransformFeedbackBuffer(null);
  53428. // Enable render effect
  53429. this._engine.enableEffect(this._renderEffect);
  53430. var viewMatrix = this._scene.getViewMatrix();
  53431. this._renderEffect.setMatrix("view", viewMatrix);
  53432. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  53433. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  53434. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  53435. if (this._scene.clipPlane) {
  53436. var clipPlane = this._scene.clipPlane;
  53437. var invView = viewMatrix.clone();
  53438. invView.invert();
  53439. this._renderEffect.setMatrix("invView", invView);
  53440. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  53441. }
  53442. // Draw order
  53443. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  53444. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  53445. }
  53446. else {
  53447. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53448. }
  53449. if (this.forceDepthWrite) {
  53450. this._engine.setDepthWrite(true);
  53451. }
  53452. // Bind source VAO
  53453. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  53454. // Render
  53455. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  53456. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53457. // Switch VAOs
  53458. this._targetIndex++;
  53459. if (this._targetIndex === 2) {
  53460. this._targetIndex = 0;
  53461. }
  53462. // Switch buffers
  53463. var tmpBuffer = this._sourceBuffer;
  53464. this._sourceBuffer = this._targetBuffer;
  53465. this._targetBuffer = tmpBuffer;
  53466. return this._currentActiveCount;
  53467. };
  53468. /**
  53469. * Rebuilds the particle system
  53470. */
  53471. GPUParticleSystem.prototype.rebuild = function () {
  53472. this._initialize(true);
  53473. };
  53474. GPUParticleSystem.prototype._releaseBuffers = function () {
  53475. if (this._buffer0) {
  53476. this._buffer0.dispose();
  53477. this._buffer0 = null;
  53478. }
  53479. if (this._buffer1) {
  53480. this._buffer1.dispose();
  53481. this._buffer1 = null;
  53482. }
  53483. if (this._spriteBuffer) {
  53484. this._spriteBuffer.dispose();
  53485. this._spriteBuffer = null;
  53486. }
  53487. };
  53488. GPUParticleSystem.prototype._releaseVAOs = function () {
  53489. if (!this._updateVAO) {
  53490. return;
  53491. }
  53492. for (var index = 0; index < this._updateVAO.length; index++) {
  53493. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  53494. }
  53495. this._updateVAO = [];
  53496. for (var index = 0; index < this._renderVAO.length; index++) {
  53497. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  53498. }
  53499. this._renderVAO = [];
  53500. };
  53501. /**
  53502. * Disposes the particle system and free the associated resources
  53503. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  53504. */
  53505. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  53506. if (disposeTexture === void 0) { disposeTexture = true; }
  53507. var index = this._scene.particleSystems.indexOf(this);
  53508. if (index > -1) {
  53509. this._scene.particleSystems.splice(index, 1);
  53510. }
  53511. this._releaseBuffers();
  53512. this._releaseVAOs();
  53513. if (this._randomTexture) {
  53514. this._randomTexture.dispose();
  53515. this._randomTexture = null;
  53516. }
  53517. if (disposeTexture && this.particleTexture) {
  53518. this.particleTexture.dispose();
  53519. this.particleTexture = null;
  53520. }
  53521. // Callback
  53522. this.onDisposeObservable.notifyObservers(this);
  53523. this.onDisposeObservable.clear();
  53524. };
  53525. /**
  53526. * Clones the particle system.
  53527. * @param name The name of the cloned object
  53528. * @param newEmitter The new emitter to use
  53529. * @returns the cloned particle system
  53530. */
  53531. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  53532. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  53533. BABYLON.Tools.DeepCopy(this, result);
  53534. if (newEmitter === undefined) {
  53535. newEmitter = this.emitter;
  53536. }
  53537. result.emitter = newEmitter;
  53538. if (this.particleTexture) {
  53539. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  53540. }
  53541. return result;
  53542. };
  53543. /**
  53544. * Serializes the particle system to a JSON object.
  53545. * @returns the JSON object
  53546. */
  53547. GPUParticleSystem.prototype.serialize = function () {
  53548. var serializationObject = {};
  53549. serializationObject.name = this.name;
  53550. serializationObject.id = this.id;
  53551. // Emitter
  53552. if (this.emitter.position) {
  53553. var emitterMesh = this.emitter;
  53554. serializationObject.emitterId = emitterMesh.id;
  53555. }
  53556. else {
  53557. var emitterPosition = this.emitter;
  53558. serializationObject.emitter = emitterPosition.asArray();
  53559. }
  53560. serializationObject.capacity = this.getCapacity();
  53561. if (this.particleTexture) {
  53562. serializationObject.textureName = this.particleTexture.name;
  53563. }
  53564. // Animations
  53565. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  53566. // Particle system
  53567. serializationObject.activeParticleCount = this.activeParticleCount;
  53568. serializationObject.randomTextureSize = this._randomTextureSize;
  53569. serializationObject.minSize = this.minSize;
  53570. serializationObject.maxSize = this.maxSize;
  53571. serializationObject.minEmitPower = this.minEmitPower;
  53572. serializationObject.maxEmitPower = this.maxEmitPower;
  53573. serializationObject.minLifeTime = this.minLifeTime;
  53574. serializationObject.maxLifeTime = this.maxLifeTime;
  53575. serializationObject.emitRate = this.emitRate;
  53576. serializationObject.gravity = this.gravity.asArray();
  53577. serializationObject.color1 = this.color1.asArray();
  53578. serializationObject.color2 = this.color2.asArray();
  53579. serializationObject.colorDead = this.colorDead.asArray();
  53580. serializationObject.updateSpeed = this.updateSpeed;
  53581. serializationObject.targetStopDuration = this.targetStopDuration;
  53582. serializationObject.blendMode = this.blendMode;
  53583. // Emitter
  53584. if (this.particleEmitterType) {
  53585. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  53586. }
  53587. return serializationObject;
  53588. };
  53589. /**
  53590. * Parses a JSON object to create a GPU particle system.
  53591. * @param parsedParticleSystem The JSON object to parse
  53592. * @param scene The scene to create the particle system in
  53593. * @param rootUrl The root url to use to load external dependencies like texture
  53594. * @returns the parsed GPU particle system
  53595. */
  53596. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  53597. var name = parsedParticleSystem.name;
  53598. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  53599. if (parsedParticleSystem.id) {
  53600. particleSystem.id = parsedParticleSystem.id;
  53601. }
  53602. // Texture
  53603. if (parsedParticleSystem.textureName) {
  53604. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  53605. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  53606. }
  53607. // Emitter
  53608. if (parsedParticleSystem.emitterId) {
  53609. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  53610. }
  53611. else {
  53612. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  53613. }
  53614. // Animations
  53615. if (parsedParticleSystem.animations) {
  53616. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  53617. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  53618. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  53619. }
  53620. }
  53621. // Particle system
  53622. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  53623. particleSystem.minSize = parsedParticleSystem.minSize;
  53624. particleSystem.maxSize = parsedParticleSystem.maxSize;
  53625. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  53626. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  53627. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  53628. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  53629. particleSystem.emitRate = parsedParticleSystem.emitRate;
  53630. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  53631. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  53632. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  53633. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  53634. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  53635. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  53636. particleSystem.blendMode = parsedParticleSystem.blendMode;
  53637. // Emitter
  53638. if (parsedParticleSystem.particleEmitterType) {
  53639. var emitterType = void 0;
  53640. switch (parsedParticleSystem.particleEmitterType.type) {
  53641. case "SphereEmitter":
  53642. emitterType = new BABYLON.SphereParticleEmitter();
  53643. break;
  53644. case "SphereDirectedParticleEmitter":
  53645. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  53646. break;
  53647. case "ConeEmitter":
  53648. emitterType = new BABYLON.ConeParticleEmitter();
  53649. break;
  53650. case "BoxEmitter":
  53651. default:
  53652. emitterType = new BABYLON.BoxParticleEmitter();
  53653. break;
  53654. }
  53655. emitterType.parse(parsedParticleSystem.particleEmitterType);
  53656. particleSystem.particleEmitterType = emitterType;
  53657. }
  53658. return particleSystem;
  53659. };
  53660. return GPUParticleSystem;
  53661. }());
  53662. BABYLON.GPUParticleSystem = GPUParticleSystem;
  53663. })(BABYLON || (BABYLON = {}));
  53664. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  53665. "use strict";
  53666. var BABYLON;
  53667. (function (BABYLON) {
  53668. /**
  53669. * Represents one particle of a solid particle system.
  53670. * @see SolidParticleSystem
  53671. */
  53672. var SolidParticle = /** @class */ (function () {
  53673. /**
  53674. * Creates a Solid Particle object.
  53675. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  53676. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  53677. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  53678. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  53679. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  53680. * @param shapeId (integer) is the model shape identifier in the SPS.
  53681. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  53682. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  53683. */
  53684. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  53685. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  53686. /**
  53687. * particle global index
  53688. */
  53689. this.idx = 0;
  53690. /**
  53691. * The color of the particle
  53692. */
  53693. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53694. /**
  53695. * The world space position of the particle.
  53696. */
  53697. this.position = BABYLON.Vector3.Zero();
  53698. /**
  53699. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  53700. */
  53701. this.rotation = BABYLON.Vector3.Zero();
  53702. /**
  53703. * The scaling of the particle.
  53704. */
  53705. this.scaling = BABYLON.Vector3.One();
  53706. /**
  53707. * The uvs of the particle.
  53708. */
  53709. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  53710. /**
  53711. * The current speed of the particle.
  53712. */
  53713. this.velocity = BABYLON.Vector3.Zero();
  53714. /**
  53715. * The pivot point in the particle local space.
  53716. */
  53717. this.pivot = BABYLON.Vector3.Zero();
  53718. /**
  53719. * Must the particle be translated from its pivot point in its local space ?
  53720. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  53721. * Default : false
  53722. */
  53723. this.translateFromPivot = false;
  53724. /**
  53725. * Is the particle active or not ?
  53726. */
  53727. this.alive = true;
  53728. /**
  53729. * Is the particle visible or not ?
  53730. */
  53731. this.isVisible = true;
  53732. /**
  53733. * Index of this particle in the global "positions" array (Internal use)
  53734. */
  53735. this._pos = 0;
  53736. /**
  53737. * Index of this particle in the global "indices" array (Internal use)
  53738. */
  53739. this._ind = 0;
  53740. /**
  53741. * ModelShape id of this particle
  53742. */
  53743. this.shapeId = 0;
  53744. /**
  53745. * Index of the particle in its shape id (Internal use)
  53746. */
  53747. this.idxInShape = 0;
  53748. /**
  53749. * Still set as invisible in order to skip useless computations (Internal use)
  53750. */
  53751. this._stillInvisible = false;
  53752. /**
  53753. * Last computed particle rotation matrix
  53754. */
  53755. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  53756. /**
  53757. * Parent particle Id, if any.
  53758. * Default null.
  53759. */
  53760. this.parentId = null;
  53761. /**
  53762. * Internal global position in the SPS.
  53763. */
  53764. this._globalPosition = BABYLON.Vector3.Zero();
  53765. this.idx = particleIndex;
  53766. this._pos = positionIndex;
  53767. this._ind = indiceIndex;
  53768. this._model = model;
  53769. this.shapeId = shapeId;
  53770. this.idxInShape = idxInShape;
  53771. this._sps = sps;
  53772. if (modelBoundingInfo) {
  53773. this._modelBoundingInfo = modelBoundingInfo;
  53774. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  53775. }
  53776. }
  53777. Object.defineProperty(SolidParticle.prototype, "scale", {
  53778. /**
  53779. * Legacy support, changed scale to scaling
  53780. */
  53781. get: function () {
  53782. return this.scaling;
  53783. },
  53784. /**
  53785. * Legacy support, changed scale to scaling
  53786. */
  53787. set: function (scale) {
  53788. this.scaling = scale;
  53789. },
  53790. enumerable: true,
  53791. configurable: true
  53792. });
  53793. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  53794. /**
  53795. * Legacy support, changed quaternion to rotationQuaternion
  53796. */
  53797. get: function () {
  53798. return this.rotationQuaternion;
  53799. },
  53800. /**
  53801. * Legacy support, changed quaternion to rotationQuaternion
  53802. */
  53803. set: function (q) {
  53804. this.rotationQuaternion = q;
  53805. },
  53806. enumerable: true,
  53807. configurable: true
  53808. });
  53809. /**
  53810. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  53811. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  53812. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  53813. * @returns true if it intersects
  53814. */
  53815. SolidParticle.prototype.intersectsMesh = function (target) {
  53816. if (!this._boundingInfo || !target._boundingInfo) {
  53817. return false;
  53818. }
  53819. if (this._sps._bSphereOnly) {
  53820. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  53821. }
  53822. return this._boundingInfo.intersects(target._boundingInfo, false);
  53823. };
  53824. return SolidParticle;
  53825. }());
  53826. BABYLON.SolidParticle = SolidParticle;
  53827. /**
  53828. * Represents the shape of the model used by one particle of a solid particle system.
  53829. * SPS internal tool, don't use it manually.
  53830. * @see SolidParticleSystem
  53831. */
  53832. var ModelShape = /** @class */ (function () {
  53833. /**
  53834. * 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.
  53835. * SPS internal tool, don't use it manually.
  53836. * @ignore
  53837. */
  53838. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  53839. /**
  53840. * length of the shape in the model indices array (internal use)
  53841. */
  53842. this._indicesLength = 0;
  53843. this.shapeID = id;
  53844. this._shape = shape;
  53845. this._indicesLength = indicesLength;
  53846. this._shapeUV = shapeUV;
  53847. this._positionFunction = posFunction;
  53848. this._vertexFunction = vtxFunction;
  53849. }
  53850. return ModelShape;
  53851. }());
  53852. BABYLON.ModelShape = ModelShape;
  53853. /**
  53854. * Represents a Depth Sorted Particle in the solid particle system.
  53855. * @see SolidParticleSystem
  53856. */
  53857. var DepthSortedParticle = /** @class */ (function () {
  53858. function DepthSortedParticle() {
  53859. /**
  53860. * Index of the particle in the "indices" array
  53861. */
  53862. this.ind = 0;
  53863. /**
  53864. * Length of the particle shape in the "indices" array
  53865. */
  53866. this.indicesLength = 0;
  53867. /**
  53868. * Squared distance from the particle to the camera
  53869. */
  53870. this.sqDistance = 0.0;
  53871. }
  53872. return DepthSortedParticle;
  53873. }());
  53874. BABYLON.DepthSortedParticle = DepthSortedParticle;
  53875. })(BABYLON || (BABYLON = {}));
  53876. //# sourceMappingURL=babylon.solidParticle.js.map
  53877. "use strict";
  53878. var BABYLON;
  53879. (function (BABYLON) {
  53880. /**
  53881. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  53882. *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.
  53883. * The SPS is also a particle system. It provides some methods to manage the particles.
  53884. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  53885. *
  53886. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  53887. */
  53888. var SolidParticleSystem = /** @class */ (function () {
  53889. /**
  53890. * Creates a SPS (Solid Particle System) object.
  53891. * @param name (String) is the SPS name, this will be the underlying mesh name.
  53892. * @param scene (Scene) is the scene in which the SPS is added.
  53893. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  53894. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  53895. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  53896. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  53897. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  53898. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  53899. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  53900. */
  53901. function SolidParticleSystem(name, scene, options) {
  53902. /**
  53903. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  53904. * Example : var p = SPS.particles[i];
  53905. */
  53906. this.particles = new Array();
  53907. /**
  53908. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  53909. */
  53910. this.nbParticles = 0;
  53911. /**
  53912. * If the particles must ever face the camera (default false). Useful for planar particles.
  53913. */
  53914. this.billboard = false;
  53915. /**
  53916. * Recompute normals when adding a shape
  53917. */
  53918. this.recomputeNormals = true;
  53919. /**
  53920. * This a counter ofr your own usage. It's not set by any SPS functions.
  53921. */
  53922. this.counter = 0;
  53923. /**
  53924. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  53925. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  53926. */
  53927. this.vars = {};
  53928. /**
  53929. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  53930. */
  53931. this._bSphereOnly = false;
  53932. /**
  53933. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  53934. */
  53935. this._bSphereRadiusFactor = 1.0;
  53936. this._positions = new Array();
  53937. this._indices = new Array();
  53938. this._normals = new Array();
  53939. this._colors = new Array();
  53940. this._uvs = new Array();
  53941. this._index = 0; // indices index
  53942. this._updatable = true;
  53943. this._pickable = false;
  53944. this._isVisibilityBoxLocked = false;
  53945. this._alwaysVisible = false;
  53946. this._depthSort = false;
  53947. this._shapeCounter = 0;
  53948. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  53949. this._color = new BABYLON.Color4(0, 0, 0, 0);
  53950. this._computeParticleColor = true;
  53951. this._computeParticleTexture = true;
  53952. this._computeParticleRotation = true;
  53953. this._computeParticleVertex = false;
  53954. this._computeBoundingBox = false;
  53955. this._depthSortParticles = true;
  53956. this._cam_axisZ = BABYLON.Vector3.Zero();
  53957. this._cam_axisY = BABYLON.Vector3.Zero();
  53958. this._cam_axisX = BABYLON.Vector3.Zero();
  53959. this._axisZ = BABYLON.Axis.Z;
  53960. this._camDir = BABYLON.Vector3.Zero();
  53961. this._camInvertedPosition = BABYLON.Vector3.Zero();
  53962. this._rotMatrix = new BABYLON.Matrix();
  53963. this._invertMatrix = new BABYLON.Matrix();
  53964. this._rotated = BABYLON.Vector3.Zero();
  53965. this._quaternion = new BABYLON.Quaternion();
  53966. this._vertex = BABYLON.Vector3.Zero();
  53967. this._normal = BABYLON.Vector3.Zero();
  53968. this._yaw = 0.0;
  53969. this._pitch = 0.0;
  53970. this._roll = 0.0;
  53971. this._halfroll = 0.0;
  53972. this._halfpitch = 0.0;
  53973. this._halfyaw = 0.0;
  53974. this._sinRoll = 0.0;
  53975. this._cosRoll = 0.0;
  53976. this._sinPitch = 0.0;
  53977. this._cosPitch = 0.0;
  53978. this._sinYaw = 0.0;
  53979. this._cosYaw = 0.0;
  53980. this._mustUnrotateFixedNormals = false;
  53981. this._minimum = BABYLON.Vector3.Zero();
  53982. this._maximum = BABYLON.Vector3.Zero();
  53983. this._minBbox = BABYLON.Vector3.Zero();
  53984. this._maxBbox = BABYLON.Vector3.Zero();
  53985. this._particlesIntersect = false;
  53986. this._depthSortFunction = function (p1, p2) {
  53987. return (p2.sqDistance - p1.sqDistance);
  53988. };
  53989. this._needs32Bits = false;
  53990. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  53991. this._scaledPivot = BABYLON.Vector3.Zero();
  53992. this._particleHasParent = false;
  53993. this.name = name;
  53994. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53995. this._camera = scene.activeCamera;
  53996. this._pickable = options ? options.isPickable : false;
  53997. this._depthSort = options ? options.enableDepthSort : false;
  53998. this._particlesIntersect = options ? options.particleIntersection : false;
  53999. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  54000. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  54001. if (options && options.updatable) {
  54002. this._updatable = options.updatable;
  54003. }
  54004. else {
  54005. this._updatable = true;
  54006. }
  54007. if (this._pickable) {
  54008. this.pickedParticles = [];
  54009. }
  54010. if (this._depthSort) {
  54011. this.depthSortedParticles = [];
  54012. }
  54013. }
  54014. /**
  54015. * Builds the SPS underlying mesh. Returns a standard Mesh.
  54016. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  54017. * @returns the created mesh
  54018. */
  54019. SolidParticleSystem.prototype.buildMesh = function () {
  54020. if (this.nbParticles === 0) {
  54021. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  54022. this.addShape(triangle, 1);
  54023. triangle.dispose();
  54024. }
  54025. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  54026. this._positions32 = new Float32Array(this._positions);
  54027. this._uvs32 = new Float32Array(this._uvs);
  54028. this._colors32 = new Float32Array(this._colors);
  54029. if (this.recomputeNormals) {
  54030. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  54031. }
  54032. this._normals32 = new Float32Array(this._normals);
  54033. this._fixedNormal32 = new Float32Array(this._normals);
  54034. if (this._mustUnrotateFixedNormals) {
  54035. this._unrotateFixedNormals();
  54036. }
  54037. var vertexData = new BABYLON.VertexData();
  54038. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  54039. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  54040. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  54041. if (this._uvs32) {
  54042. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  54043. ;
  54044. }
  54045. if (this._colors32) {
  54046. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  54047. }
  54048. var mesh = new BABYLON.Mesh(this.name, this._scene);
  54049. vertexData.applyToMesh(mesh, this._updatable);
  54050. this.mesh = mesh;
  54051. this.mesh.isPickable = this._pickable;
  54052. // free memory
  54053. if (!this._depthSort) {
  54054. this._indices = null;
  54055. }
  54056. this._positions = null;
  54057. this._normals = null;
  54058. this._uvs = null;
  54059. this._colors = null;
  54060. if (!this._updatable) {
  54061. this.particles.length = 0;
  54062. }
  54063. return mesh;
  54064. };
  54065. /**
  54066. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  54067. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  54068. * Thus the particles generated from `digest()` have their property `position` set yet.
  54069. * @param mesh ( Mesh ) is the mesh to be digested
  54070. * @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
  54071. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  54072. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  54073. * @returns the current SPS
  54074. */
  54075. SolidParticleSystem.prototype.digest = function (mesh, options) {
  54076. var size = (options && options.facetNb) || 1;
  54077. var number = (options && options.number) || 0;
  54078. var delta = (options && options.delta) || 0;
  54079. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54080. var meshInd = mesh.getIndices();
  54081. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54082. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54083. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54084. var f = 0; // facet counter
  54085. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  54086. // compute size from number
  54087. if (number) {
  54088. number = (number > totalFacets) ? totalFacets : number;
  54089. size = Math.round(totalFacets / number);
  54090. delta = 0;
  54091. }
  54092. else {
  54093. size = (size > totalFacets) ? totalFacets : size;
  54094. }
  54095. var facetPos = []; // submesh positions
  54096. var facetInd = []; // submesh indices
  54097. var facetUV = []; // submesh UV
  54098. var facetCol = []; // submesh colors
  54099. var barycenter = BABYLON.Vector3.Zero();
  54100. var sizeO = size;
  54101. while (f < totalFacets) {
  54102. size = sizeO + Math.floor((1 + delta) * Math.random());
  54103. if (f > totalFacets - size) {
  54104. size = totalFacets - f;
  54105. }
  54106. // reset temp arrays
  54107. facetPos.length = 0;
  54108. facetInd.length = 0;
  54109. facetUV.length = 0;
  54110. facetCol.length = 0;
  54111. // iterate over "size" facets
  54112. var fi = 0;
  54113. for (var j = f * 3; j < (f + size) * 3; j++) {
  54114. facetInd.push(fi);
  54115. var i = meshInd[j];
  54116. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  54117. if (meshUV) {
  54118. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  54119. }
  54120. if (meshCol) {
  54121. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  54122. }
  54123. fi++;
  54124. }
  54125. // create a model shape for each single particle
  54126. var idx = this.nbParticles;
  54127. var shape = this._posToShape(facetPos);
  54128. var shapeUV = this._uvsToShapeUV(facetUV);
  54129. // compute the barycenter of the shape
  54130. var v;
  54131. for (v = 0; v < shape.length; v++) {
  54132. barycenter.addInPlace(shape[v]);
  54133. }
  54134. barycenter.scaleInPlace(1 / shape.length);
  54135. // shift the shape from its barycenter to the origin
  54136. for (v = 0; v < shape.length; v++) {
  54137. shape[v].subtractInPlace(barycenter);
  54138. }
  54139. var bInfo;
  54140. if (this._particlesIntersect) {
  54141. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  54142. }
  54143. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  54144. // add the particle in the SPS
  54145. var currentPos = this._positions.length;
  54146. var currentInd = this._indices.length;
  54147. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  54148. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  54149. // initialize the particle position
  54150. this.particles[this.nbParticles].position.addInPlace(barycenter);
  54151. this._index += shape.length;
  54152. idx++;
  54153. this.nbParticles++;
  54154. this._shapeCounter++;
  54155. f += size;
  54156. }
  54157. return this;
  54158. };
  54159. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  54160. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  54161. var index = 0;
  54162. var idx = 0;
  54163. for (var p = 0; p < this.particles.length; p++) {
  54164. this._particle = this.particles[p];
  54165. this._shape = this._particle._model._shape;
  54166. if (this._particle.rotationQuaternion) {
  54167. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54168. }
  54169. else {
  54170. this._yaw = this._particle.rotation.y;
  54171. this._pitch = this._particle.rotation.x;
  54172. this._roll = this._particle.rotation.z;
  54173. this._quaternionRotationYPR();
  54174. }
  54175. this._quaternionToRotationMatrix();
  54176. this._rotMatrix.invertToRef(this._invertMatrix);
  54177. for (var pt = 0; pt < this._shape.length; pt++) {
  54178. idx = index + pt * 3;
  54179. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  54180. this._fixedNormal32[idx] = this._normal.x;
  54181. this._fixedNormal32[idx + 1] = this._normal.y;
  54182. this._fixedNormal32[idx + 2] = this._normal.z;
  54183. }
  54184. index = idx + 3;
  54185. }
  54186. };
  54187. //reset copy
  54188. SolidParticleSystem.prototype._resetCopy = function () {
  54189. this._copy.position.x = 0;
  54190. this._copy.position.y = 0;
  54191. this._copy.position.z = 0;
  54192. this._copy.rotation.x = 0;
  54193. this._copy.rotation.y = 0;
  54194. this._copy.rotation.z = 0;
  54195. this._copy.rotationQuaternion = null;
  54196. this._copy.scaling.x = 1.0;
  54197. this._copy.scaling.y = 1.0;
  54198. this._copy.scaling.z = 1.0;
  54199. this._copy.uvs.x = 0;
  54200. this._copy.uvs.y = 0;
  54201. this._copy.uvs.z = 1.0;
  54202. this._copy.uvs.w = 1.0;
  54203. this._copy.color = null;
  54204. this._copy.translateFromPivot = false;
  54205. };
  54206. // _meshBuilder : inserts the shape model in the global SPS mesh
  54207. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  54208. var i;
  54209. var u = 0;
  54210. var c = 0;
  54211. var n = 0;
  54212. this._resetCopy();
  54213. if (options && options.positionFunction) {
  54214. options.positionFunction(this._copy, idx, idxInShape);
  54215. this._mustUnrotateFixedNormals = true;
  54216. }
  54217. if (this._copy.rotationQuaternion) {
  54218. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54219. }
  54220. else {
  54221. this._yaw = this._copy.rotation.y;
  54222. this._pitch = this._copy.rotation.x;
  54223. this._roll = this._copy.rotation.z;
  54224. this._quaternionRotationYPR();
  54225. }
  54226. this._quaternionToRotationMatrix();
  54227. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  54228. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  54229. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  54230. if (this._copy.translateFromPivot) {
  54231. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  54232. }
  54233. else {
  54234. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  54235. }
  54236. for (i = 0; i < shape.length; i++) {
  54237. this._vertex.x = shape[i].x;
  54238. this._vertex.y = shape[i].y;
  54239. this._vertex.z = shape[i].z;
  54240. if (options && options.vertexFunction) {
  54241. options.vertexFunction(this._copy, this._vertex, i);
  54242. }
  54243. this._vertex.x *= this._copy.scaling.x;
  54244. this._vertex.y *= this._copy.scaling.y;
  54245. this._vertex.z *= this._copy.scaling.z;
  54246. this._vertex.x -= this._scaledPivot.x;
  54247. this._vertex.y -= this._scaledPivot.y;
  54248. this._vertex.z -= this._scaledPivot.z;
  54249. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54250. this._rotated.addInPlace(this._pivotBackTranslation);
  54251. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  54252. if (meshUV) {
  54253. 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);
  54254. u += 2;
  54255. }
  54256. if (this._copy.color) {
  54257. this._color = this._copy.color;
  54258. }
  54259. else if (meshCol && meshCol[c] !== undefined) {
  54260. this._color.r = meshCol[c];
  54261. this._color.g = meshCol[c + 1];
  54262. this._color.b = meshCol[c + 2];
  54263. this._color.a = meshCol[c + 3];
  54264. }
  54265. else {
  54266. this._color.r = 1.0;
  54267. this._color.g = 1.0;
  54268. this._color.b = 1.0;
  54269. this._color.a = 1.0;
  54270. }
  54271. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  54272. c += 4;
  54273. if (!this.recomputeNormals && meshNor) {
  54274. this._normal.x = meshNor[n];
  54275. this._normal.y = meshNor[n + 1];
  54276. this._normal.z = meshNor[n + 2];
  54277. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  54278. normals.push(this._normal.x, this._normal.y, this._normal.z);
  54279. n += 3;
  54280. }
  54281. }
  54282. for (i = 0; i < meshInd.length; i++) {
  54283. var current_ind = p + meshInd[i];
  54284. indices.push(current_ind);
  54285. if (current_ind > 65535) {
  54286. this._needs32Bits = true;
  54287. }
  54288. }
  54289. if (this._pickable) {
  54290. var nbfaces = meshInd.length / 3;
  54291. for (i = 0; i < nbfaces; i++) {
  54292. this.pickedParticles.push({ idx: idx, faceId: i });
  54293. }
  54294. }
  54295. if (this._depthSort) {
  54296. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  54297. }
  54298. return this._copy;
  54299. };
  54300. // returns a shape array from positions array
  54301. SolidParticleSystem.prototype._posToShape = function (positions) {
  54302. var shape = [];
  54303. for (var i = 0; i < positions.length; i += 3) {
  54304. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  54305. }
  54306. return shape;
  54307. };
  54308. // returns a shapeUV array from a Vector4 uvs
  54309. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  54310. var shapeUV = [];
  54311. if (uvs) {
  54312. for (var i = 0; i < uvs.length; i++)
  54313. shapeUV.push(uvs[i]);
  54314. }
  54315. return shapeUV;
  54316. };
  54317. // adds a new particle object in the particles array
  54318. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  54319. if (bInfo === void 0) { bInfo = null; }
  54320. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  54321. this.particles.push(sp);
  54322. return sp;
  54323. };
  54324. /**
  54325. * Adds some particles to the SPS from the model shape. Returns the shape id.
  54326. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  54327. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  54328. * @param nb (positive integer) the number of particles to be created from this model
  54329. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  54330. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  54331. * @returns the number of shapes in the system
  54332. */
  54333. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  54334. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54335. var meshInd = mesh.getIndices();
  54336. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54337. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54338. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54339. var bbInfo;
  54340. if (this._particlesIntersect) {
  54341. bbInfo = mesh.getBoundingInfo();
  54342. }
  54343. var shape = this._posToShape(meshPos);
  54344. var shapeUV = this._uvsToShapeUV(meshUV);
  54345. var posfunc = options ? options.positionFunction : null;
  54346. var vtxfunc = options ? options.vertexFunction : null;
  54347. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  54348. // particles
  54349. var sp;
  54350. var currentCopy;
  54351. var idx = this.nbParticles;
  54352. for (var i = 0; i < nb; i++) {
  54353. var currentPos = this._positions.length;
  54354. var currentInd = this._indices.length;
  54355. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  54356. if (this._updatable) {
  54357. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  54358. sp.position.copyFrom(currentCopy.position);
  54359. sp.rotation.copyFrom(currentCopy.rotation);
  54360. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  54361. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  54362. }
  54363. if (currentCopy.color && sp.color) {
  54364. sp.color.copyFrom(currentCopy.color);
  54365. }
  54366. sp.scaling.copyFrom(currentCopy.scaling);
  54367. sp.uvs.copyFrom(currentCopy.uvs);
  54368. }
  54369. this._index += shape.length;
  54370. idx++;
  54371. }
  54372. this.nbParticles += nb;
  54373. this._shapeCounter++;
  54374. return this._shapeCounter - 1;
  54375. };
  54376. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  54377. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  54378. this._resetCopy();
  54379. if (particle._model._positionFunction) {
  54380. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  54381. }
  54382. if (this._copy.rotationQuaternion) {
  54383. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54384. }
  54385. else {
  54386. this._yaw = this._copy.rotation.y;
  54387. this._pitch = this._copy.rotation.x;
  54388. this._roll = this._copy.rotation.z;
  54389. this._quaternionRotationYPR();
  54390. }
  54391. this._quaternionToRotationMatrix();
  54392. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  54393. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  54394. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  54395. if (this._copy.translateFromPivot) {
  54396. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  54397. }
  54398. else {
  54399. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  54400. }
  54401. this._shape = particle._model._shape;
  54402. for (var pt = 0; pt < this._shape.length; pt++) {
  54403. this._vertex.x = this._shape[pt].x;
  54404. this._vertex.y = this._shape[pt].y;
  54405. this._vertex.z = this._shape[pt].z;
  54406. if (particle._model._vertexFunction) {
  54407. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  54408. }
  54409. this._vertex.x *= this._copy.scaling.x;
  54410. this._vertex.y *= this._copy.scaling.y;
  54411. this._vertex.z *= this._copy.scaling.z;
  54412. this._vertex.x -= this._scaledPivot.x;
  54413. this._vertex.y -= this._scaledPivot.y;
  54414. this._vertex.z -= this._scaledPivot.z;
  54415. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54416. this._rotated.addInPlace(this._pivotBackTranslation);
  54417. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  54418. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  54419. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  54420. }
  54421. particle.position.x = 0.0;
  54422. particle.position.y = 0.0;
  54423. particle.position.z = 0.0;
  54424. particle.rotation.x = 0.0;
  54425. particle.rotation.y = 0.0;
  54426. particle.rotation.z = 0.0;
  54427. particle.rotationQuaternion = null;
  54428. particle.scaling.x = 1.0;
  54429. particle.scaling.y = 1.0;
  54430. particle.scaling.z = 1.0;
  54431. particle.uvs.x = 0.0;
  54432. particle.uvs.y = 0.0;
  54433. particle.uvs.z = 1.0;
  54434. particle.uvs.w = 1.0;
  54435. particle.pivot.x = 0.0;
  54436. particle.pivot.y = 0.0;
  54437. particle.pivot.z = 0.0;
  54438. particle.translateFromPivot = false;
  54439. particle.parentId = null;
  54440. };
  54441. /**
  54442. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  54443. * @returns the SPS.
  54444. */
  54445. SolidParticleSystem.prototype.rebuildMesh = function () {
  54446. for (var p = 0; p < this.particles.length; p++) {
  54447. this._rebuildParticle(this.particles[p]);
  54448. }
  54449. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54450. return this;
  54451. };
  54452. /**
  54453. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  54454. * This method calls `updateParticle()` for each particle of the SPS.
  54455. * For an animated SPS, it is usually called within the render loop.
  54456. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  54457. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  54458. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  54459. * @returns the SPS.
  54460. */
  54461. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  54462. if (start === void 0) { start = 0; }
  54463. if (end === void 0) { end = this.nbParticles - 1; }
  54464. if (update === void 0) { update = true; }
  54465. if (!this._updatable) {
  54466. return this;
  54467. }
  54468. // custom beforeUpdate
  54469. this.beforeUpdateParticles(start, end, update);
  54470. this._cam_axisX.x = 1.0;
  54471. this._cam_axisX.y = 0.0;
  54472. this._cam_axisX.z = 0.0;
  54473. this._cam_axisY.x = 0.0;
  54474. this._cam_axisY.y = 1.0;
  54475. this._cam_axisY.z = 0.0;
  54476. this._cam_axisZ.x = 0.0;
  54477. this._cam_axisZ.y = 0.0;
  54478. this._cam_axisZ.z = 1.0;
  54479. // cases when the World Matrix is to be computed first
  54480. if (this.billboard || this._depthSort) {
  54481. this.mesh.computeWorldMatrix(true);
  54482. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  54483. }
  54484. // if the particles will always face the camera
  54485. if (this.billboard) {
  54486. // compute the camera position and un-rotate it by the current mesh rotation
  54487. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  54488. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  54489. this._cam_axisZ.normalize();
  54490. // same for camera up vector extracted from the cam view matrix
  54491. var view = this._camera.getViewMatrix(true);
  54492. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  54493. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  54494. this._cam_axisY.normalize();
  54495. this._cam_axisX.normalize();
  54496. }
  54497. // if depthSort, compute the camera global position in the mesh local system
  54498. if (this._depthSort) {
  54499. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  54500. }
  54501. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  54502. var idx = 0; // current position index in the global array positions32
  54503. var index = 0; // position start index in the global array positions32 of the current particle
  54504. var colidx = 0; // current color index in the global array colors32
  54505. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  54506. var uvidx = 0; // current uv index in the global array uvs32
  54507. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  54508. var pt = 0; // current index in the particle model shape
  54509. if (this.mesh.isFacetDataEnabled) {
  54510. this._computeBoundingBox = true;
  54511. }
  54512. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  54513. if (this._computeBoundingBox) {
  54514. if (start == 0 && end == this.nbParticles - 1) {
  54515. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  54516. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  54517. }
  54518. else {
  54519. if (this.mesh._boundingInfo) {
  54520. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  54521. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  54522. }
  54523. }
  54524. }
  54525. // particle loop
  54526. index = this.particles[start]._pos;
  54527. var vpos = (index / 3) | 0;
  54528. colorIndex = vpos * 4;
  54529. uvIndex = vpos * 2;
  54530. for (var p = start; p <= end; p++) {
  54531. this._particle = this.particles[p];
  54532. this._shape = this._particle._model._shape;
  54533. this._shapeUV = this._particle._model._shapeUV;
  54534. // call to custom user function to update the particle properties
  54535. this.updateParticle(this._particle);
  54536. // camera-particle distance for depth sorting
  54537. if (this._depthSort && this._depthSortParticles) {
  54538. var dsp = this.depthSortedParticles[p];
  54539. dsp.ind = this._particle._ind;
  54540. dsp.indicesLength = this._particle._model._indicesLength;
  54541. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  54542. }
  54543. // skip the computations for inactive or already invisible particles
  54544. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  54545. // increment indexes for the next particle
  54546. pt = this._shape.length;
  54547. index += pt * 3;
  54548. colorIndex += pt * 4;
  54549. uvIndex += pt * 2;
  54550. continue;
  54551. }
  54552. if (this._particle.isVisible) {
  54553. this._particle._stillInvisible = false; // un-mark permanent invisibility
  54554. this._particleHasParent = (this._particle.parentId !== null);
  54555. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  54556. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  54557. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  54558. // particle rotation matrix
  54559. if (this.billboard) {
  54560. this._particle.rotation.x = 0.0;
  54561. this._particle.rotation.y = 0.0;
  54562. }
  54563. if (this._computeParticleRotation || this.billboard) {
  54564. if (this._particle.rotationQuaternion) {
  54565. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54566. }
  54567. else {
  54568. this._yaw = this._particle.rotation.y;
  54569. this._pitch = this._particle.rotation.x;
  54570. this._roll = this._particle.rotation.z;
  54571. this._quaternionRotationYPR();
  54572. }
  54573. this._quaternionToRotationMatrix();
  54574. }
  54575. if (this._particleHasParent) {
  54576. this._parent = this.particles[this._particle.parentId];
  54577. 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];
  54578. 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];
  54579. 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];
  54580. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  54581. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  54582. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  54583. if (this._computeParticleRotation || this.billboard) {
  54584. 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];
  54585. 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];
  54586. 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];
  54587. 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];
  54588. 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];
  54589. 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];
  54590. 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];
  54591. 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];
  54592. 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];
  54593. }
  54594. }
  54595. else {
  54596. this._particle._globalPosition.x = this._particle.position.x;
  54597. this._particle._globalPosition.y = this._particle.position.y;
  54598. this._particle._globalPosition.z = this._particle.position.z;
  54599. if (this._computeParticleRotation || this.billboard) {
  54600. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  54601. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  54602. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  54603. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  54604. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  54605. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  54606. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  54607. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  54608. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  54609. }
  54610. }
  54611. if (this._particle.translateFromPivot) {
  54612. this._pivotBackTranslation.x = 0.0;
  54613. this._pivotBackTranslation.y = 0.0;
  54614. this._pivotBackTranslation.z = 0.0;
  54615. }
  54616. else {
  54617. this._pivotBackTranslation.x = this._scaledPivot.x;
  54618. this._pivotBackTranslation.y = this._scaledPivot.y;
  54619. this._pivotBackTranslation.z = this._scaledPivot.z;
  54620. }
  54621. // particle vertex loop
  54622. for (pt = 0; pt < this._shape.length; pt++) {
  54623. idx = index + pt * 3;
  54624. colidx = colorIndex + pt * 4;
  54625. uvidx = uvIndex + pt * 2;
  54626. this._vertex.x = this._shape[pt].x;
  54627. this._vertex.y = this._shape[pt].y;
  54628. this._vertex.z = this._shape[pt].z;
  54629. if (this._computeParticleVertex) {
  54630. this.updateParticleVertex(this._particle, this._vertex, pt);
  54631. }
  54632. // positions
  54633. this._vertex.x *= this._particle.scaling.x;
  54634. this._vertex.y *= this._particle.scaling.y;
  54635. this._vertex.z *= this._particle.scaling.z;
  54636. this._vertex.x -= this._scaledPivot.x;
  54637. this._vertex.y -= this._scaledPivot.y;
  54638. this._vertex.z -= this._scaledPivot.z;
  54639. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54640. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54641. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54642. this._rotated.x += this._pivotBackTranslation.x;
  54643. this._rotated.y += this._pivotBackTranslation.y;
  54644. this._rotated.z += this._pivotBackTranslation.z;
  54645. 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;
  54646. 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;
  54647. 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;
  54648. if (this._computeBoundingBox) {
  54649. if (this._positions32[idx] < this._minimum.x) {
  54650. this._minimum.x = this._positions32[idx];
  54651. }
  54652. if (this._positions32[idx] > this._maximum.x) {
  54653. this._maximum.x = this._positions32[idx];
  54654. }
  54655. if (this._positions32[idx + 1] < this._minimum.y) {
  54656. this._minimum.y = this._positions32[idx + 1];
  54657. }
  54658. if (this._positions32[idx + 1] > this._maximum.y) {
  54659. this._maximum.y = this._positions32[idx + 1];
  54660. }
  54661. if (this._positions32[idx + 2] < this._minimum.z) {
  54662. this._minimum.z = this._positions32[idx + 2];
  54663. }
  54664. if (this._positions32[idx + 2] > this._maximum.z) {
  54665. this._maximum.z = this._positions32[idx + 2];
  54666. }
  54667. }
  54668. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  54669. if (!this._computeParticleVertex) {
  54670. this._normal.x = this._fixedNormal32[idx];
  54671. this._normal.y = this._fixedNormal32[idx + 1];
  54672. this._normal.z = this._fixedNormal32[idx + 2];
  54673. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  54674. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  54675. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  54676. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  54677. 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;
  54678. 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;
  54679. }
  54680. if (this._computeParticleColor && this._particle.color) {
  54681. this._colors32[colidx] = this._particle.color.r;
  54682. this._colors32[colidx + 1] = this._particle.color.g;
  54683. this._colors32[colidx + 2] = this._particle.color.b;
  54684. this._colors32[colidx + 3] = this._particle.color.a;
  54685. }
  54686. if (this._computeParticleTexture) {
  54687. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54688. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54689. }
  54690. }
  54691. }
  54692. else {
  54693. this._particle._stillInvisible = true; // mark the particle as invisible
  54694. for (pt = 0; pt < this._shape.length; pt++) {
  54695. idx = index + pt * 3;
  54696. colidx = colorIndex + pt * 4;
  54697. uvidx = uvIndex + pt * 2;
  54698. this._positions32[idx] = 0.0;
  54699. this._positions32[idx + 1] = 0.0;
  54700. this._positions32[idx + 2] = 0.0;
  54701. this._normals32[idx] = 0.0;
  54702. this._normals32[idx + 1] = 0.0;
  54703. this._normals32[idx + 2] = 0.0;
  54704. if (this._computeParticleColor && this._particle.color) {
  54705. this._colors32[colidx] = this._particle.color.r;
  54706. this._colors32[colidx + 1] = this._particle.color.g;
  54707. this._colors32[colidx + 2] = this._particle.color.b;
  54708. this._colors32[colidx + 3] = this._particle.color.a;
  54709. }
  54710. if (this._computeParticleTexture) {
  54711. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54712. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54713. }
  54714. }
  54715. }
  54716. // if the particle intersections must be computed : update the bbInfo
  54717. if (this._particlesIntersect) {
  54718. var bInfo = this._particle._boundingInfo;
  54719. var bBox = bInfo.boundingBox;
  54720. var bSphere = bInfo.boundingSphere;
  54721. if (!this._bSphereOnly) {
  54722. // place, scale and rotate the particle bbox within the SPS local system, then update it
  54723. for (var b = 0; b < bBox.vectors.length; b++) {
  54724. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  54725. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  54726. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  54727. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54728. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54729. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54730. 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;
  54731. 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;
  54732. 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;
  54733. }
  54734. bBox._update(this.mesh._worldMatrix);
  54735. }
  54736. // place and scale the particle bouding sphere in the SPS local system, then update it
  54737. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  54738. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  54739. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  54740. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  54741. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  54742. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  54743. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  54744. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  54745. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  54746. 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));
  54747. bSphere._update(this.mesh._worldMatrix);
  54748. }
  54749. // increment indexes for the next particle
  54750. index = idx + 3;
  54751. colorIndex = colidx + 4;
  54752. uvIndex = uvidx + 2;
  54753. }
  54754. // if the VBO must be updated
  54755. if (update) {
  54756. if (this._computeParticleColor) {
  54757. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  54758. }
  54759. if (this._computeParticleTexture) {
  54760. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  54761. }
  54762. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54763. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  54764. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  54765. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  54766. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  54767. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  54768. for (var i = 0; i < this._normals32.length; i++) {
  54769. this._fixedNormal32[i] = this._normals32[i];
  54770. }
  54771. }
  54772. if (!this.mesh.areNormalsFrozen) {
  54773. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  54774. }
  54775. }
  54776. if (this._depthSort && this._depthSortParticles) {
  54777. this.depthSortedParticles.sort(this._depthSortFunction);
  54778. var dspl = this.depthSortedParticles.length;
  54779. var sorted = 0;
  54780. var lind = 0;
  54781. var sind = 0;
  54782. var sid = 0;
  54783. for (sorted = 0; sorted < dspl; sorted++) {
  54784. lind = this.depthSortedParticles[sorted].indicesLength;
  54785. sind = this.depthSortedParticles[sorted].ind;
  54786. for (var i = 0; i < lind; i++) {
  54787. this._indices32[sid] = this._indices[sind + i];
  54788. sid++;
  54789. }
  54790. }
  54791. this.mesh.updateIndices(this._indices32);
  54792. }
  54793. }
  54794. if (this._computeBoundingBox) {
  54795. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  54796. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  54797. }
  54798. this.afterUpdateParticles(start, end, update);
  54799. return this;
  54800. };
  54801. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  54802. this._halfroll = this._roll * 0.5;
  54803. this._halfpitch = this._pitch * 0.5;
  54804. this._halfyaw = this._yaw * 0.5;
  54805. this._sinRoll = Math.sin(this._halfroll);
  54806. this._cosRoll = Math.cos(this._halfroll);
  54807. this._sinPitch = Math.sin(this._halfpitch);
  54808. this._cosPitch = Math.cos(this._halfpitch);
  54809. this._sinYaw = Math.sin(this._halfyaw);
  54810. this._cosYaw = Math.cos(this._halfyaw);
  54811. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  54812. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  54813. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  54814. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  54815. };
  54816. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  54817. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  54818. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  54819. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  54820. this._rotMatrix.m[3] = 0;
  54821. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  54822. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  54823. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  54824. this._rotMatrix.m[7] = 0;
  54825. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  54826. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  54827. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  54828. this._rotMatrix.m[11] = 0;
  54829. this._rotMatrix.m[12] = 0;
  54830. this._rotMatrix.m[13] = 0;
  54831. this._rotMatrix.m[14] = 0;
  54832. this._rotMatrix.m[15] = 1.0;
  54833. };
  54834. /**
  54835. * Disposes the SPS.
  54836. */
  54837. SolidParticleSystem.prototype.dispose = function () {
  54838. this.mesh.dispose();
  54839. this.vars = null;
  54840. // drop references to internal big arrays for the GC
  54841. this._positions = null;
  54842. this._indices = null;
  54843. this._normals = null;
  54844. this._uvs = null;
  54845. this._colors = null;
  54846. this._indices32 = null;
  54847. this._positions32 = null;
  54848. this._normals32 = null;
  54849. this._fixedNormal32 = null;
  54850. this._uvs32 = null;
  54851. this._colors32 = null;
  54852. this.pickedParticles = null;
  54853. };
  54854. /**
  54855. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  54856. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54857. * @returns the SPS.
  54858. */
  54859. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  54860. if (!this._isVisibilityBoxLocked) {
  54861. this.mesh.refreshBoundingInfo();
  54862. }
  54863. return this;
  54864. };
  54865. /**
  54866. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  54867. * @param size the size (float) of the visibility box
  54868. * note : this doesn't lock the SPS mesh bounding box.
  54869. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54870. */
  54871. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  54872. var vis = size / 2;
  54873. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  54874. };
  54875. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  54876. /**
  54877. * Gets whether the SPS as always visible or not
  54878. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54879. */
  54880. get: function () {
  54881. return this._alwaysVisible;
  54882. },
  54883. /**
  54884. * Sets the SPS as always visible or not
  54885. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54886. */
  54887. set: function (val) {
  54888. this._alwaysVisible = val;
  54889. this.mesh.alwaysSelectAsActiveMesh = val;
  54890. },
  54891. enumerable: true,
  54892. configurable: true
  54893. });
  54894. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  54895. /**
  54896. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54897. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54898. */
  54899. get: function () {
  54900. return this._isVisibilityBoxLocked;
  54901. },
  54902. /**
  54903. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54904. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54905. */
  54906. set: function (val) {
  54907. this._isVisibilityBoxLocked = val;
  54908. var boundingInfo = this.mesh.getBoundingInfo();
  54909. boundingInfo.isLocked = val;
  54910. },
  54911. enumerable: true,
  54912. configurable: true
  54913. });
  54914. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  54915. /**
  54916. * Gets if `setParticles()` computes the particle rotations or not.
  54917. * Default value : true. The SPS is faster when it's set to false.
  54918. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54919. */
  54920. get: function () {
  54921. return this._computeParticleRotation;
  54922. },
  54923. /**
  54924. * Tells to `setParticles()` to compute the particle rotations or not.
  54925. * Default value : true. The SPS is faster when it's set to false.
  54926. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54927. */
  54928. set: function (val) {
  54929. this._computeParticleRotation = val;
  54930. },
  54931. enumerable: true,
  54932. configurable: true
  54933. });
  54934. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  54935. /**
  54936. * Gets if `setParticles()` computes the particle colors or not.
  54937. * Default value : true. The SPS is faster when it's set to false.
  54938. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54939. */
  54940. get: function () {
  54941. return this._computeParticleColor;
  54942. },
  54943. /**
  54944. * Tells to `setParticles()` to compute the particle colors or not.
  54945. * Default value : true. The SPS is faster when it's set to false.
  54946. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54947. */
  54948. set: function (val) {
  54949. this._computeParticleColor = val;
  54950. },
  54951. enumerable: true,
  54952. configurable: true
  54953. });
  54954. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  54955. /**
  54956. * Gets if `setParticles()` computes the particle textures or not.
  54957. * Default value : true. The SPS is faster when it's set to false.
  54958. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  54959. */
  54960. get: function () {
  54961. return this._computeParticleTexture;
  54962. },
  54963. set: function (val) {
  54964. this._computeParticleTexture = val;
  54965. },
  54966. enumerable: true,
  54967. configurable: true
  54968. });
  54969. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  54970. /**
  54971. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  54972. * Default value : false. The SPS is faster when it's set to false.
  54973. * Note : the particle custom vertex positions aren't stored values.
  54974. */
  54975. get: function () {
  54976. return this._computeParticleVertex;
  54977. },
  54978. /**
  54979. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  54980. * Default value : false. The SPS is faster when it's set to false.
  54981. * Note : the particle custom vertex positions aren't stored values.
  54982. */
  54983. set: function (val) {
  54984. this._computeParticleVertex = val;
  54985. },
  54986. enumerable: true,
  54987. configurable: true
  54988. });
  54989. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  54990. /**
  54991. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  54992. */
  54993. get: function () {
  54994. return this._computeBoundingBox;
  54995. },
  54996. /**
  54997. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  54998. */
  54999. set: function (val) {
  55000. this._computeBoundingBox = val;
  55001. },
  55002. enumerable: true,
  55003. configurable: true
  55004. });
  55005. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  55006. /**
  55007. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  55008. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  55009. * Default : `true`
  55010. */
  55011. get: function () {
  55012. return this._depthSortParticles;
  55013. },
  55014. /**
  55015. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  55016. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  55017. * Default : `true`
  55018. */
  55019. set: function (val) {
  55020. this._depthSortParticles = val;
  55021. },
  55022. enumerable: true,
  55023. configurable: true
  55024. });
  55025. // =======================================================================
  55026. // Particle behavior logic
  55027. // these following methods may be overwritten by the user to fit his needs
  55028. /**
  55029. * This function does nothing. It may be overwritten to set all the particle first values.
  55030. * The SPS doesn't call this function, you may have to call it by your own.
  55031. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55032. */
  55033. SolidParticleSystem.prototype.initParticles = function () {
  55034. };
  55035. /**
  55036. * This function does nothing. It may be overwritten to recycle a particle.
  55037. * The SPS doesn't call this function, you may have to call it by your own.
  55038. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55039. * @param particle The particle to recycle
  55040. * @returns the recycled particle
  55041. */
  55042. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  55043. return particle;
  55044. };
  55045. /**
  55046. * Updates a particle : this function should be overwritten by the user.
  55047. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  55048. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55049. * @example : just set a particle position or velocity and recycle conditions
  55050. * @param particle The particle to update
  55051. * @returns the updated particle
  55052. */
  55053. SolidParticleSystem.prototype.updateParticle = function (particle) {
  55054. return particle;
  55055. };
  55056. /**
  55057. * Updates a vertex of a particle : it can be overwritten by the user.
  55058. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  55059. * @param particle the current particle
  55060. * @param vertex the current index of the current particle
  55061. * @param pt the index of the current vertex in the particle shape
  55062. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  55063. * @example : just set a vertex particle position
  55064. * @returns the updated vertex
  55065. */
  55066. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  55067. return vertex;
  55068. };
  55069. /**
  55070. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  55071. * This does nothing and may be overwritten by the user.
  55072. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55073. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55074. * @param update the boolean update value actually passed to setParticles()
  55075. */
  55076. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  55077. };
  55078. /**
  55079. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  55080. * This will be passed three parameters.
  55081. * This does nothing and may be overwritten by the user.
  55082. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55083. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55084. * @param update the boolean update value actually passed to setParticles()
  55085. */
  55086. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  55087. };
  55088. return SolidParticleSystem;
  55089. }());
  55090. BABYLON.SolidParticleSystem = SolidParticleSystem;
  55091. })(BABYLON || (BABYLON = {}));
  55092. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  55093. "use strict";
  55094. var BABYLON;
  55095. (function (BABYLON) {
  55096. var ShaderMaterial = /** @class */ (function (_super) {
  55097. __extends(ShaderMaterial, _super);
  55098. function ShaderMaterial(name, scene, shaderPath, options) {
  55099. var _this = _super.call(this, name, scene) || this;
  55100. _this._textures = {};
  55101. _this._textureArrays = {};
  55102. _this._floats = {};
  55103. _this._ints = {};
  55104. _this._floatsArrays = {};
  55105. _this._colors3 = {};
  55106. _this._colors3Arrays = {};
  55107. _this._colors4 = {};
  55108. _this._vectors2 = {};
  55109. _this._vectors3 = {};
  55110. _this._vectors4 = {};
  55111. _this._matrices = {};
  55112. _this._matrices3x3 = {};
  55113. _this._matrices2x2 = {};
  55114. _this._vectors2Arrays = {};
  55115. _this._vectors3Arrays = {};
  55116. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  55117. _this._shaderPath = shaderPath;
  55118. options.needAlphaBlending = options.needAlphaBlending || false;
  55119. options.needAlphaTesting = options.needAlphaTesting || false;
  55120. options.attributes = options.attributes || ["position", "normal", "uv"];
  55121. options.uniforms = options.uniforms || ["worldViewProjection"];
  55122. options.uniformBuffers = options.uniformBuffers || [];
  55123. options.samplers = options.samplers || [];
  55124. options.defines = options.defines || [];
  55125. _this._options = options;
  55126. return _this;
  55127. }
  55128. ShaderMaterial.prototype.getClassName = function () {
  55129. return "ShaderMaterial";
  55130. };
  55131. ShaderMaterial.prototype.needAlphaBlending = function () {
  55132. return this._options.needAlphaBlending;
  55133. };
  55134. ShaderMaterial.prototype.needAlphaTesting = function () {
  55135. return this._options.needAlphaTesting;
  55136. };
  55137. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  55138. if (this._options.uniforms.indexOf(uniformName) === -1) {
  55139. this._options.uniforms.push(uniformName);
  55140. }
  55141. };
  55142. ShaderMaterial.prototype.setTexture = function (name, texture) {
  55143. if (this._options.samplers.indexOf(name) === -1) {
  55144. this._options.samplers.push(name);
  55145. }
  55146. this._textures[name] = texture;
  55147. return this;
  55148. };
  55149. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  55150. if (this._options.samplers.indexOf(name) === -1) {
  55151. this._options.samplers.push(name);
  55152. }
  55153. this._checkUniform(name);
  55154. this._textureArrays[name] = textures;
  55155. return this;
  55156. };
  55157. ShaderMaterial.prototype.setFloat = function (name, value) {
  55158. this._checkUniform(name);
  55159. this._floats[name] = value;
  55160. return this;
  55161. };
  55162. ShaderMaterial.prototype.setInt = function (name, value) {
  55163. this._checkUniform(name);
  55164. this._ints[name] = value;
  55165. return this;
  55166. };
  55167. ShaderMaterial.prototype.setFloats = function (name, value) {
  55168. this._checkUniform(name);
  55169. this._floatsArrays[name] = value;
  55170. return this;
  55171. };
  55172. ShaderMaterial.prototype.setColor3 = function (name, value) {
  55173. this._checkUniform(name);
  55174. this._colors3[name] = value;
  55175. return this;
  55176. };
  55177. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  55178. this._checkUniform(name);
  55179. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  55180. color.toArray(arr, arr.length);
  55181. return arr;
  55182. }, []);
  55183. return this;
  55184. };
  55185. ShaderMaterial.prototype.setColor4 = function (name, value) {
  55186. this._checkUniform(name);
  55187. this._colors4[name] = value;
  55188. return this;
  55189. };
  55190. ShaderMaterial.prototype.setVector2 = function (name, value) {
  55191. this._checkUniform(name);
  55192. this._vectors2[name] = value;
  55193. return this;
  55194. };
  55195. ShaderMaterial.prototype.setVector3 = function (name, value) {
  55196. this._checkUniform(name);
  55197. this._vectors3[name] = value;
  55198. return this;
  55199. };
  55200. ShaderMaterial.prototype.setVector4 = function (name, value) {
  55201. this._checkUniform(name);
  55202. this._vectors4[name] = value;
  55203. return this;
  55204. };
  55205. ShaderMaterial.prototype.setMatrix = function (name, value) {
  55206. this._checkUniform(name);
  55207. this._matrices[name] = value;
  55208. return this;
  55209. };
  55210. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  55211. this._checkUniform(name);
  55212. this._matrices3x3[name] = value;
  55213. return this;
  55214. };
  55215. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  55216. this._checkUniform(name);
  55217. this._matrices2x2[name] = value;
  55218. return this;
  55219. };
  55220. ShaderMaterial.prototype.setArray2 = function (name, value) {
  55221. this._checkUniform(name);
  55222. this._vectors2Arrays[name] = value;
  55223. return this;
  55224. };
  55225. ShaderMaterial.prototype.setArray3 = function (name, value) {
  55226. this._checkUniform(name);
  55227. this._vectors3Arrays[name] = value;
  55228. return this;
  55229. };
  55230. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  55231. if (!mesh) {
  55232. return true;
  55233. }
  55234. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  55235. return false;
  55236. }
  55237. return false;
  55238. };
  55239. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  55240. var scene = this.getScene();
  55241. var engine = scene.getEngine();
  55242. if (!this.checkReadyOnEveryCall) {
  55243. if (this._renderId === scene.getRenderId()) {
  55244. if (this._checkCache(scene, mesh, useInstances)) {
  55245. return true;
  55246. }
  55247. }
  55248. }
  55249. // Instances
  55250. var defines = [];
  55251. var attribs = [];
  55252. var fallbacks = new BABYLON.EffectFallbacks();
  55253. if (useInstances) {
  55254. defines.push("#define INSTANCES");
  55255. }
  55256. for (var index = 0; index < this._options.defines.length; index++) {
  55257. defines.push(this._options.defines[index]);
  55258. }
  55259. for (var index = 0; index < this._options.attributes.length; index++) {
  55260. attribs.push(this._options.attributes[index]);
  55261. }
  55262. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  55263. attribs.push(BABYLON.VertexBuffer.ColorKind);
  55264. defines.push("#define VERTEXCOLOR");
  55265. }
  55266. // Bones
  55267. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  55268. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55269. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55270. if (mesh.numBoneInfluencers > 4) {
  55271. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  55272. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  55273. }
  55274. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55275. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55276. fallbacks.addCPUSkinningFallback(0, mesh);
  55277. if (this._options.uniforms.indexOf("mBones") === -1) {
  55278. this._options.uniforms.push("mBones");
  55279. }
  55280. }
  55281. else {
  55282. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55283. }
  55284. // Textures
  55285. for (var name in this._textures) {
  55286. if (!this._textures[name].isReady()) {
  55287. return false;
  55288. }
  55289. }
  55290. // Alpha test
  55291. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  55292. defines.push("#define ALPHATEST");
  55293. }
  55294. var previousEffect = this._effect;
  55295. var join = defines.join("\n");
  55296. this._effect = engine.createEffect(this._shaderPath, {
  55297. attributes: attribs,
  55298. uniformsNames: this._options.uniforms,
  55299. uniformBuffersNames: this._options.uniformBuffers,
  55300. samplers: this._options.samplers,
  55301. defines: join,
  55302. fallbacks: fallbacks,
  55303. onCompiled: this.onCompiled,
  55304. onError: this.onError
  55305. }, engine);
  55306. if (!this._effect.isReady()) {
  55307. return false;
  55308. }
  55309. if (previousEffect !== this._effect) {
  55310. scene.resetCachedMaterial();
  55311. }
  55312. this._renderId = scene.getRenderId();
  55313. return true;
  55314. };
  55315. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  55316. var scene = this.getScene();
  55317. if (!this._effect) {
  55318. return;
  55319. }
  55320. if (this._options.uniforms.indexOf("world") !== -1) {
  55321. this._effect.setMatrix("world", world);
  55322. }
  55323. if (this._options.uniforms.indexOf("worldView") !== -1) {
  55324. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  55325. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  55326. }
  55327. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  55328. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  55329. }
  55330. };
  55331. ShaderMaterial.prototype.bind = function (world, mesh) {
  55332. // Std values
  55333. this.bindOnlyWorldMatrix(world);
  55334. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  55335. if (this._options.uniforms.indexOf("view") !== -1) {
  55336. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  55337. }
  55338. if (this._options.uniforms.indexOf("projection") !== -1) {
  55339. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  55340. }
  55341. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  55342. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  55343. }
  55344. // Bones
  55345. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  55346. var name;
  55347. // Texture
  55348. for (name in this._textures) {
  55349. this._effect.setTexture(name, this._textures[name]);
  55350. }
  55351. // Texture arrays
  55352. for (name in this._textureArrays) {
  55353. this._effect.setTextureArray(name, this._textureArrays[name]);
  55354. }
  55355. // Int
  55356. for (name in this._ints) {
  55357. this._effect.setInt(name, this._ints[name]);
  55358. }
  55359. // Float
  55360. for (name in this._floats) {
  55361. this._effect.setFloat(name, this._floats[name]);
  55362. }
  55363. // Floats
  55364. for (name in this._floatsArrays) {
  55365. this._effect.setArray(name, this._floatsArrays[name]);
  55366. }
  55367. // Color3
  55368. for (name in this._colors3) {
  55369. this._effect.setColor3(name, this._colors3[name]);
  55370. }
  55371. for (name in this._colors3Arrays) {
  55372. this._effect.setArray3(name, this._colors3Arrays[name]);
  55373. }
  55374. // Color4
  55375. for (name in this._colors4) {
  55376. var color = this._colors4[name];
  55377. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  55378. }
  55379. // Vector2
  55380. for (name in this._vectors2) {
  55381. this._effect.setVector2(name, this._vectors2[name]);
  55382. }
  55383. // Vector3
  55384. for (name in this._vectors3) {
  55385. this._effect.setVector3(name, this._vectors3[name]);
  55386. }
  55387. // Vector4
  55388. for (name in this._vectors4) {
  55389. this._effect.setVector4(name, this._vectors4[name]);
  55390. }
  55391. // Matrix
  55392. for (name in this._matrices) {
  55393. this._effect.setMatrix(name, this._matrices[name]);
  55394. }
  55395. // Matrix 3x3
  55396. for (name in this._matrices3x3) {
  55397. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  55398. }
  55399. // Matrix 2x2
  55400. for (name in this._matrices2x2) {
  55401. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  55402. }
  55403. // Vector2Array
  55404. for (name in this._vectors2Arrays) {
  55405. this._effect.setArray2(name, this._vectors2Arrays[name]);
  55406. }
  55407. // Vector3Array
  55408. for (name in this._vectors3Arrays) {
  55409. this._effect.setArray3(name, this._vectors3Arrays[name]);
  55410. }
  55411. }
  55412. this._afterBind(mesh);
  55413. };
  55414. ShaderMaterial.prototype.getActiveTextures = function () {
  55415. var activeTextures = _super.prototype.getActiveTextures.call(this);
  55416. for (var name in this._textures) {
  55417. activeTextures.push(this._textures[name]);
  55418. }
  55419. for (var name in this._textureArrays) {
  55420. var array = this._textureArrays[name];
  55421. for (var index = 0; index < array.length; index++) {
  55422. activeTextures.push(array[index]);
  55423. }
  55424. }
  55425. return activeTextures;
  55426. };
  55427. ShaderMaterial.prototype.hasTexture = function (texture) {
  55428. if (_super.prototype.hasTexture.call(this, texture)) {
  55429. return true;
  55430. }
  55431. for (var name in this._textures) {
  55432. if (this._textures[name] === texture) {
  55433. return true;
  55434. }
  55435. }
  55436. for (var name in this._textureArrays) {
  55437. var array = this._textureArrays[name];
  55438. for (var index = 0; index < array.length; index++) {
  55439. if (array[index] === texture) {
  55440. return true;
  55441. }
  55442. }
  55443. }
  55444. return false;
  55445. };
  55446. ShaderMaterial.prototype.clone = function (name) {
  55447. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  55448. return newShaderMaterial;
  55449. };
  55450. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  55451. if (forceDisposeTextures) {
  55452. var name;
  55453. for (name in this._textures) {
  55454. this._textures[name].dispose();
  55455. }
  55456. for (name in this._textureArrays) {
  55457. var array = this._textureArrays[name];
  55458. for (var index = 0; index < array.length; index++) {
  55459. array[index].dispose();
  55460. }
  55461. }
  55462. }
  55463. this._textures = {};
  55464. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  55465. };
  55466. ShaderMaterial.prototype.serialize = function () {
  55467. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  55468. serializationObject.customType = "BABYLON.ShaderMaterial";
  55469. serializationObject.options = this._options;
  55470. serializationObject.shaderPath = this._shaderPath;
  55471. var name;
  55472. // Texture
  55473. serializationObject.textures = {};
  55474. for (name in this._textures) {
  55475. serializationObject.textures[name] = this._textures[name].serialize();
  55476. }
  55477. // Texture arrays
  55478. serializationObject.textureArrays = {};
  55479. for (name in this._textureArrays) {
  55480. serializationObject.textureArrays[name] = [];
  55481. var array = this._textureArrays[name];
  55482. for (var index = 0; index < array.length; index++) {
  55483. serializationObject.textureArrays[name].push(array[index].serialize());
  55484. }
  55485. }
  55486. // Float
  55487. serializationObject.floats = {};
  55488. for (name in this._floats) {
  55489. serializationObject.floats[name] = this._floats[name];
  55490. }
  55491. // Float s
  55492. serializationObject.FloatArrays = {};
  55493. for (name in this._floatsArrays) {
  55494. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  55495. }
  55496. // Color3
  55497. serializationObject.colors3 = {};
  55498. for (name in this._colors3) {
  55499. serializationObject.colors3[name] = this._colors3[name].asArray();
  55500. }
  55501. // Color3 array
  55502. serializationObject.colors3Arrays = {};
  55503. for (name in this._colors3Arrays) {
  55504. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  55505. }
  55506. // Color4
  55507. serializationObject.colors4 = {};
  55508. for (name in this._colors4) {
  55509. serializationObject.colors4[name] = this._colors4[name].asArray();
  55510. }
  55511. // Vector2
  55512. serializationObject.vectors2 = {};
  55513. for (name in this._vectors2) {
  55514. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  55515. }
  55516. // Vector3
  55517. serializationObject.vectors3 = {};
  55518. for (name in this._vectors3) {
  55519. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  55520. }
  55521. // Vector4
  55522. serializationObject.vectors4 = {};
  55523. for (name in this._vectors4) {
  55524. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  55525. }
  55526. // Matrix
  55527. serializationObject.matrices = {};
  55528. for (name in this._matrices) {
  55529. serializationObject.matrices[name] = this._matrices[name].asArray();
  55530. }
  55531. // Matrix 3x3
  55532. serializationObject.matrices3x3 = {};
  55533. for (name in this._matrices3x3) {
  55534. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  55535. }
  55536. // Matrix 2x2
  55537. serializationObject.matrices2x2 = {};
  55538. for (name in this._matrices2x2) {
  55539. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  55540. }
  55541. // Vector2Array
  55542. serializationObject.vectors2Arrays = {};
  55543. for (name in this._vectors2Arrays) {
  55544. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  55545. }
  55546. // Vector3Array
  55547. serializationObject.vectors3Arrays = {};
  55548. for (name in this._vectors3Arrays) {
  55549. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  55550. }
  55551. return serializationObject;
  55552. };
  55553. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  55554. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  55555. var name;
  55556. // Texture
  55557. for (name in source.textures) {
  55558. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  55559. }
  55560. // Texture arrays
  55561. for (name in source.textureArrays) {
  55562. var array = source.textureArrays[name];
  55563. var textureArray = new Array();
  55564. for (var index = 0; index < array.length; index++) {
  55565. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  55566. }
  55567. material.setTextureArray(name, textureArray);
  55568. }
  55569. // Float
  55570. for (name in source.floats) {
  55571. material.setFloat(name, source.floats[name]);
  55572. }
  55573. // Float s
  55574. for (name in source.floatsArrays) {
  55575. material.setFloats(name, source.floatsArrays[name]);
  55576. }
  55577. // Color3
  55578. for (name in source.colors3) {
  55579. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  55580. }
  55581. // Color3 arrays
  55582. for (name in source.colors3Arrays) {
  55583. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  55584. if (i % 3 === 0) {
  55585. arr.push([num]);
  55586. }
  55587. else {
  55588. arr[arr.length - 1].push(num);
  55589. }
  55590. return arr;
  55591. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  55592. material.setColor3Array(name, colors);
  55593. }
  55594. // Color4
  55595. for (name in source.colors4) {
  55596. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  55597. }
  55598. // Vector2
  55599. for (name in source.vectors2) {
  55600. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  55601. }
  55602. // Vector3
  55603. for (name in source.vectors3) {
  55604. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  55605. }
  55606. // Vector4
  55607. for (name in source.vectors4) {
  55608. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  55609. }
  55610. // Matrix
  55611. for (name in source.matrices) {
  55612. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  55613. }
  55614. // Matrix 3x3
  55615. for (name in source.matrices3x3) {
  55616. material.setMatrix3x3(name, source.matrices3x3[name]);
  55617. }
  55618. // Matrix 2x2
  55619. for (name in source.matrices2x2) {
  55620. material.setMatrix2x2(name, source.matrices2x2[name]);
  55621. }
  55622. // Vector2Array
  55623. for (name in source.vectors2Arrays) {
  55624. material.setArray2(name, source.vectors2Arrays[name]);
  55625. }
  55626. // Vector3Array
  55627. for (name in source.vectors3Arrays) {
  55628. material.setArray3(name, source.vectors3Arrays[name]);
  55629. }
  55630. return material;
  55631. };
  55632. return ShaderMaterial;
  55633. }(BABYLON.Material));
  55634. BABYLON.ShaderMaterial = ShaderMaterial;
  55635. })(BABYLON || (BABYLON = {}));
  55636. //# sourceMappingURL=babylon.shaderMaterial.js.map
  55637. "use strict";
  55638. var BABYLON;
  55639. (function (BABYLON) {
  55640. var GroundMesh = /** @class */ (function (_super) {
  55641. __extends(GroundMesh, _super);
  55642. function GroundMesh(name, scene) {
  55643. var _this = _super.call(this, name, scene) || this;
  55644. _this.generateOctree = false;
  55645. return _this;
  55646. }
  55647. GroundMesh.prototype.getClassName = function () {
  55648. return "GroundMesh";
  55649. };
  55650. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  55651. get: function () {
  55652. return Math.min(this._subdivisionsX, this._subdivisionsY);
  55653. },
  55654. enumerable: true,
  55655. configurable: true
  55656. });
  55657. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  55658. get: function () {
  55659. return this._subdivisionsX;
  55660. },
  55661. enumerable: true,
  55662. configurable: true
  55663. });
  55664. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  55665. get: function () {
  55666. return this._subdivisionsY;
  55667. },
  55668. enumerable: true,
  55669. configurable: true
  55670. });
  55671. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  55672. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  55673. this._subdivisionsX = chunksCount;
  55674. this._subdivisionsY = chunksCount;
  55675. this.subdivide(chunksCount);
  55676. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  55677. };
  55678. /**
  55679. * Returns a height (y) value in the Worl system :
  55680. * the ground altitude at the coordinates (x, z) expressed in the World system.
  55681. * Returns the ground y position if (x, z) are outside the ground surface.
  55682. */
  55683. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  55684. var world = this.getWorldMatrix();
  55685. var invMat = BABYLON.Tmp.Matrix[5];
  55686. world.invertToRef(invMat);
  55687. var tmpVect = BABYLON.Tmp.Vector3[8];
  55688. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  55689. x = tmpVect.x;
  55690. z = tmpVect.z;
  55691. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55692. return this.position.y;
  55693. }
  55694. if (!this._heightQuads || this._heightQuads.length == 0) {
  55695. this._initHeightQuads();
  55696. this._computeHeightQuads();
  55697. }
  55698. var facet = this._getFacetAt(x, z);
  55699. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  55700. // return y in the World system
  55701. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  55702. return tmpVect.y;
  55703. };
  55704. /**
  55705. * Returns a normalized vector (Vector3) orthogonal to the ground
  55706. * at the ground coordinates (x, z) expressed in the World system.
  55707. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  55708. */
  55709. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  55710. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  55711. this.getNormalAtCoordinatesToRef(x, z, normal);
  55712. return normal;
  55713. };
  55714. /**
  55715. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  55716. * at the ground coordinates (x, z) expressed in the World system.
  55717. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  55718. * Returns the GroundMesh.
  55719. */
  55720. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  55721. var world = this.getWorldMatrix();
  55722. var tmpMat = BABYLON.Tmp.Matrix[5];
  55723. world.invertToRef(tmpMat);
  55724. var tmpVect = BABYLON.Tmp.Vector3[8];
  55725. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  55726. x = tmpVect.x;
  55727. z = tmpVect.z;
  55728. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55729. return this;
  55730. }
  55731. if (!this._heightQuads || this._heightQuads.length == 0) {
  55732. this._initHeightQuads();
  55733. this._computeHeightQuads();
  55734. }
  55735. var facet = this._getFacetAt(x, z);
  55736. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  55737. return this;
  55738. };
  55739. /**
  55740. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  55741. * if the ground has been updated.
  55742. * This can be used in the render loop.
  55743. * Returns the GroundMesh.
  55744. */
  55745. GroundMesh.prototype.updateCoordinateHeights = function () {
  55746. if (!this._heightQuads || this._heightQuads.length == 0) {
  55747. this._initHeightQuads();
  55748. }
  55749. this._computeHeightQuads();
  55750. return this;
  55751. };
  55752. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  55753. GroundMesh.prototype._getFacetAt = function (x, z) {
  55754. // retrieve col and row from x, z coordinates in the ground local system
  55755. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  55756. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  55757. var quad = this._heightQuads[row * this._subdivisionsX + col];
  55758. var facet;
  55759. if (z < quad.slope.x * x + quad.slope.y) {
  55760. facet = quad.facet1;
  55761. }
  55762. else {
  55763. facet = quad.facet2;
  55764. }
  55765. return facet;
  55766. };
  55767. // Creates and populates the heightMap array with "facet" elements :
  55768. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  55769. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55770. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55771. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55772. // Returns the GroundMesh.
  55773. GroundMesh.prototype._initHeightQuads = function () {
  55774. var subdivisionsX = this._subdivisionsX;
  55775. var subdivisionsY = this._subdivisionsY;
  55776. this._heightQuads = new Array();
  55777. for (var row = 0; row < subdivisionsY; row++) {
  55778. for (var col = 0; col < subdivisionsX; col++) {
  55779. 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) };
  55780. this._heightQuads[row * subdivisionsX + col] = quad;
  55781. }
  55782. }
  55783. return this;
  55784. };
  55785. // Compute each quad element values and update the the heightMap array :
  55786. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55787. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55788. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55789. // Returns the GroundMesh.
  55790. GroundMesh.prototype._computeHeightQuads = function () {
  55791. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55792. if (!positions) {
  55793. return this;
  55794. }
  55795. var v1 = BABYLON.Tmp.Vector3[3];
  55796. var v2 = BABYLON.Tmp.Vector3[2];
  55797. var v3 = BABYLON.Tmp.Vector3[1];
  55798. var v4 = BABYLON.Tmp.Vector3[0];
  55799. var v1v2 = BABYLON.Tmp.Vector3[4];
  55800. var v1v3 = BABYLON.Tmp.Vector3[5];
  55801. var v1v4 = BABYLON.Tmp.Vector3[6];
  55802. var norm1 = BABYLON.Tmp.Vector3[7];
  55803. var norm2 = BABYLON.Tmp.Vector3[8];
  55804. var i = 0;
  55805. var j = 0;
  55806. var k = 0;
  55807. var cd = 0; // 2D slope coefficient : z = cd * x + h
  55808. var h = 0;
  55809. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  55810. var d2 = 0;
  55811. var subdivisionsX = this._subdivisionsX;
  55812. var subdivisionsY = this._subdivisionsY;
  55813. for (var row = 0; row < subdivisionsY; row++) {
  55814. for (var col = 0; col < subdivisionsX; col++) {
  55815. i = col * 3;
  55816. j = row * (subdivisionsX + 1) * 3;
  55817. k = (row + 1) * (subdivisionsX + 1) * 3;
  55818. v1.x = positions[j + i];
  55819. v1.y = positions[j + i + 1];
  55820. v1.z = positions[j + i + 2];
  55821. v2.x = positions[j + i + 3];
  55822. v2.y = positions[j + i + 4];
  55823. v2.z = positions[j + i + 5];
  55824. v3.x = positions[k + i];
  55825. v3.y = positions[k + i + 1];
  55826. v3.z = positions[k + i + 2];
  55827. v4.x = positions[k + i + 3];
  55828. v4.y = positions[k + i + 4];
  55829. v4.z = positions[k + i + 5];
  55830. // 2D slope V1V4
  55831. cd = (v4.z - v1.z) / (v4.x - v1.x);
  55832. h = v1.z - cd * v1.x; // v1 belongs to the slope
  55833. // facet equations :
  55834. // we compute each facet normal vector
  55835. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  55836. // we compute the value d by applying the equation to v1 which belongs to the plane
  55837. // then we store the facet equation in a Vector4
  55838. v2.subtractToRef(v1, v1v2);
  55839. v3.subtractToRef(v1, v1v3);
  55840. v4.subtractToRef(v1, v1v4);
  55841. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  55842. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  55843. norm1.normalize();
  55844. norm2.normalize();
  55845. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  55846. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  55847. var quad = this._heightQuads[row * subdivisionsX + col];
  55848. quad.slope.copyFromFloats(cd, h);
  55849. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  55850. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  55851. }
  55852. }
  55853. return this;
  55854. };
  55855. GroundMesh.prototype.serialize = function (serializationObject) {
  55856. _super.prototype.serialize.call(this, serializationObject);
  55857. serializationObject.subdivisionsX = this._subdivisionsX;
  55858. serializationObject.subdivisionsY = this._subdivisionsY;
  55859. serializationObject.minX = this._minX;
  55860. serializationObject.maxX = this._maxX;
  55861. serializationObject.minZ = this._minZ;
  55862. serializationObject.maxZ = this._maxZ;
  55863. serializationObject.width = this._width;
  55864. serializationObject.height = this._height;
  55865. };
  55866. GroundMesh.Parse = function (parsedMesh, scene) {
  55867. var result = new GroundMesh(parsedMesh.name, scene);
  55868. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  55869. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  55870. result._minX = parsedMesh.minX;
  55871. result._maxX = parsedMesh.maxX;
  55872. result._minZ = parsedMesh.minZ;
  55873. result._maxZ = parsedMesh.maxZ;
  55874. result._width = parsedMesh.width;
  55875. result._height = parsedMesh.height;
  55876. return result;
  55877. };
  55878. return GroundMesh;
  55879. }(BABYLON.Mesh));
  55880. BABYLON.GroundMesh = GroundMesh;
  55881. })(BABYLON || (BABYLON = {}));
  55882. //# sourceMappingURL=babylon.groundMesh.js.map
  55883. "use strict";
  55884. var BABYLON;
  55885. (function (BABYLON) {
  55886. /**
  55887. * Creates an instance based on a source mesh.
  55888. */
  55889. var InstancedMesh = /** @class */ (function (_super) {
  55890. __extends(InstancedMesh, _super);
  55891. function InstancedMesh(name, source) {
  55892. var _this = _super.call(this, name, source.getScene()) || this;
  55893. source.instances.push(_this);
  55894. _this._sourceMesh = source;
  55895. _this.position.copyFrom(source.position);
  55896. _this.rotation.copyFrom(source.rotation);
  55897. _this.scaling.copyFrom(source.scaling);
  55898. if (source.rotationQuaternion) {
  55899. _this.rotationQuaternion = source.rotationQuaternion.clone();
  55900. }
  55901. _this.infiniteDistance = source.infiniteDistance;
  55902. _this.setPivotMatrix(source.getPivotMatrix());
  55903. _this.refreshBoundingInfo();
  55904. _this._syncSubMeshes();
  55905. return _this;
  55906. }
  55907. /**
  55908. * Returns the string "InstancedMesh".
  55909. */
  55910. InstancedMesh.prototype.getClassName = function () {
  55911. return "InstancedMesh";
  55912. };
  55913. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  55914. // Methods
  55915. get: function () {
  55916. return this._sourceMesh.receiveShadows;
  55917. },
  55918. enumerable: true,
  55919. configurable: true
  55920. });
  55921. Object.defineProperty(InstancedMesh.prototype, "material", {
  55922. get: function () {
  55923. return this._sourceMesh.material;
  55924. },
  55925. enumerable: true,
  55926. configurable: true
  55927. });
  55928. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  55929. get: function () {
  55930. return this._sourceMesh.visibility;
  55931. },
  55932. enumerable: true,
  55933. configurable: true
  55934. });
  55935. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  55936. get: function () {
  55937. return this._sourceMesh.skeleton;
  55938. },
  55939. enumerable: true,
  55940. configurable: true
  55941. });
  55942. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  55943. get: function () {
  55944. return this._sourceMesh.renderingGroupId;
  55945. },
  55946. set: function (value) {
  55947. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  55948. return;
  55949. }
  55950. //no-op with warning
  55951. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  55952. },
  55953. enumerable: true,
  55954. configurable: true
  55955. });
  55956. /**
  55957. * Returns the total number of vertices (integer).
  55958. */
  55959. InstancedMesh.prototype.getTotalVertices = function () {
  55960. return this._sourceMesh.getTotalVertices();
  55961. };
  55962. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  55963. get: function () {
  55964. return this._sourceMesh;
  55965. },
  55966. enumerable: true,
  55967. configurable: true
  55968. });
  55969. /**
  55970. * Is this node ready to be used/rendered
  55971. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  55972. * @return {boolean} is it ready
  55973. */
  55974. InstancedMesh.prototype.isReady = function (completeCheck) {
  55975. if (completeCheck === void 0) { completeCheck = false; }
  55976. return this._sourceMesh.isReady(completeCheck, true);
  55977. };
  55978. /**
  55979. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  55980. */
  55981. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  55982. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  55983. };
  55984. /**
  55985. * Sets the vertex data of the mesh geometry for the requested `kind`.
  55986. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  55987. * The `data` are either a numeric array either a Float32Array.
  55988. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  55989. * 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).
  55990. * Note that a new underlying VertexBuffer object is created each call.
  55991. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  55992. *
  55993. * Possible `kind` values :
  55994. * - BABYLON.VertexBuffer.PositionKind
  55995. * - BABYLON.VertexBuffer.UVKind
  55996. * - BABYLON.VertexBuffer.UV2Kind
  55997. * - BABYLON.VertexBuffer.UV3Kind
  55998. * - BABYLON.VertexBuffer.UV4Kind
  55999. * - BABYLON.VertexBuffer.UV5Kind
  56000. * - BABYLON.VertexBuffer.UV6Kind
  56001. * - BABYLON.VertexBuffer.ColorKind
  56002. * - BABYLON.VertexBuffer.MatricesIndicesKind
  56003. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  56004. * - BABYLON.VertexBuffer.MatricesWeightsKind
  56005. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  56006. *
  56007. * Returns the Mesh.
  56008. */
  56009. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  56010. if (this.sourceMesh) {
  56011. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  56012. }
  56013. return this.sourceMesh;
  56014. };
  56015. /**
  56016. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  56017. * If the mesh has no geometry, it is simply returned as it is.
  56018. * The `data` are either a numeric array either a Float32Array.
  56019. * No new underlying VertexBuffer object is created.
  56020. * 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.
  56021. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  56022. *
  56023. * Possible `kind` values :
  56024. * - BABYLON.VertexBuffer.PositionKind
  56025. * - BABYLON.VertexBuffer.UVKind
  56026. * - BABYLON.VertexBuffer.UV2Kind
  56027. * - BABYLON.VertexBuffer.UV3Kind
  56028. * - BABYLON.VertexBuffer.UV4Kind
  56029. * - BABYLON.VertexBuffer.UV5Kind
  56030. * - BABYLON.VertexBuffer.UV6Kind
  56031. * - BABYLON.VertexBuffer.ColorKind
  56032. * - BABYLON.VertexBuffer.MatricesIndicesKind
  56033. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  56034. * - BABYLON.VertexBuffer.MatricesWeightsKind
  56035. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  56036. *
  56037. * Returns the Mesh.
  56038. */
  56039. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  56040. if (this.sourceMesh) {
  56041. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  56042. }
  56043. return this.sourceMesh;
  56044. };
  56045. /**
  56046. * Sets the mesh indices.
  56047. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  56048. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  56049. * This method creates a new index buffer each call.
  56050. * Returns the Mesh.
  56051. */
  56052. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  56053. if (totalVertices === void 0) { totalVertices = null; }
  56054. if (this.sourceMesh) {
  56055. this.sourceMesh.setIndices(indices, totalVertices);
  56056. }
  56057. return this.sourceMesh;
  56058. };
  56059. /**
  56060. * Boolean : True if the mesh owns the requested kind of data.
  56061. */
  56062. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  56063. return this._sourceMesh.isVerticesDataPresent(kind);
  56064. };
  56065. /**
  56066. * Returns an array of indices (IndicesArray).
  56067. */
  56068. InstancedMesh.prototype.getIndices = function () {
  56069. return this._sourceMesh.getIndices();
  56070. };
  56071. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  56072. get: function () {
  56073. return this._sourceMesh._positions;
  56074. },
  56075. enumerable: true,
  56076. configurable: true
  56077. });
  56078. /**
  56079. * Sets a new updated BoundingInfo to the mesh.
  56080. * Returns the mesh.
  56081. */
  56082. InstancedMesh.prototype.refreshBoundingInfo = function () {
  56083. var meshBB = this._sourceMesh.getBoundingInfo();
  56084. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  56085. this._updateBoundingInfo();
  56086. return this;
  56087. };
  56088. InstancedMesh.prototype._preActivate = function () {
  56089. if (this._currentLOD) {
  56090. this._currentLOD._preActivate();
  56091. }
  56092. return this;
  56093. };
  56094. InstancedMesh.prototype._activate = function (renderId) {
  56095. if (this._currentLOD) {
  56096. this._currentLOD._registerInstanceForRenderId(this, renderId);
  56097. }
  56098. return this;
  56099. };
  56100. /**
  56101. * Returns the current associated LOD AbstractMesh.
  56102. */
  56103. InstancedMesh.prototype.getLOD = function (camera) {
  56104. if (!camera) {
  56105. return this;
  56106. }
  56107. var boundingInfo = this.getBoundingInfo();
  56108. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  56109. if (this._currentLOD === this.sourceMesh) {
  56110. return this;
  56111. }
  56112. return this._currentLOD;
  56113. };
  56114. InstancedMesh.prototype._syncSubMeshes = function () {
  56115. this.releaseSubMeshes();
  56116. if (this._sourceMesh.subMeshes) {
  56117. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  56118. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  56119. }
  56120. }
  56121. return this;
  56122. };
  56123. InstancedMesh.prototype._generatePointsArray = function () {
  56124. return this._sourceMesh._generatePointsArray();
  56125. };
  56126. /**
  56127. * Creates a new InstancedMesh from the current mesh.
  56128. * - name (string) : the cloned mesh name
  56129. * - newParent (optional Node) : the optional Node to parent the clone to.
  56130. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  56131. *
  56132. * Returns the clone.
  56133. */
  56134. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  56135. var result = this._sourceMesh.createInstance(name);
  56136. // Deep copy
  56137. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  56138. // Bounding info
  56139. this.refreshBoundingInfo();
  56140. // Parent
  56141. if (newParent) {
  56142. result.parent = newParent;
  56143. }
  56144. if (!doNotCloneChildren) {
  56145. // Children
  56146. for (var index = 0; index < this.getScene().meshes.length; index++) {
  56147. var mesh = this.getScene().meshes[index];
  56148. if (mesh.parent === this) {
  56149. mesh.clone(mesh.name, result);
  56150. }
  56151. }
  56152. }
  56153. result.computeWorldMatrix(true);
  56154. return result;
  56155. };
  56156. /**
  56157. * Disposes the InstancedMesh.
  56158. * Returns nothing.
  56159. */
  56160. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  56161. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  56162. // Remove from mesh
  56163. var index = this._sourceMesh.instances.indexOf(this);
  56164. this._sourceMesh.instances.splice(index, 1);
  56165. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  56166. };
  56167. return InstancedMesh;
  56168. }(BABYLON.AbstractMesh));
  56169. BABYLON.InstancedMesh = InstancedMesh;
  56170. })(BABYLON || (BABYLON = {}));
  56171. //# sourceMappingURL=babylon.instancedMesh.js.map
  56172. "use strict";
  56173. var BABYLON;
  56174. (function (BABYLON) {
  56175. var LinesMesh = /** @class */ (function (_super) {
  56176. __extends(LinesMesh, _super);
  56177. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  56178. if (scene === void 0) { scene = null; }
  56179. if (parent === void 0) { parent = null; }
  56180. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  56181. _this.useVertexColor = useVertexColor;
  56182. _this.useVertexAlpha = useVertexAlpha;
  56183. _this.color = new BABYLON.Color3(1, 1, 1);
  56184. _this.alpha = 1;
  56185. if (source) {
  56186. _this.color = source.color.clone();
  56187. _this.alpha = source.alpha;
  56188. _this.useVertexColor = source.useVertexColor;
  56189. _this.useVertexAlpha = source.useVertexAlpha;
  56190. }
  56191. _this._intersectionThreshold = 0.1;
  56192. var defines = [];
  56193. var options = {
  56194. attributes: [BABYLON.VertexBuffer.PositionKind],
  56195. uniforms: ["world", "viewProjection"],
  56196. needAlphaBlending: true,
  56197. defines: defines
  56198. };
  56199. if (useVertexAlpha === false) {
  56200. options.needAlphaBlending = false;
  56201. }
  56202. if (!useVertexColor) {
  56203. options.uniforms.push("color");
  56204. }
  56205. else {
  56206. options.defines.push("#define VERTEXCOLOR");
  56207. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  56208. }
  56209. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  56210. return _this;
  56211. }
  56212. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  56213. /**
  56214. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  56215. * This margin is expressed in world space coordinates, so its value may vary.
  56216. * Default value is 0.1
  56217. * @returns the intersection Threshold value.
  56218. */
  56219. get: function () {
  56220. return this._intersectionThreshold;
  56221. },
  56222. /**
  56223. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  56224. * This margin is expressed in world space coordinates, so its value may vary.
  56225. * @param value the new threshold to apply
  56226. */
  56227. set: function (value) {
  56228. if (this._intersectionThreshold === value) {
  56229. return;
  56230. }
  56231. this._intersectionThreshold = value;
  56232. if (this.geometry) {
  56233. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  56234. }
  56235. },
  56236. enumerable: true,
  56237. configurable: true
  56238. });
  56239. /**
  56240. * Returns the string "LineMesh"
  56241. */
  56242. LinesMesh.prototype.getClassName = function () {
  56243. return "LinesMesh";
  56244. };
  56245. Object.defineProperty(LinesMesh.prototype, "material", {
  56246. get: function () {
  56247. return this._colorShader;
  56248. },
  56249. set: function (value) {
  56250. // Do nothing
  56251. },
  56252. enumerable: true,
  56253. configurable: true
  56254. });
  56255. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  56256. get: function () {
  56257. return false;
  56258. },
  56259. enumerable: true,
  56260. configurable: true
  56261. });
  56262. LinesMesh.prototype.createInstance = function (name) {
  56263. throw new Error("LinesMeshes do not support createInstance.");
  56264. };
  56265. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  56266. if (!this._geometry) {
  56267. return this;
  56268. }
  56269. // VBOs
  56270. this._geometry._bind(this._colorShader.getEffect());
  56271. // Color
  56272. if (!this.useVertexColor) {
  56273. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  56274. }
  56275. return this;
  56276. };
  56277. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  56278. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  56279. return this;
  56280. }
  56281. var engine = this.getScene().getEngine();
  56282. // Draw order
  56283. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  56284. return this;
  56285. };
  56286. LinesMesh.prototype.dispose = function (doNotRecurse) {
  56287. this._colorShader.dispose();
  56288. _super.prototype.dispose.call(this, doNotRecurse);
  56289. };
  56290. /**
  56291. * Returns a new LineMesh object cloned from the current one.
  56292. */
  56293. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  56294. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  56295. };
  56296. return LinesMesh;
  56297. }(BABYLON.Mesh));
  56298. BABYLON.LinesMesh = LinesMesh;
  56299. })(BABYLON || (BABYLON = {}));
  56300. //# sourceMappingURL=babylon.linesMesh.js.map
  56301. "use strict";
  56302. var BABYLON;
  56303. (function (BABYLON) {
  56304. var MeshBuilder = /** @class */ (function () {
  56305. function MeshBuilder() {
  56306. }
  56307. MeshBuilder.updateSideOrientation = function (orientation) {
  56308. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  56309. return BABYLON.Mesh.DOUBLESIDE;
  56310. }
  56311. if (orientation === undefined || orientation === null) {
  56312. return BABYLON.Mesh.FRONTSIDE;
  56313. }
  56314. return orientation;
  56315. };
  56316. /**
  56317. * Creates a box mesh.
  56318. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  56319. * The parameter `size` sets the size (float) of each box side (default 1).
  56320. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  56321. * 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).
  56322. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  56323. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56324. * 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).
  56325. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56326. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56327. */
  56328. MeshBuilder.CreateBox = function (name, options, scene) {
  56329. if (scene === void 0) { scene = null; }
  56330. var box = new BABYLON.Mesh(name, scene);
  56331. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56332. box._originalBuilderSideOrientation = options.sideOrientation;
  56333. var vertexData = BABYLON.VertexData.CreateBox(options);
  56334. vertexData.applyToMesh(box, options.updatable);
  56335. return box;
  56336. };
  56337. /**
  56338. * Creates a sphere mesh.
  56339. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  56340. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  56341. * 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`).
  56342. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  56343. * 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
  56344. * 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).
  56345. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56346. * 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).
  56347. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56348. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56349. */
  56350. MeshBuilder.CreateSphere = function (name, options, scene) {
  56351. var sphere = new BABYLON.Mesh(name, scene);
  56352. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56353. sphere._originalBuilderSideOrientation = options.sideOrientation;
  56354. var vertexData = BABYLON.VertexData.CreateSphere(options);
  56355. vertexData.applyToMesh(sphere, options.updatable);
  56356. return sphere;
  56357. };
  56358. /**
  56359. * Creates a plane polygonal mesh. By default, this is a disc.
  56360. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  56361. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  56362. * 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.
  56363. * 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
  56364. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56365. * 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).
  56366. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56367. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56368. */
  56369. MeshBuilder.CreateDisc = function (name, options, scene) {
  56370. if (scene === void 0) { scene = null; }
  56371. var disc = new BABYLON.Mesh(name, scene);
  56372. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56373. disc._originalBuilderSideOrientation = options.sideOrientation;
  56374. var vertexData = BABYLON.VertexData.CreateDisc(options);
  56375. vertexData.applyToMesh(disc, options.updatable);
  56376. return disc;
  56377. };
  56378. /**
  56379. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  56380. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  56381. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  56382. * 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`).
  56383. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  56384. * 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.
  56385. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56386. * 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).
  56387. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56388. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56389. */
  56390. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  56391. var sphere = new BABYLON.Mesh(name, scene);
  56392. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56393. sphere._originalBuilderSideOrientation = options.sideOrientation;
  56394. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  56395. vertexData.applyToMesh(sphere, options.updatable);
  56396. return sphere;
  56397. };
  56398. ;
  56399. /**
  56400. * Creates a ribbon mesh.
  56401. * 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.
  56402. *
  56403. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  56404. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  56405. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  56406. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  56407. * 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.
  56408. * 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.
  56409. * 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
  56410. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56411. * 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).
  56412. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56413. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56414. * 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.
  56415. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  56416. * 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
  56417. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  56418. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  56419. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56420. */
  56421. MeshBuilder.CreateRibbon = function (name, options, scene) {
  56422. if (scene === void 0) { scene = null; }
  56423. var pathArray = options.pathArray;
  56424. var closeArray = options.closeArray;
  56425. var closePath = options.closePath;
  56426. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56427. var instance = options.instance;
  56428. var updatable = options.updatable;
  56429. if (instance) {
  56430. // positionFunction : ribbon case
  56431. // only pathArray and sideOrientation parameters are taken into account for positions update
  56432. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  56433. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  56434. var positionFunction = function (positions) {
  56435. var minlg = pathArray[0].length;
  56436. var i = 0;
  56437. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  56438. for (var si = 1; si <= ns; si++) {
  56439. for (var p = 0; p < pathArray.length; p++) {
  56440. var path = pathArray[p];
  56441. var l = path.length;
  56442. minlg = (minlg < l) ? minlg : l;
  56443. var j = 0;
  56444. while (j < minlg) {
  56445. positions[i] = path[j].x;
  56446. positions[i + 1] = path[j].y;
  56447. positions[i + 2] = path[j].z;
  56448. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  56449. BABYLON.Tmp.Vector3[0].x = path[j].x;
  56450. }
  56451. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  56452. BABYLON.Tmp.Vector3[1].x = path[j].x;
  56453. }
  56454. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  56455. BABYLON.Tmp.Vector3[0].y = path[j].y;
  56456. }
  56457. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  56458. BABYLON.Tmp.Vector3[1].y = path[j].y;
  56459. }
  56460. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  56461. BABYLON.Tmp.Vector3[0].z = path[j].z;
  56462. }
  56463. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  56464. BABYLON.Tmp.Vector3[1].z = path[j].z;
  56465. }
  56466. j++;
  56467. i += 3;
  56468. }
  56469. if (instance._closePath) {
  56470. positions[i] = path[0].x;
  56471. positions[i + 1] = path[0].y;
  56472. positions[i + 2] = path[0].z;
  56473. i += 3;
  56474. }
  56475. }
  56476. }
  56477. };
  56478. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56479. positionFunction(positions);
  56480. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  56481. instance._boundingInfo.update(instance._worldMatrix);
  56482. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56483. if (options.colors) {
  56484. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56485. for (var c = 0; c < options.colors.length; c++) {
  56486. colors[c * 4] = options.colors[c].r;
  56487. colors[c * 4 + 1] = options.colors[c].g;
  56488. colors[c * 4 + 2] = options.colors[c].b;
  56489. colors[c * 4 + 3] = options.colors[c].a;
  56490. }
  56491. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  56492. }
  56493. if (options.uvs) {
  56494. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56495. for (var i = 0; i < options.uvs.length; i++) {
  56496. uvs[i * 2] = options.uvs[i].x;
  56497. uvs[i * 2 + 1] = options.uvs[i].y;
  56498. }
  56499. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  56500. }
  56501. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  56502. var indices = instance.getIndices();
  56503. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56504. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  56505. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  56506. if (instance._closePath) {
  56507. var indexFirst = 0;
  56508. var indexLast = 0;
  56509. for (var p = 0; p < pathArray.length; p++) {
  56510. indexFirst = instance._idx[p] * 3;
  56511. if (p + 1 < pathArray.length) {
  56512. indexLast = (instance._idx[p + 1] - 1) * 3;
  56513. }
  56514. else {
  56515. indexLast = normals.length - 3;
  56516. }
  56517. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  56518. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  56519. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  56520. normals[indexLast] = normals[indexFirst];
  56521. normals[indexLast + 1] = normals[indexFirst + 1];
  56522. normals[indexLast + 2] = normals[indexFirst + 2];
  56523. }
  56524. }
  56525. if (!(instance.areNormalsFrozen)) {
  56526. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  56527. }
  56528. }
  56529. return instance;
  56530. }
  56531. else {
  56532. var ribbon = new BABYLON.Mesh(name, scene);
  56533. ribbon._originalBuilderSideOrientation = sideOrientation;
  56534. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  56535. if (closePath) {
  56536. ribbon._idx = vertexData._idx;
  56537. }
  56538. ribbon._closePath = closePath;
  56539. ribbon._closeArray = closeArray;
  56540. vertexData.applyToMesh(ribbon, updatable);
  56541. return ribbon;
  56542. }
  56543. };
  56544. /**
  56545. * Creates a cylinder or a cone mesh.
  56546. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  56547. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  56548. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  56549. * 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.
  56550. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  56551. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  56552. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  56553. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  56554. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  56555. * 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).
  56556. * 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
  56557. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  56558. * 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
  56559. * 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.
  56560. * If `enclose` is false, a ring surface is one element.
  56561. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  56562. * 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
  56563. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56564. * 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).
  56565. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56566. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56567. */
  56568. MeshBuilder.CreateCylinder = function (name, options, scene) {
  56569. var cylinder = new BABYLON.Mesh(name, scene);
  56570. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56571. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  56572. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  56573. vertexData.applyToMesh(cylinder, options.updatable);
  56574. return cylinder;
  56575. };
  56576. /**
  56577. * Creates a torus mesh.
  56578. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  56579. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  56580. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  56581. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  56582. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56583. * 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).
  56584. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56585. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56586. */
  56587. MeshBuilder.CreateTorus = function (name, options, scene) {
  56588. var torus = new BABYLON.Mesh(name, scene);
  56589. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56590. torus._originalBuilderSideOrientation = options.sideOrientation;
  56591. var vertexData = BABYLON.VertexData.CreateTorus(options);
  56592. vertexData.applyToMesh(torus, options.updatable);
  56593. return torus;
  56594. };
  56595. /**
  56596. * Creates a torus knot mesh.
  56597. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  56598. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  56599. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  56600. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  56601. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  56602. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56603. * 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).
  56604. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56605. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56606. */
  56607. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  56608. var torusKnot = new BABYLON.Mesh(name, scene);
  56609. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56610. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  56611. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  56612. vertexData.applyToMesh(torusKnot, options.updatable);
  56613. return torusKnot;
  56614. };
  56615. /**
  56616. * Creates a line system mesh.
  56617. * A line system is a pool of many lines gathered in a single mesh.
  56618. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  56619. * 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.
  56620. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  56621. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  56622. * 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
  56623. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  56624. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  56625. * 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
  56626. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  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.CreateLineSystem = function (name, options, scene) {
  56630. var instance = options.instance;
  56631. var lines = options.lines;
  56632. var colors = options.colors;
  56633. if (instance) {
  56634. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56635. var vertexColor;
  56636. var lineColors;
  56637. if (colors) {
  56638. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56639. }
  56640. var i = 0;
  56641. var c = 0;
  56642. for (var l = 0; l < lines.length; l++) {
  56643. var points = lines[l];
  56644. for (var p = 0; p < points.length; p++) {
  56645. positions[i] = points[p].x;
  56646. positions[i + 1] = points[p].y;
  56647. positions[i + 2] = points[p].z;
  56648. if (colors && vertexColor) {
  56649. lineColors = colors[l];
  56650. vertexColor[c] = lineColors[p].r;
  56651. vertexColor[c + 1] = lineColors[p].g;
  56652. vertexColor[c + 2] = lineColors[p].b;
  56653. vertexColor[c + 3] = lineColors[p].a;
  56654. c += 4;
  56655. }
  56656. i += 3;
  56657. }
  56658. }
  56659. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56660. if (colors && vertexColor) {
  56661. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  56662. }
  56663. return instance;
  56664. }
  56665. // line system creation
  56666. var useVertexColor = (colors) ? true : false;
  56667. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  56668. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  56669. vertexData.applyToMesh(lineSystem, options.updatable);
  56670. return lineSystem;
  56671. };
  56672. /**
  56673. * Creates a line mesh.
  56674. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  56675. * 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.
  56676. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56677. * The parameter `points` is an array successive Vector3.
  56678. * 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
  56679. * The optional parameter `colors` is an array of successive Color4, one per line point.
  56680. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  56681. * When updating an instance, remember that only point positions can change, not the number of points.
  56682. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56683. */
  56684. MeshBuilder.CreateLines = function (name, options, scene) {
  56685. if (scene === void 0) { scene = null; }
  56686. var colors = (options.colors) ? [options.colors] : null;
  56687. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  56688. return lines;
  56689. };
  56690. /**
  56691. * Creates a dashed line mesh.
  56692. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  56693. * 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.
  56694. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56695. * The parameter `points` is an array successive Vector3.
  56696. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  56697. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  56698. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  56699. * 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
  56700. * When updating an instance, remember that only point positions can change, not the number of points.
  56701. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56702. */
  56703. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  56704. if (scene === void 0) { scene = null; }
  56705. var points = options.points;
  56706. var instance = options.instance;
  56707. var gapSize = options.gapSize || 1;
  56708. var dashSize = options.dashSize || 3;
  56709. if (instance) {
  56710. var positionFunction = function (positions) {
  56711. var curvect = BABYLON.Vector3.Zero();
  56712. var nbSeg = positions.length / 6;
  56713. var lg = 0;
  56714. var nb = 0;
  56715. var shft = 0;
  56716. var dashshft = 0;
  56717. var curshft = 0;
  56718. var p = 0;
  56719. var i = 0;
  56720. var j = 0;
  56721. for (i = 0; i < points.length - 1; i++) {
  56722. points[i + 1].subtractToRef(points[i], curvect);
  56723. lg += curvect.length();
  56724. }
  56725. shft = lg / nbSeg;
  56726. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  56727. for (i = 0; i < points.length - 1; i++) {
  56728. points[i + 1].subtractToRef(points[i], curvect);
  56729. nb = Math.floor(curvect.length() / shft);
  56730. curvect.normalize();
  56731. j = 0;
  56732. while (j < nb && p < positions.length) {
  56733. curshft = shft * j;
  56734. positions[p] = points[i].x + curshft * curvect.x;
  56735. positions[p + 1] = points[i].y + curshft * curvect.y;
  56736. positions[p + 2] = points[i].z + curshft * curvect.z;
  56737. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  56738. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  56739. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  56740. p += 6;
  56741. j++;
  56742. }
  56743. }
  56744. while (p < positions.length) {
  56745. positions[p] = points[i].x;
  56746. positions[p + 1] = points[i].y;
  56747. positions[p + 2] = points[i].z;
  56748. p += 3;
  56749. }
  56750. };
  56751. instance.updateMeshPositions(positionFunction, false);
  56752. return instance;
  56753. }
  56754. // dashed lines creation
  56755. var dashedLines = new BABYLON.LinesMesh(name, scene);
  56756. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  56757. vertexData.applyToMesh(dashedLines, options.updatable);
  56758. dashedLines.dashSize = dashSize;
  56759. dashedLines.gapSize = gapSize;
  56760. return dashedLines;
  56761. };
  56762. /**
  56763. * Creates an extruded shape mesh.
  56764. * 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.
  56765. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  56766. *
  56767. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56768. * 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
  56769. * extruded along the Z axis.
  56770. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56771. * 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.
  56772. * The parameter `scale` (float, default 1) is the value to scale the shape.
  56773. * 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
  56774. * 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
  56775. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56776. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56777. * 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).
  56778. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56779. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  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.ExtrudeShape = function (name, options, scene) {
  56783. if (scene === void 0) { scene = null; }
  56784. var path = options.path;
  56785. var shape = options.shape;
  56786. var scale = options.scale || 1;
  56787. var rotation = options.rotation || 0;
  56788. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56789. var updatable = options.updatable;
  56790. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56791. var instance = options.instance || null;
  56792. var invertUV = options.invertUV || false;
  56793. 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);
  56794. };
  56795. /**
  56796. * Creates an custom extruded shape mesh.
  56797. * 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.
  56798. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  56799. *
  56800. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56801. * 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
  56802. * extruded along the Z axis.
  56803. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56804. * 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
  56805. * and the distance of this point from the begining of the path :
  56806. * ```javascript
  56807. * var rotationFunction = function(i, distance) {
  56808. * // do things
  56809. * return rotationValue; }
  56810. * ```
  56811. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  56812. * 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
  56813. * and the distance of this point from the begining of the path :
  56814. * ```javascript
  56815. * var scaleFunction = function(i, distance) {
  56816. * // do things
  56817. * return scaleValue;}
  56818. * ```
  56819. * It must returns a float value that will be the scale value applied to the shape on each path point.
  56820. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  56821. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  56822. * 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
  56823. * 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
  56824. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56825. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56826. * 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).
  56827. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56828. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56829. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56830. */
  56831. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  56832. var path = options.path;
  56833. var shape = options.shape;
  56834. var scaleFunction = options.scaleFunction || (function () { return 1; });
  56835. var rotationFunction = options.rotationFunction || (function () { return 0; });
  56836. var ribbonCloseArray = options.ribbonCloseArray || false;
  56837. var ribbonClosePath = options.ribbonClosePath || false;
  56838. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56839. var updatable = options.updatable;
  56840. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56841. var instance = options.instance;
  56842. var invertUV = options.invertUV || false;
  56843. 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);
  56844. };
  56845. /**
  56846. * Creates lathe mesh.
  56847. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  56848. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  56849. *
  56850. * 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
  56851. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  56852. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  56853. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  56854. * 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.
  56855. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  56856. * 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
  56857. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56858. * 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).
  56859. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56860. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56861. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56862. */
  56863. MeshBuilder.CreateLathe = function (name, options, scene) {
  56864. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  56865. var closed = (options.closed === undefined) ? true : options.closed;
  56866. var shape = options.shape;
  56867. var radius = options.radius || 1;
  56868. var tessellation = options.tessellation || 64;
  56869. var updatable = options.updatable;
  56870. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56871. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  56872. var pi2 = Math.PI * 2;
  56873. var paths = new Array();
  56874. var invertUV = options.invertUV || false;
  56875. var i = 0;
  56876. var p = 0;
  56877. var step = pi2 / tessellation * arc;
  56878. var rotated;
  56879. var path = new Array();
  56880. ;
  56881. for (i = 0; i <= tessellation; i++) {
  56882. var path = [];
  56883. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  56884. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  56885. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  56886. }
  56887. for (p = 0; p < shape.length; p++) {
  56888. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  56889. path.push(rotated);
  56890. }
  56891. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  56892. 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));
  56893. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  56894. }
  56895. paths.push(path);
  56896. }
  56897. // lathe ribbon
  56898. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56899. return lathe;
  56900. };
  56901. /**
  56902. * Creates a plane mesh.
  56903. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56904. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  56905. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  56906. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  56907. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56908. * 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).
  56909. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56910. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56911. */
  56912. MeshBuilder.CreatePlane = function (name, options, scene) {
  56913. var plane = new BABYLON.Mesh(name, scene);
  56914. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56915. plane._originalBuilderSideOrientation = options.sideOrientation;
  56916. var vertexData = BABYLON.VertexData.CreatePlane(options);
  56917. vertexData.applyToMesh(plane, options.updatable);
  56918. if (options.sourcePlane) {
  56919. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  56920. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  56921. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  56922. plane.rotate(vectorProduct, product);
  56923. }
  56924. return plane;
  56925. };
  56926. /**
  56927. * Creates a ground mesh.
  56928. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56929. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  56930. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  56931. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56932. */
  56933. MeshBuilder.CreateGround = function (name, options, scene) {
  56934. var ground = new BABYLON.GroundMesh(name, scene);
  56935. ground._setReady(false);
  56936. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  56937. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  56938. ground._width = options.width || 1;
  56939. ground._height = options.height || 1;
  56940. ground._maxX = ground._width / 2;
  56941. ground._maxZ = ground._height / 2;
  56942. ground._minX = -ground._maxX;
  56943. ground._minZ = -ground._maxZ;
  56944. var vertexData = BABYLON.VertexData.CreateGround(options);
  56945. vertexData.applyToMesh(ground, options.updatable);
  56946. ground._setReady(true);
  56947. return ground;
  56948. };
  56949. /**
  56950. * Creates a tiled ground mesh.
  56951. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  56952. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  56953. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  56954. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  56955. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  56956. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  56957. * numbers of subdivisions on the ground width and height of each tile.
  56958. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56959. */
  56960. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  56961. var tiledGround = new BABYLON.Mesh(name, scene);
  56962. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  56963. vertexData.applyToMesh(tiledGround, options.updatable);
  56964. return tiledGround;
  56965. };
  56966. /**
  56967. * Creates a ground mesh from a height map.
  56968. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  56969. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  56970. * The parameter `url` sets the URL of the height map image resource.
  56971. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  56972. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  56973. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  56974. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  56975. * 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.
  56976. * 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).
  56977. * This function is passed the newly built mesh :
  56978. * ```javascript
  56979. * function(mesh) { // do things
  56980. * return; }
  56981. * ```
  56982. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56983. */
  56984. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  56985. var width = options.width || 10.0;
  56986. var height = options.height || 10.0;
  56987. var subdivisions = options.subdivisions || 1 | 0;
  56988. var minHeight = options.minHeight || 0.0;
  56989. var maxHeight = options.maxHeight || 1.0;
  56990. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  56991. var updatable = options.updatable;
  56992. var onReady = options.onReady;
  56993. var ground = new BABYLON.GroundMesh(name, scene);
  56994. ground._subdivisionsX = subdivisions;
  56995. ground._subdivisionsY = subdivisions;
  56996. ground._width = width;
  56997. ground._height = height;
  56998. ground._maxX = ground._width / 2.0;
  56999. ground._maxZ = ground._height / 2.0;
  57000. ground._minX = -ground._maxX;
  57001. ground._minZ = -ground._maxZ;
  57002. ground._setReady(false);
  57003. var onload = function (img) {
  57004. // Getting height map data
  57005. var canvas = document.createElement("canvas");
  57006. var context = canvas.getContext("2d");
  57007. if (!context) {
  57008. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  57009. }
  57010. if (scene.isDisposed) {
  57011. return;
  57012. }
  57013. var bufferWidth = img.width;
  57014. var bufferHeight = img.height;
  57015. canvas.width = bufferWidth;
  57016. canvas.height = bufferHeight;
  57017. context.drawImage(img, 0, 0);
  57018. // Create VertexData from map data
  57019. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  57020. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  57021. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  57022. width: width, height: height,
  57023. subdivisions: subdivisions,
  57024. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  57025. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  57026. });
  57027. vertexData.applyToMesh(ground, updatable);
  57028. //execute ready callback, if set
  57029. if (onReady) {
  57030. onReady(ground);
  57031. }
  57032. ground._setReady(true);
  57033. };
  57034. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  57035. return ground;
  57036. };
  57037. /**
  57038. * Creates a polygon mesh.
  57039. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  57040. * 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.
  57041. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57042. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57043. * 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).
  57044. * Remember you can only change the shape positions, not their number when updating a polygon.
  57045. */
  57046. MeshBuilder.CreatePolygon = function (name, options, scene) {
  57047. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57048. var shape = options.shape;
  57049. var holes = options.holes || [];
  57050. var depth = options.depth || 0;
  57051. var contours = [];
  57052. var hole = [];
  57053. for (var i = 0; i < shape.length; i++) {
  57054. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  57055. }
  57056. var epsilon = 0.00000001;
  57057. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  57058. contours.pop();
  57059. }
  57060. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  57061. for (var hNb = 0; hNb < holes.length; hNb++) {
  57062. hole = [];
  57063. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  57064. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  57065. }
  57066. polygonTriangulation.addHole(hole);
  57067. }
  57068. var polygon = polygonTriangulation.build(options.updatable, depth);
  57069. polygon._originalBuilderSideOrientation = options.sideOrientation;
  57070. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  57071. vertexData.applyToMesh(polygon, options.updatable);
  57072. return polygon;
  57073. };
  57074. ;
  57075. /**
  57076. * Creates an extruded polygon mesh, with depth in the Y direction.
  57077. * 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).
  57078. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  57079. */
  57080. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  57081. return MeshBuilder.CreatePolygon(name, options, scene);
  57082. };
  57083. ;
  57084. /**
  57085. * Creates a tube mesh.
  57086. * 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.
  57087. *
  57088. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  57089. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  57090. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  57091. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  57092. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  57093. * 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.
  57094. * It must return a radius value (positive float) :
  57095. * ```javascript
  57096. * var radiusFunction = function(i, distance) {
  57097. * // do things
  57098. * return radius; }
  57099. * ```
  57100. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  57101. * 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
  57102. * 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
  57103. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57104. * 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).
  57105. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57106. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57107. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57108. */
  57109. MeshBuilder.CreateTube = function (name, options, scene) {
  57110. var path = options.path;
  57111. var instance = options.instance;
  57112. var radius = 1.0;
  57113. if (instance) {
  57114. radius = instance.radius;
  57115. }
  57116. if (options.radius !== undefined) {
  57117. radius = options.radius;
  57118. }
  57119. ;
  57120. var tessellation = options.tessellation || 64 | 0;
  57121. var radiusFunction = options.radiusFunction || null;
  57122. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  57123. var invertUV = options.invertUV || false;
  57124. var updatable = options.updatable;
  57125. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57126. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  57127. // tube geometry
  57128. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  57129. var tangents = path3D.getTangents();
  57130. var normals = path3D.getNormals();
  57131. var distances = path3D.getDistances();
  57132. var pi2 = Math.PI * 2;
  57133. var step = pi2 / tessellation * arc;
  57134. var returnRadius = function () { return radius; };
  57135. var radiusFunctionFinal = radiusFunction || returnRadius;
  57136. var circlePath;
  57137. var rad;
  57138. var normal;
  57139. var rotated;
  57140. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  57141. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  57142. for (var i = 0; i < path.length; i++) {
  57143. rad = radiusFunctionFinal(i, distances[i]); // current radius
  57144. circlePath = Array(); // current circle array
  57145. normal = normals[i]; // current normal
  57146. for (var t = 0; t < tessellation; t++) {
  57147. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  57148. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  57149. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  57150. rotated.scaleInPlace(rad).addInPlace(path[i]);
  57151. circlePath[t] = rotated;
  57152. }
  57153. circlePaths[index] = circlePath;
  57154. index++;
  57155. }
  57156. // cap
  57157. var capPath = function (nbPoints, pathIndex) {
  57158. var pointCap = Array();
  57159. for (var i = 0; i < nbPoints; i++) {
  57160. pointCap.push(path[pathIndex]);
  57161. }
  57162. return pointCap;
  57163. };
  57164. switch (cap) {
  57165. case BABYLON.Mesh.NO_CAP:
  57166. break;
  57167. case BABYLON.Mesh.CAP_START:
  57168. circlePaths[0] = capPath(tessellation, 0);
  57169. circlePaths[1] = circlePaths[2].slice(0);
  57170. break;
  57171. case BABYLON.Mesh.CAP_END:
  57172. circlePaths[index] = circlePaths[index - 1].slice(0);
  57173. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  57174. break;
  57175. case BABYLON.Mesh.CAP_ALL:
  57176. circlePaths[0] = capPath(tessellation, 0);
  57177. circlePaths[1] = circlePaths[2].slice(0);
  57178. circlePaths[index] = circlePaths[index - 1].slice(0);
  57179. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  57180. break;
  57181. default:
  57182. break;
  57183. }
  57184. return circlePaths;
  57185. };
  57186. var path3D;
  57187. var pathArray;
  57188. if (instance) {
  57189. var arc = options.arc || instance.arc;
  57190. path3D = (instance.path3D).update(path);
  57191. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  57192. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  57193. instance.path3D = path3D;
  57194. instance.pathArray = pathArray;
  57195. instance.arc = arc;
  57196. instance.radius = radius;
  57197. return instance;
  57198. }
  57199. // tube creation
  57200. path3D = new BABYLON.Path3D(path);
  57201. var newPathArray = new Array();
  57202. cap = (cap < 0 || cap > 3) ? 0 : cap;
  57203. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  57204. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  57205. tube.pathArray = pathArray;
  57206. tube.path3D = path3D;
  57207. tube.tessellation = tessellation;
  57208. tube.cap = cap;
  57209. tube.arc = options.arc;
  57210. tube.radius = radius;
  57211. return tube;
  57212. };
  57213. /**
  57214. * Creates a polyhedron mesh.
  57215. *
  57216. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  57217. * 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
  57218. * to choose the wanted type.
  57219. * The parameter `size` (positive float, default 1) sets the polygon size.
  57220. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  57221. * 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`.
  57222. * 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
  57223. * 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)`).
  57224. * 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
  57225. * 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.
  57226. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57227. * 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).
  57228. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57229. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57230. */
  57231. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  57232. var polyhedron = new BABYLON.Mesh(name, scene);
  57233. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57234. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  57235. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  57236. vertexData.applyToMesh(polyhedron, options.updatable);
  57237. return polyhedron;
  57238. };
  57239. /**
  57240. * Creates a decal mesh.
  57241. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  57242. * 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.
  57243. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  57244. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  57245. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  57246. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  57247. */
  57248. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  57249. var indices = sourceMesh.getIndices();
  57250. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57251. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57252. var position = options.position || BABYLON.Vector3.Zero();
  57253. var normal = options.normal || BABYLON.Vector3.Up();
  57254. var size = options.size || BABYLON.Vector3.One();
  57255. var angle = options.angle || 0;
  57256. // Getting correct rotation
  57257. if (!normal) {
  57258. var target = new BABYLON.Vector3(0, 0, 1);
  57259. var camera = sourceMesh.getScene().activeCamera;
  57260. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  57261. normal = camera.globalPosition.subtract(cameraWorldTarget);
  57262. }
  57263. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  57264. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  57265. var pitch = Math.atan2(normal.y, len);
  57266. // Matrix
  57267. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  57268. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  57269. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  57270. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  57271. var vertexData = new BABYLON.VertexData();
  57272. vertexData.indices = [];
  57273. vertexData.positions = [];
  57274. vertexData.normals = [];
  57275. vertexData.uvs = [];
  57276. var currentVertexDataIndex = 0;
  57277. var extractDecalVector3 = function (indexId) {
  57278. var result = new BABYLON.PositionNormalVertex();
  57279. if (!indices || !positions || !normals) {
  57280. return result;
  57281. }
  57282. var vertexId = indices[indexId];
  57283. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  57284. // Send vector to decal local world
  57285. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  57286. // Get normal
  57287. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  57288. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  57289. return result;
  57290. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  57291. var clip = function (vertices, axis) {
  57292. if (vertices.length === 0) {
  57293. return vertices;
  57294. }
  57295. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  57296. var clipVertices = function (v0, v1) {
  57297. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  57298. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  57299. };
  57300. var result = new Array();
  57301. for (var index = 0; index < vertices.length; index += 3) {
  57302. var v1Out;
  57303. var v2Out;
  57304. var v3Out;
  57305. var total = 0;
  57306. var nV1 = null;
  57307. var nV2 = null;
  57308. var nV3 = null;
  57309. var nV4 = null;
  57310. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  57311. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  57312. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  57313. v1Out = d1 > 0;
  57314. v2Out = d2 > 0;
  57315. v3Out = d3 > 0;
  57316. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  57317. switch (total) {
  57318. case 0:
  57319. result.push(vertices[index]);
  57320. result.push(vertices[index + 1]);
  57321. result.push(vertices[index + 2]);
  57322. break;
  57323. case 1:
  57324. if (v1Out) {
  57325. nV1 = vertices[index + 1];
  57326. nV2 = vertices[index + 2];
  57327. nV3 = clipVertices(vertices[index], nV1);
  57328. nV4 = clipVertices(vertices[index], nV2);
  57329. }
  57330. if (v2Out) {
  57331. nV1 = vertices[index];
  57332. nV2 = vertices[index + 2];
  57333. nV3 = clipVertices(vertices[index + 1], nV1);
  57334. nV4 = clipVertices(vertices[index + 1], nV2);
  57335. result.push(nV3);
  57336. result.push(nV2.clone());
  57337. result.push(nV1.clone());
  57338. result.push(nV2.clone());
  57339. result.push(nV3.clone());
  57340. result.push(nV4);
  57341. break;
  57342. }
  57343. if (v3Out) {
  57344. nV1 = vertices[index];
  57345. nV2 = vertices[index + 1];
  57346. nV3 = clipVertices(vertices[index + 2], nV1);
  57347. nV4 = clipVertices(vertices[index + 2], nV2);
  57348. }
  57349. if (nV1 && nV2 && nV3 && nV4) {
  57350. result.push(nV1.clone());
  57351. result.push(nV2.clone());
  57352. result.push(nV3);
  57353. result.push(nV4);
  57354. result.push(nV3.clone());
  57355. result.push(nV2.clone());
  57356. }
  57357. break;
  57358. case 2:
  57359. if (!v1Out) {
  57360. nV1 = vertices[index].clone();
  57361. nV2 = clipVertices(nV1, vertices[index + 1]);
  57362. nV3 = clipVertices(nV1, vertices[index + 2]);
  57363. result.push(nV1);
  57364. result.push(nV2);
  57365. result.push(nV3);
  57366. }
  57367. if (!v2Out) {
  57368. nV1 = vertices[index + 1].clone();
  57369. nV2 = clipVertices(nV1, vertices[index + 2]);
  57370. nV3 = clipVertices(nV1, vertices[index]);
  57371. result.push(nV1);
  57372. result.push(nV2);
  57373. result.push(nV3);
  57374. }
  57375. if (!v3Out) {
  57376. nV1 = vertices[index + 2].clone();
  57377. nV2 = clipVertices(nV1, vertices[index]);
  57378. nV3 = clipVertices(nV1, vertices[index + 1]);
  57379. result.push(nV1);
  57380. result.push(nV2);
  57381. result.push(nV3);
  57382. }
  57383. break;
  57384. case 3:
  57385. break;
  57386. }
  57387. }
  57388. return result;
  57389. };
  57390. for (var index = 0; index < indices.length; index += 3) {
  57391. var faceVertices = new Array();
  57392. faceVertices.push(extractDecalVector3(index));
  57393. faceVertices.push(extractDecalVector3(index + 1));
  57394. faceVertices.push(extractDecalVector3(index + 2));
  57395. // Clip
  57396. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  57397. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  57398. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  57399. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  57400. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  57401. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  57402. if (faceVertices.length === 0) {
  57403. continue;
  57404. }
  57405. // Add UVs and get back to world
  57406. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  57407. var vertex = faceVertices[vIndex];
  57408. //TODO check for Int32Array | Uint32Array | Uint16Array
  57409. vertexData.indices.push(currentVertexDataIndex);
  57410. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  57411. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  57412. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  57413. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  57414. currentVertexDataIndex++;
  57415. }
  57416. }
  57417. // Return mesh
  57418. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  57419. vertexData.applyToMesh(decal);
  57420. decal.position = position.clone();
  57421. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  57422. return decal;
  57423. };
  57424. // Privates
  57425. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  57426. // extrusion geometry
  57427. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  57428. var tangents = path3D.getTangents();
  57429. var normals = path3D.getNormals();
  57430. var binormals = path3D.getBinormals();
  57431. var distances = path3D.getDistances();
  57432. var angle = 0;
  57433. var returnScale = function () { return scale !== null ? scale : 1; };
  57434. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  57435. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  57436. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  57437. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  57438. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  57439. for (var i = 0; i < curve.length; i++) {
  57440. var shapePath = new Array();
  57441. var angleStep = rotate(i, distances[i]);
  57442. var scaleRatio = scl(i, distances[i]);
  57443. for (var p = 0; p < shape.length; p++) {
  57444. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  57445. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  57446. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  57447. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  57448. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  57449. shapePath[p] = rotated;
  57450. }
  57451. shapePaths[index] = shapePath;
  57452. angle += angleStep;
  57453. index++;
  57454. }
  57455. // cap
  57456. var capPath = function (shapePath) {
  57457. var pointCap = Array();
  57458. var barycenter = BABYLON.Vector3.Zero();
  57459. var i;
  57460. for (i = 0; i < shapePath.length; i++) {
  57461. barycenter.addInPlace(shapePath[i]);
  57462. }
  57463. barycenter.scaleInPlace(1.0 / shapePath.length);
  57464. for (i = 0; i < shapePath.length; i++) {
  57465. pointCap.push(barycenter);
  57466. }
  57467. return pointCap;
  57468. };
  57469. switch (cap) {
  57470. case BABYLON.Mesh.NO_CAP:
  57471. break;
  57472. case BABYLON.Mesh.CAP_START:
  57473. shapePaths[0] = capPath(shapePaths[2]);
  57474. shapePaths[1] = shapePaths[2];
  57475. break;
  57476. case BABYLON.Mesh.CAP_END:
  57477. shapePaths[index] = shapePaths[index - 1];
  57478. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  57479. break;
  57480. case BABYLON.Mesh.CAP_ALL:
  57481. shapePaths[0] = capPath(shapePaths[2]);
  57482. shapePaths[1] = shapePaths[2];
  57483. shapePaths[index] = shapePaths[index - 1];
  57484. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  57485. break;
  57486. default:
  57487. break;
  57488. }
  57489. return shapePaths;
  57490. };
  57491. var path3D;
  57492. var pathArray;
  57493. if (instance) {
  57494. path3D = (instance.path3D).update(curve);
  57495. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  57496. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  57497. return instance;
  57498. }
  57499. // extruded shape creation
  57500. path3D = new BABYLON.Path3D(curve);
  57501. var newShapePaths = new Array();
  57502. cap = (cap < 0 || cap > 3) ? 0 : cap;
  57503. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  57504. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  57505. extrudedGeneric.pathArray = pathArray;
  57506. extrudedGeneric.path3D = path3D;
  57507. extrudedGeneric.cap = cap;
  57508. return extrudedGeneric;
  57509. };
  57510. return MeshBuilder;
  57511. }());
  57512. BABYLON.MeshBuilder = MeshBuilder;
  57513. })(BABYLON || (BABYLON = {}));
  57514. //# sourceMappingURL=babylon.meshBuilder.js.map
  57515. "use strict";
  57516. var BABYLON;
  57517. (function (BABYLON) {
  57518. /**
  57519. * Draco compression (https://google.github.io/draco/)
  57520. */
  57521. var DracoCompression = /** @class */ (function () {
  57522. /**
  57523. * Constructor
  57524. * @param numWorkers The number of workers for async operations
  57525. */
  57526. function DracoCompression(numWorkers) {
  57527. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  57528. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  57529. if (!workerBlobUrl || !Worker) {
  57530. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  57531. return;
  57532. }
  57533. var workers = new Array(numWorkers);
  57534. for (var i = 0; i < workers.length; i++) {
  57535. var worker = new Worker(workerBlobUrl);
  57536. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  57537. workers[i] = worker;
  57538. }
  57539. this._workerPool = new BABYLON.WorkerPool(workers);
  57540. }
  57541. /**
  57542. * Stop all async operations and release resources.
  57543. */
  57544. DracoCompression.prototype.dispose = function () {
  57545. this._workerPool.dispose();
  57546. delete this._workerPool;
  57547. };
  57548. /**
  57549. * Decode Draco compressed mesh data to vertex data.
  57550. * @param data The array buffer view for the Draco compression data
  57551. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  57552. * @returns A promise that resolves with the decoded vertex data
  57553. */
  57554. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  57555. var _this = this;
  57556. return new Promise(function (resolve, reject) {
  57557. _this._workerPool.push(function (worker, onComplete) {
  57558. var vertexData = new BABYLON.VertexData();
  57559. var onError = function (error) {
  57560. worker.removeEventListener("error", onError);
  57561. worker.removeEventListener("message", onMessage);
  57562. reject(error);
  57563. onComplete();
  57564. };
  57565. var onMessage = function (message) {
  57566. if (message.data === "done") {
  57567. worker.removeEventListener("error", onError);
  57568. worker.removeEventListener("message", onMessage);
  57569. resolve(vertexData);
  57570. onComplete();
  57571. }
  57572. else if (message.data.id === "indices") {
  57573. vertexData.indices = message.data.value;
  57574. }
  57575. else {
  57576. vertexData.set(message.data.value, message.data.id);
  57577. }
  57578. };
  57579. worker.addEventListener("error", onError);
  57580. worker.addEventListener("message", onMessage);
  57581. var dataCopy = new Uint8Array(data.byteLength);
  57582. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  57583. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  57584. });
  57585. });
  57586. };
  57587. /**
  57588. * The worker function that gets converted to a blob url to pass into a worker.
  57589. */
  57590. DracoCompression._Worker = function () {
  57591. // self is actually a DedicatedWorkerGlobalScope
  57592. var _self = self;
  57593. var decodeMesh = function (data, attributes) {
  57594. var dracoModule = new DracoDecoderModule();
  57595. var buffer = new dracoModule.DecoderBuffer();
  57596. buffer.Init(data, data.byteLength);
  57597. var decoder = new dracoModule.Decoder();
  57598. var geometry;
  57599. var status;
  57600. try {
  57601. var type = decoder.GetEncodedGeometryType(buffer);
  57602. switch (type) {
  57603. case dracoModule.TRIANGULAR_MESH:
  57604. geometry = new dracoModule.Mesh();
  57605. status = decoder.DecodeBufferToMesh(buffer, geometry);
  57606. break;
  57607. case dracoModule.POINT_CLOUD:
  57608. geometry = new dracoModule.PointCloud();
  57609. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  57610. break;
  57611. default:
  57612. throw new Error("Invalid geometry type " + type);
  57613. }
  57614. if (!status.ok() || !geometry.ptr) {
  57615. throw new Error(status.error_msg());
  57616. }
  57617. var numPoints = geometry.num_points();
  57618. if (type === dracoModule.TRIANGULAR_MESH) {
  57619. var numFaces = geometry.num_faces();
  57620. var faceIndices = new dracoModule.DracoInt32Array();
  57621. try {
  57622. var indices = new Uint32Array(numFaces * 3);
  57623. for (var i = 0; i < numFaces; i++) {
  57624. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  57625. var offset = i * 3;
  57626. indices[offset + 0] = faceIndices.GetValue(0);
  57627. indices[offset + 1] = faceIndices.GetValue(1);
  57628. indices[offset + 2] = faceIndices.GetValue(2);
  57629. }
  57630. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  57631. }
  57632. finally {
  57633. dracoModule.destroy(faceIndices);
  57634. }
  57635. }
  57636. for (var kind in attributes) {
  57637. var uniqueId = attributes[kind];
  57638. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  57639. var dracoData = new dracoModule.DracoFloat32Array();
  57640. try {
  57641. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  57642. var babylonData = new Float32Array(numPoints * attribute.num_components());
  57643. for (var i = 0; i < babylonData.length; i++) {
  57644. babylonData[i] = dracoData.GetValue(i);
  57645. }
  57646. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  57647. }
  57648. finally {
  57649. dracoModule.destroy(dracoData);
  57650. }
  57651. }
  57652. }
  57653. finally {
  57654. if (geometry) {
  57655. dracoModule.destroy(geometry);
  57656. }
  57657. dracoModule.destroy(decoder);
  57658. dracoModule.destroy(buffer);
  57659. }
  57660. _self.postMessage("done");
  57661. };
  57662. _self.onmessage = function (event) {
  57663. switch (event.data.id) {
  57664. case "initDecoder": {
  57665. importScripts(event.data.url);
  57666. break;
  57667. }
  57668. case "decodeMesh": {
  57669. decodeMesh(event.data.data, event.data.attributes);
  57670. break;
  57671. }
  57672. }
  57673. };
  57674. };
  57675. DracoCompression._GetDefaultDecoderUrl = function () {
  57676. if (!BABYLON.Tools.IsWindowObjectExist) {
  57677. return null;
  57678. }
  57679. for (var i = 0; i < document.scripts.length; i++) {
  57680. if (document.scripts[i].type === "text/x-draco-decoder") {
  57681. return document.scripts[i].src;
  57682. }
  57683. }
  57684. return null;
  57685. };
  57686. /**
  57687. * Gets the url to the draco decoder if available.
  57688. */
  57689. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  57690. return DracoCompression;
  57691. }());
  57692. BABYLON.DracoCompression = DracoCompression;
  57693. })(BABYLON || (BABYLON = {}));
  57694. //# sourceMappingURL=babylon.dracoCompression.js.map
  57695. "use strict";
  57696. var BABYLON;
  57697. (function (BABYLON) {
  57698. var AudioEngine = /** @class */ (function () {
  57699. function AudioEngine() {
  57700. this._audioContext = null;
  57701. this._audioContextInitialized = false;
  57702. this.canUseWebAudio = false;
  57703. this.WarnedWebAudioUnsupported = false;
  57704. this.unlocked = false;
  57705. this.isMP3supported = false;
  57706. this.isOGGsupported = false;
  57707. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  57708. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  57709. this.canUseWebAudio = true;
  57710. }
  57711. var audioElem = document.createElement('audio');
  57712. try {
  57713. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  57714. this.isMP3supported = true;
  57715. }
  57716. }
  57717. catch (e) {
  57718. // protect error during capability check.
  57719. }
  57720. try {
  57721. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  57722. this.isOGGsupported = true;
  57723. }
  57724. }
  57725. catch (e) {
  57726. // protect error during capability check.
  57727. }
  57728. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  57729. this._unlockiOSaudio();
  57730. }
  57731. else {
  57732. this.unlocked = true;
  57733. }
  57734. }
  57735. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  57736. get: function () {
  57737. if (!this._audioContextInitialized) {
  57738. this._initializeAudioContext();
  57739. }
  57740. return this._audioContext;
  57741. },
  57742. enumerable: true,
  57743. configurable: true
  57744. });
  57745. AudioEngine.prototype._unlockiOSaudio = function () {
  57746. var _this = this;
  57747. var unlockaudio = function () {
  57748. if (!_this.audioContext) {
  57749. return;
  57750. }
  57751. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  57752. var source = _this.audioContext.createBufferSource();
  57753. source.buffer = buffer;
  57754. source.connect(_this.audioContext.destination);
  57755. source.start(0);
  57756. setTimeout(function () {
  57757. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  57758. _this.unlocked = true;
  57759. window.removeEventListener('touchend', unlockaudio, false);
  57760. if (_this.onAudioUnlocked) {
  57761. _this.onAudioUnlocked();
  57762. }
  57763. }
  57764. }, 0);
  57765. };
  57766. window.addEventListener('touchend', unlockaudio, false);
  57767. };
  57768. AudioEngine.prototype._initializeAudioContext = function () {
  57769. try {
  57770. if (this.canUseWebAudio) {
  57771. this._audioContext = new AudioContext();
  57772. // create a global volume gain node
  57773. this.masterGain = this._audioContext.createGain();
  57774. this.masterGain.gain.value = 1;
  57775. this.masterGain.connect(this._audioContext.destination);
  57776. this._audioContextInitialized = true;
  57777. }
  57778. }
  57779. catch (e) {
  57780. this.canUseWebAudio = false;
  57781. BABYLON.Tools.Error("Web Audio: " + e.message);
  57782. }
  57783. };
  57784. AudioEngine.prototype.dispose = function () {
  57785. if (this.canUseWebAudio && this._audioContextInitialized) {
  57786. if (this._connectedAnalyser && this._audioContext) {
  57787. this._connectedAnalyser.stopDebugCanvas();
  57788. this._connectedAnalyser.dispose();
  57789. this.masterGain.disconnect();
  57790. this.masterGain.connect(this._audioContext.destination);
  57791. this._connectedAnalyser = null;
  57792. }
  57793. this.masterGain.gain.value = 1;
  57794. }
  57795. this.WarnedWebAudioUnsupported = false;
  57796. };
  57797. AudioEngine.prototype.getGlobalVolume = function () {
  57798. if (this.canUseWebAudio && this._audioContextInitialized) {
  57799. return this.masterGain.gain.value;
  57800. }
  57801. else {
  57802. return -1;
  57803. }
  57804. };
  57805. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  57806. if (this.canUseWebAudio && this._audioContextInitialized) {
  57807. this.masterGain.gain.value = newVolume;
  57808. }
  57809. };
  57810. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  57811. if (this._connectedAnalyser) {
  57812. this._connectedAnalyser.stopDebugCanvas();
  57813. }
  57814. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  57815. this._connectedAnalyser = analyser;
  57816. this.masterGain.disconnect();
  57817. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  57818. }
  57819. };
  57820. return AudioEngine;
  57821. }());
  57822. BABYLON.AudioEngine = AudioEngine;
  57823. })(BABYLON || (BABYLON = {}));
  57824. //# sourceMappingURL=babylon.audioEngine.js.map
  57825. "use strict";
  57826. var BABYLON;
  57827. (function (BABYLON) {
  57828. var Sound = /** @class */ (function () {
  57829. /**
  57830. * Create a sound and attach it to a scene
  57831. * @param name Name of your sound
  57832. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  57833. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  57834. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  57835. */
  57836. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  57837. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  57838. var _this = this;
  57839. this.autoplay = false;
  57840. this.loop = false;
  57841. this.useCustomAttenuation = false;
  57842. this.spatialSound = false;
  57843. this.refDistance = 1;
  57844. this.rolloffFactor = 1;
  57845. this.maxDistance = 100;
  57846. this.distanceModel = "linear";
  57847. this._panningModel = "equalpower";
  57848. this._playbackRate = 1;
  57849. this._streaming = false;
  57850. this._startTime = 0;
  57851. this._startOffset = 0;
  57852. this._position = BABYLON.Vector3.Zero();
  57853. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  57854. this._volume = 1;
  57855. this._isReadyToPlay = false;
  57856. this.isPlaying = false;
  57857. this.isPaused = false;
  57858. this._isDirectional = false;
  57859. // Used if you'd like to create a directional sound.
  57860. // If not set, the sound will be omnidirectional
  57861. this._coneInnerAngle = 360;
  57862. this._coneOuterAngle = 360;
  57863. this._coneOuterGain = 0;
  57864. this._isOutputConnected = false;
  57865. this._urlType = "Unknown";
  57866. this.name = name;
  57867. this._scene = scene;
  57868. this._readyToPlayCallback = readyToPlayCallback;
  57869. // Default custom attenuation function is a linear attenuation
  57870. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  57871. if (currentDistance < maxDistance) {
  57872. return currentVolume * (1 - currentDistance / maxDistance);
  57873. }
  57874. else {
  57875. return 0;
  57876. }
  57877. };
  57878. if (options) {
  57879. this.autoplay = options.autoplay || false;
  57880. this.loop = options.loop || false;
  57881. // if volume === 0, we need another way to check this option
  57882. if (options.volume !== undefined) {
  57883. this._volume = options.volume;
  57884. }
  57885. this.spatialSound = options.spatialSound || false;
  57886. this.maxDistance = options.maxDistance || 100;
  57887. this.useCustomAttenuation = options.useCustomAttenuation || false;
  57888. this.rolloffFactor = options.rolloffFactor || 1;
  57889. this.refDistance = options.refDistance || 1;
  57890. this.distanceModel = options.distanceModel || "linear";
  57891. this._playbackRate = options.playbackRate || 1;
  57892. this._streaming = options.streaming || false;
  57893. }
  57894. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57895. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  57896. this._soundGain.gain.value = this._volume;
  57897. this._inputAudioNode = this._soundGain;
  57898. this._ouputAudioNode = this._soundGain;
  57899. if (this.spatialSound) {
  57900. this._createSpatialParameters();
  57901. }
  57902. this._scene.mainSoundTrack.AddSound(this);
  57903. var validParameter = true;
  57904. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  57905. if (urlOrArrayBuffer) {
  57906. if (typeof (urlOrArrayBuffer) === "string")
  57907. this._urlType = "String";
  57908. if (Array.isArray(urlOrArrayBuffer))
  57909. this._urlType = "Array";
  57910. if (urlOrArrayBuffer instanceof ArrayBuffer)
  57911. this._urlType = "ArrayBuffer";
  57912. var urls = [];
  57913. var codecSupportedFound = false;
  57914. switch (this._urlType) {
  57915. case "ArrayBuffer":
  57916. if (urlOrArrayBuffer.byteLength > 0) {
  57917. codecSupportedFound = true;
  57918. this._soundLoaded(urlOrArrayBuffer);
  57919. }
  57920. break;
  57921. case "String":
  57922. urls.push(urlOrArrayBuffer);
  57923. case "Array":
  57924. if (urls.length === 0)
  57925. urls = urlOrArrayBuffer;
  57926. // If we found a supported format, we load it immediately and stop the loop
  57927. for (var i = 0; i < urls.length; i++) {
  57928. var url = urls[i];
  57929. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  57930. codecSupportedFound = true;
  57931. }
  57932. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  57933. codecSupportedFound = true;
  57934. }
  57935. if (url.indexOf(".wav", url.length - 4) !== -1) {
  57936. codecSupportedFound = true;
  57937. }
  57938. if (url.indexOf("blob:") !== -1) {
  57939. codecSupportedFound = true;
  57940. }
  57941. if (codecSupportedFound) {
  57942. // Loading sound using XHR2
  57943. if (!this._streaming) {
  57944. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  57945. }
  57946. else {
  57947. this._htmlAudioElement = new Audio(url);
  57948. this._htmlAudioElement.controls = false;
  57949. this._htmlAudioElement.loop = this.loop;
  57950. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  57951. this._htmlAudioElement.preload = "auto";
  57952. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  57953. _this._isReadyToPlay = true;
  57954. if (_this.autoplay) {
  57955. _this.play();
  57956. }
  57957. if (_this._readyToPlayCallback) {
  57958. _this._readyToPlayCallback();
  57959. }
  57960. });
  57961. document.body.appendChild(this._htmlAudioElement);
  57962. }
  57963. break;
  57964. }
  57965. }
  57966. break;
  57967. default:
  57968. validParameter = false;
  57969. break;
  57970. }
  57971. if (!validParameter) {
  57972. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  57973. }
  57974. else {
  57975. if (!codecSupportedFound) {
  57976. this._isReadyToPlay = true;
  57977. // Simulating a ready to play event to avoid breaking code path
  57978. if (this._readyToPlayCallback) {
  57979. window.setTimeout(function () {
  57980. if (_this._readyToPlayCallback) {
  57981. _this._readyToPlayCallback();
  57982. }
  57983. }, 1000);
  57984. }
  57985. }
  57986. }
  57987. }
  57988. }
  57989. else {
  57990. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  57991. this._scene.mainSoundTrack.AddSound(this);
  57992. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  57993. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  57994. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  57995. }
  57996. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  57997. if (this._readyToPlayCallback) {
  57998. window.setTimeout(function () {
  57999. if (_this._readyToPlayCallback) {
  58000. _this._readyToPlayCallback();
  58001. }
  58002. }, 1000);
  58003. }
  58004. }
  58005. }
  58006. Sound.prototype.dispose = function () {
  58007. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  58008. if (this.isPlaying) {
  58009. this.stop();
  58010. }
  58011. this._isReadyToPlay = false;
  58012. if (this.soundTrackId === -1) {
  58013. this._scene.mainSoundTrack.RemoveSound(this);
  58014. }
  58015. else {
  58016. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  58017. }
  58018. if (this._soundGain) {
  58019. this._soundGain.disconnect();
  58020. this._soundGain = null;
  58021. }
  58022. if (this._soundPanner) {
  58023. this._soundPanner.disconnect();
  58024. this._soundPanner = null;
  58025. }
  58026. if (this._soundSource) {
  58027. this._soundSource.disconnect();
  58028. this._soundSource = null;
  58029. }
  58030. this._audioBuffer = null;
  58031. if (this._htmlAudioElement) {
  58032. this._htmlAudioElement.pause();
  58033. this._htmlAudioElement.src = "";
  58034. document.body.removeChild(this._htmlAudioElement);
  58035. }
  58036. if (this._connectedMesh && this._registerFunc) {
  58037. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58038. this._connectedMesh = null;
  58039. }
  58040. }
  58041. };
  58042. Sound.prototype.isReady = function () {
  58043. return this._isReadyToPlay;
  58044. };
  58045. Sound.prototype._soundLoaded = function (audioData) {
  58046. var _this = this;
  58047. if (!BABYLON.Engine.audioEngine.audioContext) {
  58048. return;
  58049. }
  58050. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  58051. _this._audioBuffer = buffer;
  58052. _this._isReadyToPlay = true;
  58053. if (_this.autoplay) {
  58054. _this.play();
  58055. }
  58056. if (_this._readyToPlayCallback) {
  58057. _this._readyToPlayCallback();
  58058. }
  58059. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  58060. };
  58061. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  58062. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58063. this._audioBuffer = audioBuffer;
  58064. this._isReadyToPlay = true;
  58065. }
  58066. };
  58067. Sound.prototype.updateOptions = function (options) {
  58068. if (options) {
  58069. this.loop = options.loop || this.loop;
  58070. this.maxDistance = options.maxDistance || this.maxDistance;
  58071. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  58072. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  58073. this.refDistance = options.refDistance || this.refDistance;
  58074. this.distanceModel = options.distanceModel || this.distanceModel;
  58075. this._playbackRate = options.playbackRate || this._playbackRate;
  58076. this._updateSpatialParameters();
  58077. if (this.isPlaying) {
  58078. if (this._streaming) {
  58079. this._htmlAudioElement.playbackRate = this._playbackRate;
  58080. }
  58081. else {
  58082. if (this._soundSource) {
  58083. this._soundSource.playbackRate.value = this._playbackRate;
  58084. }
  58085. }
  58086. }
  58087. }
  58088. };
  58089. Sound.prototype._createSpatialParameters = function () {
  58090. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58091. if (this._scene.headphone) {
  58092. this._panningModel = "HRTF";
  58093. }
  58094. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  58095. this._updateSpatialParameters();
  58096. this._soundPanner.connect(this._ouputAudioNode);
  58097. this._inputAudioNode = this._soundPanner;
  58098. }
  58099. };
  58100. Sound.prototype._updateSpatialParameters = function () {
  58101. if (this.spatialSound && this._soundPanner) {
  58102. if (this.useCustomAttenuation) {
  58103. // Tricks to disable in a way embedded Web Audio attenuation
  58104. this._soundPanner.distanceModel = "linear";
  58105. this._soundPanner.maxDistance = Number.MAX_VALUE;
  58106. this._soundPanner.refDistance = 1;
  58107. this._soundPanner.rolloffFactor = 1;
  58108. this._soundPanner.panningModel = this._panningModel;
  58109. }
  58110. else {
  58111. this._soundPanner.distanceModel = this.distanceModel;
  58112. this._soundPanner.maxDistance = this.maxDistance;
  58113. this._soundPanner.refDistance = this.refDistance;
  58114. this._soundPanner.rolloffFactor = this.rolloffFactor;
  58115. this._soundPanner.panningModel = this._panningModel;
  58116. }
  58117. }
  58118. };
  58119. Sound.prototype.switchPanningModelToHRTF = function () {
  58120. this._panningModel = "HRTF";
  58121. this._switchPanningModel();
  58122. };
  58123. Sound.prototype.switchPanningModelToEqualPower = function () {
  58124. this._panningModel = "equalpower";
  58125. this._switchPanningModel();
  58126. };
  58127. Sound.prototype._switchPanningModel = function () {
  58128. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  58129. this._soundPanner.panningModel = this._panningModel;
  58130. }
  58131. };
  58132. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  58133. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58134. if (this._isOutputConnected) {
  58135. this._ouputAudioNode.disconnect();
  58136. }
  58137. this._ouputAudioNode.connect(soundTrackAudioNode);
  58138. this._isOutputConnected = true;
  58139. }
  58140. };
  58141. /**
  58142. * Transform this sound into a directional source
  58143. * @param coneInnerAngle Size of the inner cone in degree
  58144. * @param coneOuterAngle Size of the outer cone in degree
  58145. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  58146. */
  58147. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  58148. if (coneOuterAngle < coneInnerAngle) {
  58149. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  58150. return;
  58151. }
  58152. this._coneInnerAngle = coneInnerAngle;
  58153. this._coneOuterAngle = coneOuterAngle;
  58154. this._coneOuterGain = coneOuterGain;
  58155. this._isDirectional = true;
  58156. if (this.isPlaying && this.loop) {
  58157. this.stop();
  58158. this.play();
  58159. }
  58160. };
  58161. Sound.prototype.setPosition = function (newPosition) {
  58162. this._position = newPosition;
  58163. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  58164. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  58165. }
  58166. };
  58167. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  58168. this._localDirection = newLocalDirection;
  58169. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  58170. this._updateDirection();
  58171. }
  58172. };
  58173. Sound.prototype._updateDirection = function () {
  58174. if (!this._connectedMesh || !this._soundPanner) {
  58175. return;
  58176. }
  58177. var mat = this._connectedMesh.getWorldMatrix();
  58178. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  58179. direction.normalize();
  58180. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  58181. };
  58182. Sound.prototype.updateDistanceFromListener = function () {
  58183. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  58184. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  58185. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  58186. }
  58187. };
  58188. Sound.prototype.setAttenuationFunction = function (callback) {
  58189. this._customAttenuationFunction = callback;
  58190. };
  58191. /**
  58192. * Play the sound
  58193. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  58194. * @param offset (optional) Start the sound setting it at a specific time
  58195. */
  58196. Sound.prototype.play = function (time, offset) {
  58197. var _this = this;
  58198. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  58199. try {
  58200. if (this._startOffset < 0) {
  58201. time = -this._startOffset;
  58202. this._startOffset = 0;
  58203. }
  58204. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  58205. if (!this._soundSource || !this._streamingSource) {
  58206. if (this.spatialSound && this._soundPanner) {
  58207. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  58208. if (this._isDirectional) {
  58209. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  58210. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  58211. this._soundPanner.coneOuterGain = this._coneOuterGain;
  58212. if (this._connectedMesh) {
  58213. this._updateDirection();
  58214. }
  58215. else {
  58216. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  58217. }
  58218. }
  58219. }
  58220. }
  58221. if (this._streaming) {
  58222. if (!this._streamingSource) {
  58223. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  58224. this._htmlAudioElement.onended = function () { _this._onended(); };
  58225. this._htmlAudioElement.playbackRate = this._playbackRate;
  58226. }
  58227. this._streamingSource.disconnect();
  58228. this._streamingSource.connect(this._inputAudioNode);
  58229. this._htmlAudioElement.play();
  58230. }
  58231. else {
  58232. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  58233. this._soundSource.buffer = this._audioBuffer;
  58234. this._soundSource.connect(this._inputAudioNode);
  58235. this._soundSource.loop = this.loop;
  58236. this._soundSource.playbackRate.value = this._playbackRate;
  58237. this._soundSource.onended = function () { _this._onended(); };
  58238. if (this._soundSource.buffer) {
  58239. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  58240. }
  58241. }
  58242. this._startTime = startTime;
  58243. this.isPlaying = true;
  58244. this.isPaused = false;
  58245. }
  58246. catch (ex) {
  58247. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  58248. }
  58249. }
  58250. };
  58251. Sound.prototype._onended = function () {
  58252. this.isPlaying = false;
  58253. if (this.onended) {
  58254. this.onended();
  58255. }
  58256. };
  58257. /**
  58258. * Stop the sound
  58259. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  58260. */
  58261. Sound.prototype.stop = function (time) {
  58262. if (this.isPlaying) {
  58263. if (this._streaming) {
  58264. this._htmlAudioElement.pause();
  58265. // Test needed for Firefox or it will generate an Invalid State Error
  58266. if (this._htmlAudioElement.currentTime > 0) {
  58267. this._htmlAudioElement.currentTime = 0;
  58268. }
  58269. }
  58270. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  58271. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  58272. this._soundSource.stop(stopTime);
  58273. this._soundSource.onended = function () { };
  58274. if (!this.isPaused) {
  58275. this._startOffset = 0;
  58276. }
  58277. }
  58278. this.isPlaying = false;
  58279. }
  58280. };
  58281. Sound.prototype.pause = function () {
  58282. if (this.isPlaying) {
  58283. this.isPaused = true;
  58284. if (this._streaming) {
  58285. this._htmlAudioElement.pause();
  58286. }
  58287. else if (BABYLON.Engine.audioEngine.audioContext) {
  58288. this.stop(0);
  58289. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  58290. }
  58291. }
  58292. };
  58293. Sound.prototype.setVolume = function (newVolume, time) {
  58294. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  58295. if (time && BABYLON.Engine.audioEngine.audioContext) {
  58296. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  58297. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  58298. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  58299. }
  58300. else {
  58301. this._soundGain.gain.value = newVolume;
  58302. }
  58303. }
  58304. this._volume = newVolume;
  58305. };
  58306. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  58307. this._playbackRate = newPlaybackRate;
  58308. if (this.isPlaying) {
  58309. if (this._streaming) {
  58310. this._htmlAudioElement.playbackRate = this._playbackRate;
  58311. }
  58312. else if (this._soundSource) {
  58313. this._soundSource.playbackRate.value = this._playbackRate;
  58314. }
  58315. }
  58316. };
  58317. Sound.prototype.getVolume = function () {
  58318. return this._volume;
  58319. };
  58320. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  58321. var _this = this;
  58322. if (this._connectedMesh && this._registerFunc) {
  58323. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58324. this._registerFunc = null;
  58325. }
  58326. this._connectedMesh = meshToConnectTo;
  58327. if (!this.spatialSound) {
  58328. this.spatialSound = true;
  58329. this._createSpatialParameters();
  58330. if (this.isPlaying && this.loop) {
  58331. this.stop();
  58332. this.play();
  58333. }
  58334. }
  58335. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  58336. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  58337. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  58338. };
  58339. Sound.prototype.detachFromMesh = function () {
  58340. if (this._connectedMesh && this._registerFunc) {
  58341. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58342. this._registerFunc = null;
  58343. this._connectedMesh = null;
  58344. }
  58345. };
  58346. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  58347. if (!node.getBoundingInfo) {
  58348. return;
  58349. }
  58350. var mesh = node;
  58351. var boundingInfo = mesh.getBoundingInfo();
  58352. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  58353. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  58354. this._updateDirection();
  58355. }
  58356. };
  58357. Sound.prototype.clone = function () {
  58358. var _this = this;
  58359. if (!this._streaming) {
  58360. var setBufferAndRun = function () {
  58361. if (_this._isReadyToPlay) {
  58362. clonedSound._audioBuffer = _this.getAudioBuffer();
  58363. clonedSound._isReadyToPlay = true;
  58364. if (clonedSound.autoplay) {
  58365. clonedSound.play();
  58366. }
  58367. }
  58368. else {
  58369. window.setTimeout(setBufferAndRun, 300);
  58370. }
  58371. };
  58372. var currentOptions = {
  58373. autoplay: this.autoplay, loop: this.loop,
  58374. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  58375. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  58376. refDistance: this.refDistance, distanceModel: this.distanceModel
  58377. };
  58378. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  58379. if (this.useCustomAttenuation) {
  58380. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  58381. }
  58382. clonedSound.setPosition(this._position);
  58383. clonedSound.setPlaybackRate(this._playbackRate);
  58384. setBufferAndRun();
  58385. return clonedSound;
  58386. }
  58387. else {
  58388. return null;
  58389. }
  58390. };
  58391. Sound.prototype.getAudioBuffer = function () {
  58392. return this._audioBuffer;
  58393. };
  58394. Sound.prototype.serialize = function () {
  58395. var serializationObject = {
  58396. name: this.name,
  58397. url: this.name,
  58398. autoplay: this.autoplay,
  58399. loop: this.loop,
  58400. volume: this._volume,
  58401. spatialSound: this.spatialSound,
  58402. maxDistance: this.maxDistance,
  58403. rolloffFactor: this.rolloffFactor,
  58404. refDistance: this.refDistance,
  58405. distanceModel: this.distanceModel,
  58406. playbackRate: this._playbackRate,
  58407. panningModel: this._panningModel,
  58408. soundTrackId: this.soundTrackId
  58409. };
  58410. if (this.spatialSound) {
  58411. if (this._connectedMesh)
  58412. serializationObject.connectedMeshId = this._connectedMesh.id;
  58413. serializationObject.position = this._position.asArray();
  58414. serializationObject.refDistance = this.refDistance;
  58415. serializationObject.distanceModel = this.distanceModel;
  58416. serializationObject.isDirectional = this._isDirectional;
  58417. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  58418. serializationObject.coneInnerAngle = this._coneInnerAngle;
  58419. serializationObject.coneOuterAngle = this._coneOuterAngle;
  58420. serializationObject.coneOuterGain = this._coneOuterGain;
  58421. }
  58422. return serializationObject;
  58423. };
  58424. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  58425. var soundName = parsedSound.name;
  58426. var soundUrl;
  58427. if (parsedSound.url) {
  58428. soundUrl = rootUrl + parsedSound.url;
  58429. }
  58430. else {
  58431. soundUrl = rootUrl + soundName;
  58432. }
  58433. var options = {
  58434. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  58435. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  58436. rolloffFactor: parsedSound.rolloffFactor,
  58437. refDistance: parsedSound.refDistance,
  58438. distanceModel: parsedSound.distanceModel,
  58439. playbackRate: parsedSound.playbackRate
  58440. };
  58441. var newSound;
  58442. if (!sourceSound) {
  58443. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  58444. scene._addPendingData(newSound);
  58445. }
  58446. else {
  58447. var setBufferAndRun = function () {
  58448. if (sourceSound._isReadyToPlay) {
  58449. newSound._audioBuffer = sourceSound.getAudioBuffer();
  58450. newSound._isReadyToPlay = true;
  58451. if (newSound.autoplay) {
  58452. newSound.play();
  58453. }
  58454. }
  58455. else {
  58456. window.setTimeout(setBufferAndRun, 300);
  58457. }
  58458. };
  58459. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  58460. setBufferAndRun();
  58461. }
  58462. if (parsedSound.position) {
  58463. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  58464. newSound.setPosition(soundPosition);
  58465. }
  58466. if (parsedSound.isDirectional) {
  58467. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  58468. if (parsedSound.localDirectionToMesh) {
  58469. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  58470. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  58471. }
  58472. }
  58473. if (parsedSound.connectedMeshId) {
  58474. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  58475. if (connectedMesh) {
  58476. newSound.attachToMesh(connectedMesh);
  58477. }
  58478. }
  58479. return newSound;
  58480. };
  58481. return Sound;
  58482. }());
  58483. BABYLON.Sound = Sound;
  58484. })(BABYLON || (BABYLON = {}));
  58485. //# sourceMappingURL=babylon.sound.js.map
  58486. "use strict";
  58487. var BABYLON;
  58488. (function (BABYLON) {
  58489. var SoundTrack = /** @class */ (function () {
  58490. function SoundTrack(scene, options) {
  58491. this.id = -1;
  58492. this._isMainTrack = false;
  58493. this._isInitialized = false;
  58494. this._scene = scene;
  58495. this.soundCollection = new Array();
  58496. this._options = options;
  58497. if (!this._isMainTrack) {
  58498. this._scene.soundTracks.push(this);
  58499. this.id = this._scene.soundTracks.length - 1;
  58500. }
  58501. }
  58502. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  58503. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58504. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  58505. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  58506. if (this._options) {
  58507. if (this._options.volume) {
  58508. this._outputAudioNode.gain.value = this._options.volume;
  58509. }
  58510. if (this._options.mainTrack) {
  58511. this._isMainTrack = this._options.mainTrack;
  58512. }
  58513. }
  58514. this._isInitialized = true;
  58515. }
  58516. };
  58517. SoundTrack.prototype.dispose = function () {
  58518. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  58519. if (this._connectedAnalyser) {
  58520. this._connectedAnalyser.stopDebugCanvas();
  58521. }
  58522. while (this.soundCollection.length) {
  58523. this.soundCollection[0].dispose();
  58524. }
  58525. if (this._outputAudioNode) {
  58526. this._outputAudioNode.disconnect();
  58527. }
  58528. this._outputAudioNode = null;
  58529. }
  58530. };
  58531. SoundTrack.prototype.AddSound = function (sound) {
  58532. if (!this._isInitialized) {
  58533. this._initializeSoundTrackAudioGraph();
  58534. }
  58535. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58536. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  58537. }
  58538. if (sound.soundTrackId) {
  58539. if (sound.soundTrackId === -1) {
  58540. this._scene.mainSoundTrack.RemoveSound(sound);
  58541. }
  58542. else {
  58543. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  58544. }
  58545. }
  58546. this.soundCollection.push(sound);
  58547. sound.soundTrackId = this.id;
  58548. };
  58549. SoundTrack.prototype.RemoveSound = function (sound) {
  58550. var index = this.soundCollection.indexOf(sound);
  58551. if (index !== -1) {
  58552. this.soundCollection.splice(index, 1);
  58553. }
  58554. };
  58555. SoundTrack.prototype.setVolume = function (newVolume) {
  58556. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58557. this._outputAudioNode.gain.value = newVolume;
  58558. }
  58559. };
  58560. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  58561. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58562. for (var i = 0; i < this.soundCollection.length; i++) {
  58563. this.soundCollection[i].switchPanningModelToHRTF();
  58564. }
  58565. }
  58566. };
  58567. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  58568. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58569. for (var i = 0; i < this.soundCollection.length; i++) {
  58570. this.soundCollection[i].switchPanningModelToEqualPower();
  58571. }
  58572. }
  58573. };
  58574. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  58575. if (this._connectedAnalyser) {
  58576. this._connectedAnalyser.stopDebugCanvas();
  58577. }
  58578. this._connectedAnalyser = analyser;
  58579. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58580. this._outputAudioNode.disconnect();
  58581. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  58582. }
  58583. };
  58584. return SoundTrack;
  58585. }());
  58586. BABYLON.SoundTrack = SoundTrack;
  58587. })(BABYLON || (BABYLON = {}));
  58588. //# sourceMappingURL=babylon.soundtrack.js.map
  58589. "use strict";
  58590. var BABYLON;
  58591. (function (BABYLON) {
  58592. var Analyser = /** @class */ (function () {
  58593. function Analyser(scene) {
  58594. this.SMOOTHING = 0.75;
  58595. this.FFT_SIZE = 512;
  58596. this.BARGRAPHAMPLITUDE = 256;
  58597. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  58598. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  58599. this._scene = scene;
  58600. this._audioEngine = BABYLON.Engine.audioEngine;
  58601. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  58602. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  58603. this._webAudioAnalyser.minDecibels = -140;
  58604. this._webAudioAnalyser.maxDecibels = 0;
  58605. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  58606. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  58607. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  58608. }
  58609. }
  58610. Analyser.prototype.getFrequencyBinCount = function () {
  58611. if (this._audioEngine.canUseWebAudio) {
  58612. return this._webAudioAnalyser.frequencyBinCount;
  58613. }
  58614. else {
  58615. return 0;
  58616. }
  58617. };
  58618. Analyser.prototype.getByteFrequencyData = function () {
  58619. if (this._audioEngine.canUseWebAudio) {
  58620. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58621. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58622. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  58623. }
  58624. return this._byteFreqs;
  58625. };
  58626. Analyser.prototype.getByteTimeDomainData = function () {
  58627. if (this._audioEngine.canUseWebAudio) {
  58628. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58629. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58630. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  58631. }
  58632. return this._byteTime;
  58633. };
  58634. Analyser.prototype.getFloatFrequencyData = function () {
  58635. if (this._audioEngine.canUseWebAudio) {
  58636. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58637. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58638. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  58639. }
  58640. return this._floatFreqs;
  58641. };
  58642. Analyser.prototype.drawDebugCanvas = function () {
  58643. var _this = this;
  58644. if (this._audioEngine.canUseWebAudio) {
  58645. if (!this._debugCanvas) {
  58646. this._debugCanvas = document.createElement("canvas");
  58647. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  58648. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  58649. this._debugCanvas.style.position = "absolute";
  58650. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  58651. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  58652. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  58653. document.body.appendChild(this._debugCanvas);
  58654. this._registerFunc = function () {
  58655. _this.drawDebugCanvas();
  58656. };
  58657. this._scene.registerBeforeRender(this._registerFunc);
  58658. }
  58659. if (this._registerFunc && this._debugCanvasContext) {
  58660. var workingArray = this.getByteFrequencyData();
  58661. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  58662. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  58663. // Draw the frequency domain chart.
  58664. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  58665. var value = workingArray[i];
  58666. var percent = value / this.BARGRAPHAMPLITUDE;
  58667. var height = this.DEBUGCANVASSIZE.height * percent;
  58668. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  58669. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  58670. var hue = i / this.getFrequencyBinCount() * 360;
  58671. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  58672. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  58673. }
  58674. }
  58675. }
  58676. };
  58677. Analyser.prototype.stopDebugCanvas = function () {
  58678. if (this._debugCanvas) {
  58679. if (this._registerFunc) {
  58680. this._scene.unregisterBeforeRender(this._registerFunc);
  58681. this._registerFunc = null;
  58682. }
  58683. document.body.removeChild(this._debugCanvas);
  58684. this._debugCanvas = null;
  58685. this._debugCanvasContext = null;
  58686. }
  58687. };
  58688. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  58689. if (this._audioEngine.canUseWebAudio) {
  58690. inputAudioNode.connect(this._webAudioAnalyser);
  58691. this._webAudioAnalyser.connect(outputAudioNode);
  58692. }
  58693. };
  58694. Analyser.prototype.dispose = function () {
  58695. if (this._audioEngine.canUseWebAudio) {
  58696. this._webAudioAnalyser.disconnect();
  58697. }
  58698. };
  58699. return Analyser;
  58700. }());
  58701. BABYLON.Analyser = Analyser;
  58702. })(BABYLON || (BABYLON = {}));
  58703. //# sourceMappingURL=babylon.analyser.js.map
  58704. "use strict";
  58705. var BABYLON;
  58706. (function (BABYLON) {
  58707. var CubeTexture = /** @class */ (function (_super) {
  58708. __extends(CubeTexture, _super);
  58709. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  58710. if (extensions === void 0) { extensions = null; }
  58711. if (noMipmap === void 0) { noMipmap = false; }
  58712. if (files === void 0) { files = null; }
  58713. if (onLoad === void 0) { onLoad = null; }
  58714. if (onError === void 0) { onError = null; }
  58715. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58716. if (prefiltered === void 0) { prefiltered = false; }
  58717. if (forcedExtension === void 0) { forcedExtension = null; }
  58718. var _this = _super.call(this, scene) || this;
  58719. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  58720. /**
  58721. * Gets or sets the center of the bounding box associated with the cube texture
  58722. * It must define where the camera used to render the texture was set
  58723. */
  58724. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58725. _this.name = rootUrl;
  58726. _this.url = rootUrl;
  58727. _this._noMipmap = noMipmap;
  58728. _this.hasAlpha = false;
  58729. _this._format = format;
  58730. _this._prefiltered = prefiltered;
  58731. _this.isCube = true;
  58732. _this._textureMatrix = BABYLON.Matrix.Identity();
  58733. if (prefiltered) {
  58734. _this.gammaSpace = false;
  58735. }
  58736. if (!rootUrl && !files) {
  58737. return _this;
  58738. }
  58739. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  58740. var lastDot = rootUrl.lastIndexOf(".");
  58741. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  58742. var isDDS = (extension === ".dds");
  58743. if (!files) {
  58744. if (!isDDS && !extensions) {
  58745. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  58746. }
  58747. files = [];
  58748. if (extensions) {
  58749. for (var index = 0; index < extensions.length; index++) {
  58750. files.push(rootUrl + extensions[index]);
  58751. }
  58752. }
  58753. }
  58754. _this._files = files;
  58755. if (!_this._texture) {
  58756. if (!scene.useDelayedTextureLoading) {
  58757. if (prefiltered) {
  58758. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  58759. }
  58760. else {
  58761. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  58762. }
  58763. }
  58764. else {
  58765. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  58766. }
  58767. }
  58768. else if (onLoad) {
  58769. if (_this._texture.isReady) {
  58770. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  58771. }
  58772. else {
  58773. _this._texture.onLoadedObservable.add(onLoad);
  58774. }
  58775. }
  58776. return _this;
  58777. }
  58778. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  58779. get: function () {
  58780. return this._boundingBoxSize;
  58781. },
  58782. /**
  58783. * Gets or sets the size of the bounding box associated with the cube texture
  58784. * When defined, the cubemap will switch to local mode
  58785. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58786. * @example https://www.babylonjs-playground.com/#RNASML
  58787. */
  58788. set: function (value) {
  58789. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58790. return;
  58791. }
  58792. this._boundingBoxSize = value;
  58793. var scene = this.getScene();
  58794. if (scene) {
  58795. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  58796. }
  58797. },
  58798. enumerable: true,
  58799. configurable: true
  58800. });
  58801. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  58802. var rootUrlKey = "";
  58803. files.forEach(function (url) { return rootUrlKey += url; });
  58804. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  58805. };
  58806. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  58807. if (forcedExtension === void 0) { forcedExtension = null; }
  58808. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  58809. };
  58810. // Methods
  58811. CubeTexture.prototype.delayLoad = function () {
  58812. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  58813. return;
  58814. }
  58815. var scene = this.getScene();
  58816. if (!scene) {
  58817. return;
  58818. }
  58819. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  58820. this._texture = this._getFromCache(this.url, this._noMipmap);
  58821. if (!this._texture) {
  58822. if (this._prefiltered) {
  58823. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  58824. }
  58825. else {
  58826. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  58827. }
  58828. }
  58829. };
  58830. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  58831. return this._textureMatrix;
  58832. };
  58833. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  58834. this._textureMatrix = value;
  58835. };
  58836. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  58837. var texture = BABYLON.SerializationHelper.Parse(function () {
  58838. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  58839. }, parsedTexture, scene);
  58840. // Local Cubemaps
  58841. if (parsedTexture.boundingBoxPosition) {
  58842. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  58843. }
  58844. if (parsedTexture.boundingBoxSize) {
  58845. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  58846. }
  58847. // Animations
  58848. if (parsedTexture.animations) {
  58849. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  58850. var parsedAnimation = parsedTexture.animations[animationIndex];
  58851. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58852. }
  58853. }
  58854. return texture;
  58855. };
  58856. CubeTexture.prototype.clone = function () {
  58857. var _this = this;
  58858. return BABYLON.SerializationHelper.Clone(function () {
  58859. var scene = _this.getScene();
  58860. if (!scene) {
  58861. return _this;
  58862. }
  58863. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  58864. }, this);
  58865. };
  58866. return CubeTexture;
  58867. }(BABYLON.BaseTexture));
  58868. BABYLON.CubeTexture = CubeTexture;
  58869. })(BABYLON || (BABYLON = {}));
  58870. //# sourceMappingURL=babylon.cubeTexture.js.map
  58871. "use strict";
  58872. var BABYLON;
  58873. (function (BABYLON) {
  58874. var RenderTargetTexture = /** @class */ (function (_super) {
  58875. __extends(RenderTargetTexture, _super);
  58876. /**
  58877. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  58878. * or used a shadow, depth texture...
  58879. * @param name The friendly name of the texture
  58880. * @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)
  58881. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  58882. * @param generateMipMaps True if mip maps need to be generated after render.
  58883. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  58884. * @param type The type of the buffer in the RTT (int, half float, float...)
  58885. * @param isCube True if a cube texture needs to be created
  58886. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  58887. * @param generateDepthBuffer True to generate a depth buffer
  58888. * @param generateStencilBuffer True to generate a stencil buffer
  58889. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  58890. */
  58891. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  58892. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  58893. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58894. if (isCube === void 0) { isCube = false; }
  58895. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58896. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58897. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  58898. if (isMulti === void 0) { isMulti = false; }
  58899. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  58900. _this.isCube = isCube;
  58901. /**
  58902. * Use this list to define the list of mesh you want to render.
  58903. */
  58904. _this.renderList = new Array();
  58905. _this.renderParticles = true;
  58906. _this.renderSprites = false;
  58907. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  58908. _this.ignoreCameraViewport = false;
  58909. // Events
  58910. /**
  58911. * An event triggered when the texture is unbind.
  58912. * @type {BABYLON.Observable}
  58913. */
  58914. _this.onBeforeBindObservable = new BABYLON.Observable();
  58915. /**
  58916. * An event triggered when the texture is unbind.
  58917. * @type {BABYLON.Observable}
  58918. */
  58919. _this.onAfterUnbindObservable = new BABYLON.Observable();
  58920. /**
  58921. * An event triggered before rendering the texture
  58922. * @type {BABYLON.Observable}
  58923. */
  58924. _this.onBeforeRenderObservable = new BABYLON.Observable();
  58925. /**
  58926. * An event triggered after rendering the texture
  58927. * @type {BABYLON.Observable}
  58928. */
  58929. _this.onAfterRenderObservable = new BABYLON.Observable();
  58930. /**
  58931. * An event triggered after the texture clear
  58932. * @type {BABYLON.Observable}
  58933. */
  58934. _this.onClearObservable = new BABYLON.Observable();
  58935. _this._currentRefreshId = -1;
  58936. _this._refreshRate = 1;
  58937. _this._samples = 1;
  58938. /**
  58939. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  58940. * It must define where the camera used to render the texture is set
  58941. */
  58942. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58943. scene = _this.getScene();
  58944. if (!scene) {
  58945. return _this;
  58946. }
  58947. _this._engine = scene.getEngine();
  58948. _this.name = name;
  58949. _this.isRenderTarget = true;
  58950. _this._initialSizeParameter = size;
  58951. _this._processSizeParameter(size);
  58952. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  58953. });
  58954. _this._generateMipMaps = generateMipMaps ? true : false;
  58955. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  58956. // Rendering groups
  58957. _this._renderingManager = new BABYLON.RenderingManager(scene);
  58958. if (isMulti) {
  58959. return _this;
  58960. }
  58961. _this._renderTargetOptions = {
  58962. generateMipMaps: generateMipMaps,
  58963. type: type,
  58964. samplingMode: samplingMode,
  58965. generateDepthBuffer: generateDepthBuffer,
  58966. generateStencilBuffer: generateStencilBuffer
  58967. };
  58968. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  58969. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58970. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58971. }
  58972. if (isCube) {
  58973. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  58974. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  58975. _this._textureMatrix = BABYLON.Matrix.Identity();
  58976. }
  58977. else {
  58978. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  58979. }
  58980. return _this;
  58981. }
  58982. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  58983. get: function () {
  58984. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  58985. },
  58986. enumerable: true,
  58987. configurable: true
  58988. });
  58989. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  58990. get: function () {
  58991. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  58992. },
  58993. enumerable: true,
  58994. configurable: true
  58995. });
  58996. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  58997. get: function () {
  58998. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  58999. },
  59000. enumerable: true,
  59001. configurable: true
  59002. });
  59003. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  59004. set: function (callback) {
  59005. if (this._onAfterUnbindObserver) {
  59006. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  59007. }
  59008. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  59009. },
  59010. enumerable: true,
  59011. configurable: true
  59012. });
  59013. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  59014. set: function (callback) {
  59015. if (this._onBeforeRenderObserver) {
  59016. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  59017. }
  59018. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  59019. },
  59020. enumerable: true,
  59021. configurable: true
  59022. });
  59023. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  59024. set: function (callback) {
  59025. if (this._onAfterRenderObserver) {
  59026. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  59027. }
  59028. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  59029. },
  59030. enumerable: true,
  59031. configurable: true
  59032. });
  59033. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  59034. set: function (callback) {
  59035. if (this._onClearObserver) {
  59036. this.onClearObservable.remove(this._onClearObserver);
  59037. }
  59038. this._onClearObserver = this.onClearObservable.add(callback);
  59039. },
  59040. enumerable: true,
  59041. configurable: true
  59042. });
  59043. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  59044. get: function () {
  59045. return this._renderTargetOptions;
  59046. },
  59047. enumerable: true,
  59048. configurable: true
  59049. });
  59050. RenderTargetTexture.prototype._onRatioRescale = function () {
  59051. if (this._sizeRatio) {
  59052. this.resize(this._initialSizeParameter);
  59053. }
  59054. };
  59055. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  59056. get: function () {
  59057. return this._boundingBoxSize;
  59058. },
  59059. /**
  59060. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  59061. * When defined, the cubemap will switch to local mode
  59062. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  59063. * @example https://www.babylonjs-playground.com/#RNASML
  59064. */
  59065. set: function (value) {
  59066. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  59067. return;
  59068. }
  59069. this._boundingBoxSize = value;
  59070. var scene = this.getScene();
  59071. if (scene) {
  59072. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  59073. }
  59074. },
  59075. enumerable: true,
  59076. configurable: true
  59077. });
  59078. /**
  59079. * Creates a depth stencil texture.
  59080. * This is only available in WebGL 2 or with the depth texture extension available.
  59081. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  59082. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  59083. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  59084. */
  59085. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  59086. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  59087. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  59088. if (generateStencil === void 0) { generateStencil = false; }
  59089. if (!this.getScene()) {
  59090. return;
  59091. }
  59092. var engine = this.getScene().getEngine();
  59093. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  59094. bilinearFiltering: bilinearFiltering,
  59095. comparisonFunction: comparisonFunction,
  59096. generateStencil: generateStencil,
  59097. isCube: this.isCube
  59098. });
  59099. engine.setFrameBufferDepthStencilTexture(this);
  59100. };
  59101. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  59102. if (size.ratio) {
  59103. this._sizeRatio = size.ratio;
  59104. this._size = {
  59105. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  59106. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  59107. };
  59108. }
  59109. else {
  59110. this._size = size;
  59111. }
  59112. };
  59113. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  59114. get: function () {
  59115. return this._samples;
  59116. },
  59117. set: function (value) {
  59118. if (this._samples === value) {
  59119. return;
  59120. }
  59121. var scene = this.getScene();
  59122. if (!scene) {
  59123. return;
  59124. }
  59125. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  59126. },
  59127. enumerable: true,
  59128. configurable: true
  59129. });
  59130. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  59131. this._currentRefreshId = -1;
  59132. };
  59133. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  59134. get: function () {
  59135. return this._refreshRate;
  59136. },
  59137. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  59138. set: function (value) {
  59139. this._refreshRate = value;
  59140. this.resetRefreshCounter();
  59141. },
  59142. enumerable: true,
  59143. configurable: true
  59144. });
  59145. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  59146. if (!this._postProcessManager) {
  59147. var scene = this.getScene();
  59148. if (!scene) {
  59149. return;
  59150. }
  59151. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  59152. this._postProcesses = new Array();
  59153. }
  59154. this._postProcesses.push(postProcess);
  59155. this._postProcesses[0].autoClear = false;
  59156. };
  59157. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  59158. if (!this._postProcesses) {
  59159. return;
  59160. }
  59161. if (dispose) {
  59162. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  59163. var postProcess = _a[_i];
  59164. postProcess.dispose();
  59165. }
  59166. }
  59167. this._postProcesses = [];
  59168. };
  59169. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  59170. if (!this._postProcesses) {
  59171. return;
  59172. }
  59173. var index = this._postProcesses.indexOf(postProcess);
  59174. if (index === -1) {
  59175. return;
  59176. }
  59177. this._postProcesses.splice(index, 1);
  59178. if (this._postProcesses.length > 0) {
  59179. this._postProcesses[0].autoClear = false;
  59180. }
  59181. };
  59182. RenderTargetTexture.prototype._shouldRender = function () {
  59183. if (this._currentRefreshId === -1) {
  59184. this._currentRefreshId = 1;
  59185. return true;
  59186. }
  59187. if (this.refreshRate === this._currentRefreshId) {
  59188. this._currentRefreshId = 1;
  59189. return true;
  59190. }
  59191. this._currentRefreshId++;
  59192. return false;
  59193. };
  59194. RenderTargetTexture.prototype.getRenderSize = function () {
  59195. if (this._size.width) {
  59196. return this._size.width;
  59197. }
  59198. return this._size;
  59199. };
  59200. RenderTargetTexture.prototype.getRenderWidth = function () {
  59201. if (this._size.width) {
  59202. return this._size.width;
  59203. }
  59204. return this._size;
  59205. };
  59206. RenderTargetTexture.prototype.getRenderHeight = function () {
  59207. if (this._size.width) {
  59208. return this._size.height;
  59209. }
  59210. return this._size;
  59211. };
  59212. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  59213. get: function () {
  59214. return true;
  59215. },
  59216. enumerable: true,
  59217. configurable: true
  59218. });
  59219. RenderTargetTexture.prototype.scale = function (ratio) {
  59220. var newSize = this.getRenderSize() * ratio;
  59221. this.resize(newSize);
  59222. };
  59223. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  59224. if (this.isCube) {
  59225. return this._textureMatrix;
  59226. }
  59227. return _super.prototype.getReflectionTextureMatrix.call(this);
  59228. };
  59229. RenderTargetTexture.prototype.resize = function (size) {
  59230. this.releaseInternalTexture();
  59231. var scene = this.getScene();
  59232. if (!scene) {
  59233. return;
  59234. }
  59235. this._processSizeParameter(size);
  59236. if (this.isCube) {
  59237. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  59238. }
  59239. else {
  59240. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  59241. }
  59242. };
  59243. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  59244. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  59245. if (dumpForDebug === void 0) { dumpForDebug = false; }
  59246. var scene = this.getScene();
  59247. if (!scene) {
  59248. return;
  59249. }
  59250. var engine = scene.getEngine();
  59251. if (this.useCameraPostProcesses !== undefined) {
  59252. useCameraPostProcess = this.useCameraPostProcesses;
  59253. }
  59254. if (this._waitingRenderList) {
  59255. this.renderList = [];
  59256. for (var index = 0; index < this._waitingRenderList.length; index++) {
  59257. var id = this._waitingRenderList[index];
  59258. var mesh_1 = scene.getMeshByID(id);
  59259. if (mesh_1) {
  59260. this.renderList.push(mesh_1);
  59261. }
  59262. }
  59263. delete this._waitingRenderList;
  59264. }
  59265. // Is predicate defined?
  59266. if (this.renderListPredicate) {
  59267. if (this.renderList) {
  59268. this.renderList.splice(0); // Clear previous renderList
  59269. }
  59270. else {
  59271. this.renderList = [];
  59272. }
  59273. var scene = this.getScene();
  59274. if (!scene) {
  59275. return;
  59276. }
  59277. var sceneMeshes = scene.meshes;
  59278. for (var index = 0; index < sceneMeshes.length; index++) {
  59279. var mesh = sceneMeshes[index];
  59280. if (this.renderListPredicate(mesh)) {
  59281. this.renderList.push(mesh);
  59282. }
  59283. }
  59284. }
  59285. this.onBeforeBindObservable.notifyObservers(this);
  59286. // Set custom projection.
  59287. // Needs to be before binding to prevent changing the aspect ratio.
  59288. var camera;
  59289. if (this.activeCamera) {
  59290. camera = this.activeCamera;
  59291. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  59292. if (this.activeCamera !== scene.activeCamera) {
  59293. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  59294. }
  59295. }
  59296. else {
  59297. camera = scene.activeCamera;
  59298. if (camera) {
  59299. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  59300. }
  59301. }
  59302. // Prepare renderingManager
  59303. this._renderingManager.reset();
  59304. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  59305. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  59306. var sceneRenderId = scene.getRenderId();
  59307. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  59308. var mesh = currentRenderList[meshIndex];
  59309. if (mesh) {
  59310. if (!mesh.isReady(this.refreshRate === 0)) {
  59311. this.resetRefreshCounter();
  59312. continue;
  59313. }
  59314. mesh._preActivateForIntermediateRendering(sceneRenderId);
  59315. var isMasked = void 0;
  59316. if (!this.renderList && camera) {
  59317. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  59318. }
  59319. else {
  59320. isMasked = false;
  59321. }
  59322. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  59323. mesh._activate(sceneRenderId);
  59324. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  59325. var subMesh = mesh.subMeshes[subIndex];
  59326. scene._activeIndices.addCount(subMesh.indexCount, false);
  59327. this._renderingManager.dispatch(subMesh, mesh);
  59328. }
  59329. }
  59330. }
  59331. }
  59332. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  59333. var particleSystem = scene.particleSystems[particleIndex];
  59334. var emitter = particleSystem.emitter;
  59335. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  59336. continue;
  59337. }
  59338. if (currentRenderList.indexOf(emitter) >= 0) {
  59339. this._renderingManager.dispatchParticles(particleSystem);
  59340. }
  59341. }
  59342. if (this.isCube) {
  59343. for (var face = 0; face < 6; face++) {
  59344. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  59345. scene.incrementRenderId();
  59346. scene.resetCachedMaterial();
  59347. }
  59348. }
  59349. else {
  59350. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  59351. }
  59352. this.onAfterUnbindObservable.notifyObservers(this);
  59353. if (scene.activeCamera) {
  59354. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  59355. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  59356. }
  59357. engine.setViewport(scene.activeCamera.viewport);
  59358. }
  59359. scene.resetCachedMaterial();
  59360. };
  59361. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  59362. var minimum = 128;
  59363. var x = renderDimension * scale;
  59364. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  59365. // Ensure we don't exceed the render dimension (while staying POT)
  59366. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  59367. };
  59368. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  59369. var _this = this;
  59370. if (!this._texture) {
  59371. return;
  59372. }
  59373. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  59374. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  59375. });
  59376. };
  59377. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  59378. var scene = this.getScene();
  59379. if (!scene) {
  59380. return;
  59381. }
  59382. var engine = scene.getEngine();
  59383. if (!this._texture) {
  59384. return;
  59385. }
  59386. // Bind
  59387. if (this._postProcessManager) {
  59388. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  59389. }
  59390. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  59391. if (this._texture) {
  59392. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  59393. }
  59394. }
  59395. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  59396. // Clear
  59397. if (this.onClearObservable.hasObservers()) {
  59398. this.onClearObservable.notifyObservers(engine);
  59399. }
  59400. else {
  59401. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  59402. }
  59403. if (!this._doNotChangeAspectRatio) {
  59404. scene.updateTransformMatrix(true);
  59405. }
  59406. // Render
  59407. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  59408. if (this._postProcessManager) {
  59409. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  59410. }
  59411. else if (useCameraPostProcess) {
  59412. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  59413. }
  59414. if (!this._doNotChangeAspectRatio) {
  59415. scene.updateTransformMatrix(true);
  59416. }
  59417. // Dump ?
  59418. if (dumpForDebug) {
  59419. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  59420. }
  59421. // Unbind
  59422. if (!this.isCube || faceIndex === 5) {
  59423. if (this.isCube) {
  59424. if (faceIndex === 5) {
  59425. engine.generateMipMapsForCubemap(this._texture);
  59426. }
  59427. }
  59428. this.unbindFrameBuffer(engine, faceIndex);
  59429. }
  59430. else {
  59431. this.onAfterRenderObservable.notifyObservers(faceIndex);
  59432. }
  59433. };
  59434. /**
  59435. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  59436. * This allowed control for front to back rendering or reversly depending of the special needs.
  59437. *
  59438. * @param renderingGroupId The rendering group id corresponding to its index
  59439. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  59440. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  59441. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  59442. */
  59443. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  59444. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  59445. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  59446. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  59447. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  59448. };
  59449. /**
  59450. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  59451. *
  59452. * @param renderingGroupId The rendering group id corresponding to its index
  59453. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  59454. */
  59455. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  59456. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  59457. };
  59458. RenderTargetTexture.prototype.clone = function () {
  59459. var textureSize = this.getSize();
  59460. 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);
  59461. // Base texture
  59462. newTexture.hasAlpha = this.hasAlpha;
  59463. newTexture.level = this.level;
  59464. // RenderTarget Texture
  59465. newTexture.coordinatesMode = this.coordinatesMode;
  59466. if (this.renderList) {
  59467. newTexture.renderList = this.renderList.slice(0);
  59468. }
  59469. return newTexture;
  59470. };
  59471. RenderTargetTexture.prototype.serialize = function () {
  59472. if (!this.name) {
  59473. return null;
  59474. }
  59475. var serializationObject = _super.prototype.serialize.call(this);
  59476. serializationObject.renderTargetSize = this.getRenderSize();
  59477. serializationObject.renderList = [];
  59478. if (this.renderList) {
  59479. for (var index = 0; index < this.renderList.length; index++) {
  59480. serializationObject.renderList.push(this.renderList[index].id);
  59481. }
  59482. }
  59483. return serializationObject;
  59484. };
  59485. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  59486. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  59487. var objBuffer = this.getInternalTexture();
  59488. var scene = this.getScene();
  59489. if (objBuffer && scene) {
  59490. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  59491. }
  59492. };
  59493. RenderTargetTexture.prototype.dispose = function () {
  59494. if (this._postProcessManager) {
  59495. this._postProcessManager.dispose();
  59496. this._postProcessManager = null;
  59497. }
  59498. this.clearPostProcesses(true);
  59499. if (this._resizeObserver) {
  59500. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  59501. this._resizeObserver = null;
  59502. }
  59503. this.renderList = null;
  59504. // Remove from custom render targets
  59505. var scene = this.getScene();
  59506. if (!scene) {
  59507. return;
  59508. }
  59509. var index = scene.customRenderTargets.indexOf(this);
  59510. if (index >= 0) {
  59511. scene.customRenderTargets.splice(index, 1);
  59512. }
  59513. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  59514. var camera = _a[_i];
  59515. index = camera.customRenderTargets.indexOf(this);
  59516. if (index >= 0) {
  59517. camera.customRenderTargets.splice(index, 1);
  59518. }
  59519. }
  59520. _super.prototype.dispose.call(this);
  59521. };
  59522. RenderTargetTexture.prototype._rebuild = function () {
  59523. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  59524. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  59525. }
  59526. if (this._postProcessManager) {
  59527. this._postProcessManager._rebuild();
  59528. }
  59529. };
  59530. /**
  59531. * Clear the info related to rendering groups preventing retention point in material dispose.
  59532. */
  59533. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  59534. if (this._renderingManager) {
  59535. this._renderingManager.freeRenderingGroups();
  59536. }
  59537. };
  59538. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  59539. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  59540. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  59541. return RenderTargetTexture;
  59542. }(BABYLON.Texture));
  59543. BABYLON.RenderTargetTexture = RenderTargetTexture;
  59544. })(BABYLON || (BABYLON = {}));
  59545. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  59546. "use strict";
  59547. var BABYLON;
  59548. (function (BABYLON) {
  59549. ;
  59550. var MultiRenderTarget = /** @class */ (function (_super) {
  59551. __extends(MultiRenderTarget, _super);
  59552. function MultiRenderTarget(name, size, count, scene, options) {
  59553. var _this = this;
  59554. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  59555. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  59556. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  59557. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  59558. _this._engine = scene.getEngine();
  59559. if (!_this.isSupported) {
  59560. _this.dispose();
  59561. return;
  59562. }
  59563. var types = [];
  59564. var samplingModes = [];
  59565. for (var i = 0; i < count; i++) {
  59566. if (options && options.types && options.types[i] !== undefined) {
  59567. types.push(options.types[i]);
  59568. }
  59569. else {
  59570. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59571. }
  59572. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  59573. samplingModes.push(options.samplingModes[i]);
  59574. }
  59575. else {
  59576. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59577. }
  59578. }
  59579. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  59580. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  59581. _this._size = size;
  59582. _this._multiRenderTargetOptions = {
  59583. samplingModes: samplingModes,
  59584. generateMipMaps: generateMipMaps,
  59585. generateDepthBuffer: generateDepthBuffer,
  59586. generateStencilBuffer: generateStencilBuffer,
  59587. generateDepthTexture: generateDepthTexture,
  59588. types: types,
  59589. textureCount: count
  59590. };
  59591. _this._createInternalTextures();
  59592. _this._createTextures();
  59593. return _this;
  59594. }
  59595. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  59596. get: function () {
  59597. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  59598. },
  59599. enumerable: true,
  59600. configurable: true
  59601. });
  59602. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  59603. get: function () {
  59604. return this._textures;
  59605. },
  59606. enumerable: true,
  59607. configurable: true
  59608. });
  59609. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  59610. get: function () {
  59611. return this._textures[this._textures.length - 1];
  59612. },
  59613. enumerable: true,
  59614. configurable: true
  59615. });
  59616. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  59617. set: function (wrap) {
  59618. if (this._textures) {
  59619. for (var i = 0; i < this._textures.length; i++) {
  59620. this._textures[i].wrapU = wrap;
  59621. }
  59622. }
  59623. },
  59624. enumerable: true,
  59625. configurable: true
  59626. });
  59627. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  59628. set: function (wrap) {
  59629. if (this._textures) {
  59630. for (var i = 0; i < this._textures.length; i++) {
  59631. this._textures[i].wrapV = wrap;
  59632. }
  59633. }
  59634. },
  59635. enumerable: true,
  59636. configurable: true
  59637. });
  59638. MultiRenderTarget.prototype._rebuild = function () {
  59639. this.releaseInternalTextures();
  59640. this._createInternalTextures();
  59641. for (var i = 0; i < this._internalTextures.length; i++) {
  59642. var texture = this._textures[i];
  59643. texture._texture = this._internalTextures[i];
  59644. }
  59645. // Keeps references to frame buffer and stencil/depth buffer
  59646. this._texture = this._internalTextures[0];
  59647. };
  59648. MultiRenderTarget.prototype._createInternalTextures = function () {
  59649. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  59650. };
  59651. MultiRenderTarget.prototype._createTextures = function () {
  59652. this._textures = [];
  59653. for (var i = 0; i < this._internalTextures.length; i++) {
  59654. var texture = new BABYLON.Texture(null, this.getScene());
  59655. texture._texture = this._internalTextures[i];
  59656. this._textures.push(texture);
  59657. }
  59658. // Keeps references to frame buffer and stencil/depth buffer
  59659. this._texture = this._internalTextures[0];
  59660. };
  59661. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  59662. get: function () {
  59663. return this._samples;
  59664. },
  59665. set: function (value) {
  59666. if (this._samples === value) {
  59667. return;
  59668. }
  59669. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  59670. },
  59671. enumerable: true,
  59672. configurable: true
  59673. });
  59674. MultiRenderTarget.prototype.resize = function (size) {
  59675. this.releaseInternalTextures();
  59676. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  59677. this._createInternalTextures();
  59678. };
  59679. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  59680. var _this = this;
  59681. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  59682. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  59683. });
  59684. };
  59685. MultiRenderTarget.prototype.dispose = function () {
  59686. this.releaseInternalTextures();
  59687. _super.prototype.dispose.call(this);
  59688. };
  59689. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  59690. if (!this._internalTextures) {
  59691. return;
  59692. }
  59693. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  59694. if (this._internalTextures[i] !== undefined) {
  59695. this._internalTextures[i].dispose();
  59696. this._internalTextures.splice(i, 1);
  59697. }
  59698. }
  59699. };
  59700. return MultiRenderTarget;
  59701. }(BABYLON.RenderTargetTexture));
  59702. BABYLON.MultiRenderTarget = MultiRenderTarget;
  59703. })(BABYLON || (BABYLON = {}));
  59704. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  59705. "use strict";
  59706. var BABYLON;
  59707. (function (BABYLON) {
  59708. var MirrorTexture = /** @class */ (function (_super) {
  59709. __extends(MirrorTexture, _super);
  59710. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  59711. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59712. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59713. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  59714. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  59715. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  59716. _this._transformMatrix = BABYLON.Matrix.Zero();
  59717. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  59718. _this._adaptiveBlurKernel = 0;
  59719. _this._blurKernelX = 0;
  59720. _this._blurKernelY = 0;
  59721. _this._blurRatio = 1.0;
  59722. _this.ignoreCameraViewport = true;
  59723. _this.onBeforeRenderObservable.add(function () {
  59724. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  59725. _this._savedViewMatrix = scene.getViewMatrix();
  59726. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  59727. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  59728. scene.clipPlane = _this.mirrorPlane;
  59729. scene.getEngine().cullBackFaces = false;
  59730. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  59731. });
  59732. _this.onAfterRenderObservable.add(function () {
  59733. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  59734. scene.getEngine().cullBackFaces = true;
  59735. scene._mirroredCameraPosition = null;
  59736. delete scene.clipPlane;
  59737. });
  59738. return _this;
  59739. }
  59740. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  59741. get: function () {
  59742. return this._blurRatio;
  59743. },
  59744. set: function (value) {
  59745. if (this._blurRatio === value) {
  59746. return;
  59747. }
  59748. this._blurRatio = value;
  59749. this._preparePostProcesses();
  59750. },
  59751. enumerable: true,
  59752. configurable: true
  59753. });
  59754. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  59755. set: function (value) {
  59756. this._adaptiveBlurKernel = value;
  59757. this._autoComputeBlurKernel();
  59758. },
  59759. enumerable: true,
  59760. configurable: true
  59761. });
  59762. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  59763. set: function (value) {
  59764. this.blurKernelX = value;
  59765. this.blurKernelY = value;
  59766. },
  59767. enumerable: true,
  59768. configurable: true
  59769. });
  59770. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  59771. get: function () {
  59772. return this._blurKernelX;
  59773. },
  59774. set: function (value) {
  59775. if (this._blurKernelX === value) {
  59776. return;
  59777. }
  59778. this._blurKernelX = value;
  59779. this._preparePostProcesses();
  59780. },
  59781. enumerable: true,
  59782. configurable: true
  59783. });
  59784. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  59785. get: function () {
  59786. return this._blurKernelY;
  59787. },
  59788. set: function (value) {
  59789. if (this._blurKernelY === value) {
  59790. return;
  59791. }
  59792. this._blurKernelY = value;
  59793. this._preparePostProcesses();
  59794. },
  59795. enumerable: true,
  59796. configurable: true
  59797. });
  59798. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  59799. var engine = this.getScene().getEngine();
  59800. var dw = this.getRenderWidth() / engine.getRenderWidth();
  59801. var dh = this.getRenderHeight() / engine.getRenderHeight();
  59802. this.blurKernelX = this._adaptiveBlurKernel * dw;
  59803. this.blurKernelY = this._adaptiveBlurKernel * dh;
  59804. };
  59805. MirrorTexture.prototype._onRatioRescale = function () {
  59806. if (this._sizeRatio) {
  59807. this.resize(this._initialSizeParameter);
  59808. if (!this._adaptiveBlurKernel) {
  59809. this._preparePostProcesses();
  59810. }
  59811. }
  59812. if (this._adaptiveBlurKernel) {
  59813. this._autoComputeBlurKernel();
  59814. }
  59815. };
  59816. MirrorTexture.prototype._preparePostProcesses = function () {
  59817. this.clearPostProcesses(true);
  59818. if (this._blurKernelX && this._blurKernelY) {
  59819. var engine = this.getScene().getEngine();
  59820. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59821. 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);
  59822. this._blurX.autoClear = false;
  59823. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  59824. this._blurX.inputTexture = this._texture;
  59825. }
  59826. else {
  59827. this._blurX.alwaysForcePOT = true;
  59828. }
  59829. 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);
  59830. this._blurY.autoClear = false;
  59831. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  59832. this.addPostProcess(this._blurX);
  59833. this.addPostProcess(this._blurY);
  59834. }
  59835. else {
  59836. if (this._blurY) {
  59837. this.removePostProcess(this._blurY);
  59838. this._blurY.dispose();
  59839. this._blurY = null;
  59840. }
  59841. if (this._blurX) {
  59842. this.removePostProcess(this._blurX);
  59843. this._blurX.dispose();
  59844. this._blurX = null;
  59845. }
  59846. }
  59847. };
  59848. MirrorTexture.prototype.clone = function () {
  59849. var scene = this.getScene();
  59850. if (!scene) {
  59851. return this;
  59852. }
  59853. var textureSize = this.getSize();
  59854. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  59855. // Base texture
  59856. newTexture.hasAlpha = this.hasAlpha;
  59857. newTexture.level = this.level;
  59858. // Mirror Texture
  59859. newTexture.mirrorPlane = this.mirrorPlane.clone();
  59860. if (this.renderList) {
  59861. newTexture.renderList = this.renderList.slice(0);
  59862. }
  59863. return newTexture;
  59864. };
  59865. MirrorTexture.prototype.serialize = function () {
  59866. if (!this.name) {
  59867. return null;
  59868. }
  59869. var serializationObject = _super.prototype.serialize.call(this);
  59870. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  59871. return serializationObject;
  59872. };
  59873. return MirrorTexture;
  59874. }(BABYLON.RenderTargetTexture));
  59875. BABYLON.MirrorTexture = MirrorTexture;
  59876. })(BABYLON || (BABYLON = {}));
  59877. //# sourceMappingURL=babylon.mirrorTexture.js.map
  59878. "use strict";
  59879. var BABYLON;
  59880. (function (BABYLON) {
  59881. /**
  59882. * Creates a refraction texture used by refraction channel of the standard material.
  59883. * @param name the texture name
  59884. * @param size size of the underlying texture
  59885. * @param scene root scene
  59886. */
  59887. var RefractionTexture = /** @class */ (function (_super) {
  59888. __extends(RefractionTexture, _super);
  59889. function RefractionTexture(name, size, scene, generateMipMaps) {
  59890. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  59891. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  59892. _this.depth = 2.0;
  59893. _this.onBeforeRenderObservable.add(function () {
  59894. scene.clipPlane = _this.refractionPlane;
  59895. });
  59896. _this.onAfterRenderObservable.add(function () {
  59897. delete scene.clipPlane;
  59898. });
  59899. return _this;
  59900. }
  59901. RefractionTexture.prototype.clone = function () {
  59902. var scene = this.getScene();
  59903. if (!scene) {
  59904. return this;
  59905. }
  59906. var textureSize = this.getSize();
  59907. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  59908. // Base texture
  59909. newTexture.hasAlpha = this.hasAlpha;
  59910. newTexture.level = this.level;
  59911. // Refraction Texture
  59912. newTexture.refractionPlane = this.refractionPlane.clone();
  59913. if (this.renderList) {
  59914. newTexture.renderList = this.renderList.slice(0);
  59915. }
  59916. newTexture.depth = this.depth;
  59917. return newTexture;
  59918. };
  59919. RefractionTexture.prototype.serialize = function () {
  59920. if (!this.name) {
  59921. return null;
  59922. }
  59923. var serializationObject = _super.prototype.serialize.call(this);
  59924. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  59925. serializationObject.depth = this.depth;
  59926. return serializationObject;
  59927. };
  59928. return RefractionTexture;
  59929. }(BABYLON.RenderTargetTexture));
  59930. BABYLON.RefractionTexture = RefractionTexture;
  59931. })(BABYLON || (BABYLON = {}));
  59932. //# sourceMappingURL=babylon.refractionTexture.js.map
  59933. "use strict";
  59934. var BABYLON;
  59935. (function (BABYLON) {
  59936. var DynamicTexture = /** @class */ (function (_super) {
  59937. __extends(DynamicTexture, _super);
  59938. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  59939. if (scene === void 0) { scene = null; }
  59940. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59941. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  59942. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  59943. _this.name = name;
  59944. _this._engine = _this.getScene().getEngine();
  59945. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59946. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59947. _this._generateMipMaps = generateMipMaps;
  59948. if (options.getContext) {
  59949. _this._canvas = options;
  59950. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59951. }
  59952. else {
  59953. _this._canvas = document.createElement("canvas");
  59954. if (options.width) {
  59955. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59956. }
  59957. else {
  59958. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  59959. }
  59960. }
  59961. var textureSize = _this.getSize();
  59962. _this._canvas.width = textureSize.width;
  59963. _this._canvas.height = textureSize.height;
  59964. _this._context = _this._canvas.getContext("2d");
  59965. return _this;
  59966. }
  59967. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  59968. get: function () {
  59969. return true;
  59970. },
  59971. enumerable: true,
  59972. configurable: true
  59973. });
  59974. DynamicTexture.prototype._recreate = function (textureSize) {
  59975. this._canvas.width = textureSize.width;
  59976. this._canvas.height = textureSize.height;
  59977. this.releaseInternalTexture();
  59978. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  59979. };
  59980. DynamicTexture.prototype.scale = function (ratio) {
  59981. var textureSize = this.getSize();
  59982. textureSize.width *= ratio;
  59983. textureSize.height *= ratio;
  59984. this._recreate(textureSize);
  59985. };
  59986. DynamicTexture.prototype.scaleTo = function (width, height) {
  59987. var textureSize = this.getSize();
  59988. textureSize.width = width;
  59989. textureSize.height = height;
  59990. this._recreate(textureSize);
  59991. };
  59992. DynamicTexture.prototype.getContext = function () {
  59993. return this._context;
  59994. };
  59995. DynamicTexture.prototype.clear = function () {
  59996. var size = this.getSize();
  59997. this._context.fillRect(0, 0, size.width, size.height);
  59998. };
  59999. DynamicTexture.prototype.update = function (invertY) {
  60000. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  60001. };
  60002. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  60003. if (update === void 0) { update = true; }
  60004. var size = this.getSize();
  60005. if (clearColor) {
  60006. this._context.fillStyle = clearColor;
  60007. this._context.fillRect(0, 0, size.width, size.height);
  60008. }
  60009. this._context.font = font;
  60010. if (x === null || x === undefined) {
  60011. var textSize = this._context.measureText(text);
  60012. x = (size.width - textSize.width) / 2;
  60013. }
  60014. if (y === null || y === undefined) {
  60015. var fontSize = parseInt((font.replace(/\D/g, '')));
  60016. ;
  60017. y = (size.height / 2) + (fontSize / 3.65);
  60018. }
  60019. this._context.fillStyle = color;
  60020. this._context.fillText(text, x, y);
  60021. if (update) {
  60022. this.update(invertY);
  60023. }
  60024. };
  60025. DynamicTexture.prototype.clone = function () {
  60026. var scene = this.getScene();
  60027. if (!scene) {
  60028. return this;
  60029. }
  60030. var textureSize = this.getSize();
  60031. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  60032. // Base texture
  60033. newTexture.hasAlpha = this.hasAlpha;
  60034. newTexture.level = this.level;
  60035. // Dynamic Texture
  60036. newTexture.wrapU = this.wrapU;
  60037. newTexture.wrapV = this.wrapV;
  60038. return newTexture;
  60039. };
  60040. DynamicTexture.prototype._rebuild = function () {
  60041. this.update();
  60042. };
  60043. return DynamicTexture;
  60044. }(BABYLON.Texture));
  60045. BABYLON.DynamicTexture = DynamicTexture;
  60046. })(BABYLON || (BABYLON = {}));
  60047. //# sourceMappingURL=babylon.dynamicTexture.js.map
  60048. "use strict";
  60049. var BABYLON;
  60050. (function (BABYLON) {
  60051. var VideoTexture = /** @class */ (function (_super) {
  60052. __extends(VideoTexture, _super);
  60053. /**
  60054. * Creates a video texture.
  60055. * Sample : https://doc.babylonjs.com/how_to/video_texture
  60056. * @param {string | null} name optional name, will detect from video source, if not defined
  60057. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  60058. * @param {BABYLON.Scene} scene is obviously the current scene.
  60059. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  60060. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  60061. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  60062. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  60063. */
  60064. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  60065. if (generateMipMaps === void 0) { generateMipMaps = false; }
  60066. if (invertY === void 0) { invertY = false; }
  60067. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60068. if (settings === void 0) { settings = {
  60069. autoPlay: true,
  60070. loop: true,
  60071. autoUpdateTexture: true,
  60072. }; }
  60073. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  60074. _this._createInternalTexture = function () {
  60075. if (_this._texture != null) {
  60076. return;
  60077. }
  60078. if (!_this._engine.needPOTTextures ||
  60079. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  60080. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60081. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60082. }
  60083. else {
  60084. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60085. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60086. _this._generateMipMaps = false;
  60087. }
  60088. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  60089. _this._texture.isReady = true;
  60090. _this._updateInternalTexture();
  60091. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  60092. _this.onLoadObservable.notifyObservers(_this);
  60093. }
  60094. };
  60095. _this.reset = function () {
  60096. if (_this._texture == null) {
  60097. return;
  60098. }
  60099. _this._texture.dispose();
  60100. _this._texture = null;
  60101. };
  60102. _this._updateInternalTexture = function (e) {
  60103. if (_this._texture == null || !_this._texture.isReady) {
  60104. return;
  60105. }
  60106. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  60107. return;
  60108. }
  60109. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  60110. };
  60111. _this._engine = _this.getScene().getEngine();
  60112. _this._generateMipMaps = generateMipMaps;
  60113. _this._samplingMode = samplingMode;
  60114. _this.autoUpdateTexture = settings.autoUpdateTexture;
  60115. _this.name = name || _this._getName(src);
  60116. _this.video = _this._getVideo(src);
  60117. if (settings.autoPlay !== undefined) {
  60118. _this.video.autoplay = settings.autoPlay;
  60119. }
  60120. if (settings.loop !== undefined) {
  60121. _this.video.loop = settings.loop;
  60122. }
  60123. _this.video.addEventListener("canplay", _this._createInternalTexture);
  60124. _this.video.addEventListener("paused", _this._updateInternalTexture);
  60125. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  60126. _this.video.addEventListener("emptied", _this.reset);
  60127. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  60128. _this._createInternalTexture();
  60129. }
  60130. return _this;
  60131. }
  60132. VideoTexture.prototype._getName = function (src) {
  60133. if (src instanceof HTMLVideoElement) {
  60134. return src.currentSrc;
  60135. }
  60136. if (typeof src === "object") {
  60137. return src.toString();
  60138. }
  60139. return src;
  60140. };
  60141. ;
  60142. VideoTexture.prototype._getVideo = function (src) {
  60143. if (src instanceof HTMLVideoElement) {
  60144. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  60145. return src;
  60146. }
  60147. var video = document.createElement("video");
  60148. if (typeof src === "string") {
  60149. BABYLON.Tools.SetCorsBehavior(src, video);
  60150. video.src = src;
  60151. }
  60152. else {
  60153. BABYLON.Tools.SetCorsBehavior(src[0], video);
  60154. src.forEach(function (url) {
  60155. var source = document.createElement("source");
  60156. source.src = url;
  60157. video.appendChild(source);
  60158. });
  60159. }
  60160. return video;
  60161. };
  60162. ;
  60163. /**
  60164. * Internal method to initiate `update`.
  60165. */
  60166. VideoTexture.prototype._rebuild = function () {
  60167. this.update();
  60168. };
  60169. /**
  60170. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  60171. */
  60172. VideoTexture.prototype.update = function () {
  60173. if (!this.autoUpdateTexture) {
  60174. // Expecting user to call `updateTexture` manually
  60175. return;
  60176. }
  60177. this.updateTexture(true);
  60178. };
  60179. /**
  60180. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  60181. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  60182. */
  60183. VideoTexture.prototype.updateTexture = function (isVisible) {
  60184. if (!isVisible) {
  60185. return;
  60186. }
  60187. if (this.video.paused) {
  60188. return;
  60189. }
  60190. this._updateInternalTexture();
  60191. };
  60192. /**
  60193. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  60194. * @param url New url.
  60195. */
  60196. VideoTexture.prototype.updateURL = function (url) {
  60197. this.video.src = url;
  60198. };
  60199. VideoTexture.prototype.dispose = function () {
  60200. _super.prototype.dispose.call(this);
  60201. this.video.removeEventListener("canplay", this._createInternalTexture);
  60202. this.video.removeEventListener("paused", this._updateInternalTexture);
  60203. this.video.removeEventListener("seeked", this._updateInternalTexture);
  60204. this.video.removeEventListener("emptied", this.reset);
  60205. this.video.pause();
  60206. };
  60207. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  60208. var video = document.createElement("video");
  60209. var constraintsDeviceId;
  60210. if (constraints && constraints.deviceId) {
  60211. constraintsDeviceId = {
  60212. exact: constraints.deviceId,
  60213. };
  60214. }
  60215. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  60216. if (navigator.mediaDevices) {
  60217. navigator.mediaDevices.getUserMedia({ video: constraints })
  60218. .then(function (stream) {
  60219. if (video.mozSrcObject !== undefined) {
  60220. // hack for Firefox < 19
  60221. video.mozSrcObject = stream;
  60222. }
  60223. else {
  60224. video.srcObject = stream;
  60225. }
  60226. var onPlaying = function () {
  60227. if (onReady) {
  60228. onReady(new VideoTexture("video", video, scene, true, true));
  60229. }
  60230. video.removeEventListener("playing", onPlaying);
  60231. };
  60232. video.addEventListener("playing", onPlaying);
  60233. video.play();
  60234. })
  60235. .catch(function (err) {
  60236. BABYLON.Tools.Error(err.name);
  60237. });
  60238. }
  60239. else {
  60240. navigator.getUserMedia =
  60241. navigator.getUserMedia ||
  60242. navigator.webkitGetUserMedia ||
  60243. navigator.mozGetUserMedia ||
  60244. navigator.msGetUserMedia;
  60245. if (navigator.getUserMedia) {
  60246. navigator.getUserMedia({
  60247. video: {
  60248. deviceId: constraintsDeviceId,
  60249. width: {
  60250. min: (constraints && constraints.minWidth) || 256,
  60251. max: (constraints && constraints.maxWidth) || 640,
  60252. },
  60253. height: {
  60254. min: (constraints && constraints.minHeight) || 256,
  60255. max: (constraints && constraints.maxHeight) || 480,
  60256. },
  60257. },
  60258. }, function (stream) {
  60259. if (video.mozSrcObject !== undefined) {
  60260. // hack for Firefox < 19
  60261. video.mozSrcObject = stream;
  60262. }
  60263. else {
  60264. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  60265. }
  60266. video.play();
  60267. if (onReady) {
  60268. onReady(new VideoTexture("video", video, scene, true, true));
  60269. }
  60270. }, function (e) {
  60271. BABYLON.Tools.Error(e.name);
  60272. });
  60273. }
  60274. }
  60275. };
  60276. return VideoTexture;
  60277. }(BABYLON.Texture));
  60278. BABYLON.VideoTexture = VideoTexture;
  60279. })(BABYLON || (BABYLON = {}));
  60280. //# sourceMappingURL=babylon.videoTexture.js.map
  60281. "use strict";
  60282. var BABYLON;
  60283. (function (BABYLON) {
  60284. var RawTexture = /** @class */ (function (_super) {
  60285. __extends(RawTexture, _super);
  60286. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  60287. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60288. if (invertY === void 0) { invertY = false; }
  60289. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60290. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60291. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  60292. _this.format = format;
  60293. _this._engine = scene.getEngine();
  60294. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  60295. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60296. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60297. return _this;
  60298. }
  60299. RawTexture.prototype.update = function (data) {
  60300. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  60301. };
  60302. // Statics
  60303. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60304. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60305. if (invertY === void 0) { invertY = false; }
  60306. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60307. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  60308. };
  60309. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60310. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60311. if (invertY === void 0) { invertY = false; }
  60312. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60313. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  60314. };
  60315. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60316. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60317. if (invertY === void 0) { invertY = false; }
  60318. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60319. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  60320. };
  60321. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  60322. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60323. if (invertY === void 0) { invertY = false; }
  60324. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60325. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60326. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  60327. };
  60328. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  60329. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60330. if (invertY === void 0) { invertY = false; }
  60331. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60332. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60333. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  60334. };
  60335. return RawTexture;
  60336. }(BABYLON.Texture));
  60337. BABYLON.RawTexture = RawTexture;
  60338. })(BABYLON || (BABYLON = {}));
  60339. //# sourceMappingURL=babylon.rawTexture.js.map
  60340. "use strict";
  60341. var BABYLON;
  60342. (function (BABYLON) {
  60343. /**
  60344. * PostProcess can be used to apply a shader to a texture after it has been rendered
  60345. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  60346. */
  60347. var PostProcess = /** @class */ (function () {
  60348. /**
  60349. * Creates a new instance of @see PostProcess
  60350. * @param name The name of the PostProcess.
  60351. * @param fragmentUrl The url of the fragment shader to be used.
  60352. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  60353. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  60354. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  60355. * @param camera The camera to apply the render pass to.
  60356. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  60357. * @param engine The engine which the post process will be applied. (default: current engine)
  60358. * @param reusable If the post process can be reused on the same frame. (default: false)
  60359. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  60360. * @param textureType Type of textures used when performing the post process. (default: 0)
  60361. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  60362. * @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
  60363. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  60364. */
  60365. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  60366. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  60367. if (defines === void 0) { defines = null; }
  60368. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60369. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  60370. if (blockCompilation === void 0) { blockCompilation = false; }
  60371. this.name = name;
  60372. /**
  60373. * Width of the texture to apply the post process on
  60374. */
  60375. this.width = -1;
  60376. /**
  60377. * Height of the texture to apply the post process on
  60378. */
  60379. this.height = -1;
  60380. /**
  60381. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  60382. */
  60383. this._outputTexture = null;
  60384. /**
  60385. * If the buffer needs to be cleared before applying the post process. (default: true)
  60386. * Should be set to false if shader will overwrite all previous pixels.
  60387. */
  60388. this.autoClear = true;
  60389. /**
  60390. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  60391. */
  60392. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  60393. /**
  60394. * Animations to be used for the post processing
  60395. */
  60396. this.animations = new Array();
  60397. /**
  60398. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  60399. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  60400. */
  60401. this.enablePixelPerfectMode = false;
  60402. /**
  60403. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  60404. */
  60405. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  60406. /**
  60407. * Force textures to be a power of two (default: false)
  60408. */
  60409. this.alwaysForcePOT = false;
  60410. /**
  60411. * Number of sample textures (default: 1)
  60412. */
  60413. this.samples = 1;
  60414. /**
  60415. * Modify the scale of the post process to be the same as the viewport (default: false)
  60416. */
  60417. this.adaptScaleToCurrentViewport = false;
  60418. this._reusable = false;
  60419. /**
  60420. * Smart array of input and output textures for the post process.
  60421. */
  60422. this._textures = new BABYLON.SmartArray(2);
  60423. /**
  60424. * The index in _textures that corresponds to the output texture.
  60425. */
  60426. this._currentRenderTextureInd = 0;
  60427. this._scaleRatio = new BABYLON.Vector2(1, 1);
  60428. this._texelSize = BABYLON.Vector2.Zero();
  60429. // Events
  60430. /**
  60431. * An event triggered when the postprocess is activated.
  60432. * @type {BABYLON.Observable}
  60433. */
  60434. this.onActivateObservable = new BABYLON.Observable();
  60435. /**
  60436. * An event triggered when the postprocess changes its size.
  60437. * @type {BABYLON.Observable}
  60438. */
  60439. this.onSizeChangedObservable = new BABYLON.Observable();
  60440. /**
  60441. * An event triggered when the postprocess applies its effect.
  60442. * @type {BABYLON.Observable}
  60443. */
  60444. this.onApplyObservable = new BABYLON.Observable();
  60445. /**
  60446. * An event triggered before rendering the postprocess
  60447. * @type {BABYLON.Observable}
  60448. */
  60449. this.onBeforeRenderObservable = new BABYLON.Observable();
  60450. /**
  60451. * An event triggered after rendering the postprocess
  60452. * @type {BABYLON.Observable}
  60453. */
  60454. this.onAfterRenderObservable = new BABYLON.Observable();
  60455. if (camera != null) {
  60456. this._camera = camera;
  60457. this._scene = camera.getScene();
  60458. camera.attachPostProcess(this);
  60459. this._engine = this._scene.getEngine();
  60460. this._scene.postProcesses.push(this);
  60461. }
  60462. else if (engine) {
  60463. this._engine = engine;
  60464. this._engine.postProcesses.push(this);
  60465. }
  60466. this._options = options;
  60467. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  60468. this._reusable = reusable || false;
  60469. this._textureType = textureType;
  60470. this._samplers = samplers || [];
  60471. this._samplers.push("textureSampler");
  60472. this._fragmentUrl = fragmentUrl;
  60473. this._vertexUrl = vertexUrl;
  60474. this._parameters = parameters || [];
  60475. this._parameters.push("scale");
  60476. this._indexParameters = indexParameters;
  60477. if (!blockCompilation) {
  60478. this.updateEffect(defines);
  60479. }
  60480. }
  60481. Object.defineProperty(PostProcess.prototype, "onActivate", {
  60482. /**
  60483. * A function that is added to the onActivateObservable
  60484. */
  60485. set: function (callback) {
  60486. if (this._onActivateObserver) {
  60487. this.onActivateObservable.remove(this._onActivateObserver);
  60488. }
  60489. if (callback) {
  60490. this._onActivateObserver = this.onActivateObservable.add(callback);
  60491. }
  60492. },
  60493. enumerable: true,
  60494. configurable: true
  60495. });
  60496. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  60497. /**
  60498. * A function that is added to the onSizeChangedObservable
  60499. */
  60500. set: function (callback) {
  60501. if (this._onSizeChangedObserver) {
  60502. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  60503. }
  60504. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  60505. },
  60506. enumerable: true,
  60507. configurable: true
  60508. });
  60509. Object.defineProperty(PostProcess.prototype, "onApply", {
  60510. /**
  60511. * A function that is added to the onApplyObservable
  60512. */
  60513. set: function (callback) {
  60514. if (this._onApplyObserver) {
  60515. this.onApplyObservable.remove(this._onApplyObserver);
  60516. }
  60517. this._onApplyObserver = this.onApplyObservable.add(callback);
  60518. },
  60519. enumerable: true,
  60520. configurable: true
  60521. });
  60522. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  60523. /**
  60524. * A function that is added to the onBeforeRenderObservable
  60525. */
  60526. set: function (callback) {
  60527. if (this._onBeforeRenderObserver) {
  60528. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  60529. }
  60530. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  60531. },
  60532. enumerable: true,
  60533. configurable: true
  60534. });
  60535. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  60536. /**
  60537. * A function that is added to the onAfterRenderObservable
  60538. */
  60539. set: function (callback) {
  60540. if (this._onAfterRenderObserver) {
  60541. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  60542. }
  60543. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  60544. },
  60545. enumerable: true,
  60546. configurable: true
  60547. });
  60548. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  60549. /**
  60550. * 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
  60551. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  60552. */
  60553. get: function () {
  60554. return this._textures.data[this._currentRenderTextureInd];
  60555. },
  60556. set: function (value) {
  60557. this._forcedOutputTexture = value;
  60558. },
  60559. enumerable: true,
  60560. configurable: true
  60561. });
  60562. /**
  60563. * Gets the camera which post process is applied to.
  60564. * @returns The camera the post process is applied to.
  60565. */
  60566. PostProcess.prototype.getCamera = function () {
  60567. return this._camera;
  60568. };
  60569. Object.defineProperty(PostProcess.prototype, "texelSize", {
  60570. /**
  60571. * Gets the texel size of the postprocess.
  60572. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  60573. */
  60574. get: function () {
  60575. if (this._shareOutputWithPostProcess) {
  60576. return this._shareOutputWithPostProcess.texelSize;
  60577. }
  60578. if (this._forcedOutputTexture) {
  60579. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  60580. }
  60581. return this._texelSize;
  60582. },
  60583. enumerable: true,
  60584. configurable: true
  60585. });
  60586. /**
  60587. * Gets the engine which this post process belongs to.
  60588. * @returns The engine the post process was enabled with.
  60589. */
  60590. PostProcess.prototype.getEngine = function () {
  60591. return this._engine;
  60592. };
  60593. /**
  60594. * The effect that is created when initializing the post process.
  60595. * @returns The created effect corrisponding the the postprocess.
  60596. */
  60597. PostProcess.prototype.getEffect = function () {
  60598. return this._effect;
  60599. };
  60600. /**
  60601. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  60602. * @param postProcess The post process to share the output with.
  60603. * @returns This post process.
  60604. */
  60605. PostProcess.prototype.shareOutputWith = function (postProcess) {
  60606. this._disposeTextures();
  60607. this._shareOutputWithPostProcess = postProcess;
  60608. return this;
  60609. };
  60610. /**
  60611. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  60612. * This should be called if the post process that shares output with this post process is disabled/disposed.
  60613. */
  60614. PostProcess.prototype.useOwnOutput = function () {
  60615. if (this._textures.length == 0) {
  60616. this._textures = new BABYLON.SmartArray(2);
  60617. }
  60618. this._shareOutputWithPostProcess = null;
  60619. };
  60620. /**
  60621. * Updates the effect with the current post process compile time values and recompiles the shader.
  60622. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  60623. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  60624. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  60625. * @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
  60626. * @param onCompiled Called when the shader has been compiled.
  60627. * @param onError Called if there is an error when compiling a shader.
  60628. */
  60629. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  60630. if (defines === void 0) { defines = null; }
  60631. if (uniforms === void 0) { uniforms = null; }
  60632. if (samplers === void 0) { samplers = null; }
  60633. 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);
  60634. };
  60635. /**
  60636. * The post process is reusable if it can be used multiple times within one frame.
  60637. * @returns If the post process is reusable
  60638. */
  60639. PostProcess.prototype.isReusable = function () {
  60640. return this._reusable;
  60641. };
  60642. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  60643. PostProcess.prototype.markTextureDirty = function () {
  60644. this.width = -1;
  60645. };
  60646. /**
  60647. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  60648. * 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.
  60649. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  60650. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  60651. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  60652. * @returns The target texture that was bound to be written to.
  60653. */
  60654. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  60655. var _this = this;
  60656. if (sourceTexture === void 0) { sourceTexture = null; }
  60657. camera = camera || this._camera;
  60658. var scene = camera.getScene();
  60659. var engine = scene.getEngine();
  60660. var maxSize = engine.getCaps().maxTextureSize;
  60661. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  60662. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  60663. // 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
  60664. var webVRCamera = camera.parent;
  60665. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  60666. requiredWidth /= 2;
  60667. }
  60668. var desiredWidth = (this._options.width || requiredWidth);
  60669. var desiredHeight = this._options.height || requiredHeight;
  60670. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  60671. if (this.adaptScaleToCurrentViewport) {
  60672. var currentViewport = engine.currentViewport;
  60673. if (currentViewport) {
  60674. desiredWidth *= currentViewport.width;
  60675. desiredHeight *= currentViewport.height;
  60676. }
  60677. }
  60678. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  60679. if (!this._options.width) {
  60680. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  60681. }
  60682. if (!this._options.height) {
  60683. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  60684. }
  60685. }
  60686. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  60687. if (this._textures.length > 0) {
  60688. for (var i = 0; i < this._textures.length; i++) {
  60689. this._engine._releaseTexture(this._textures.data[i]);
  60690. }
  60691. this._textures.reset();
  60692. }
  60693. this.width = desiredWidth;
  60694. this.height = desiredHeight;
  60695. var textureSize = { width: this.width, height: this.height };
  60696. var textureOptions = {
  60697. generateMipMaps: false,
  60698. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  60699. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  60700. samplingMode: this.renderTargetSamplingMode,
  60701. type: this._textureType
  60702. };
  60703. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60704. if (this._reusable) {
  60705. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60706. }
  60707. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  60708. this.onSizeChangedObservable.notifyObservers(this);
  60709. }
  60710. this._textures.forEach(function (texture) {
  60711. if (texture.samples !== _this.samples) {
  60712. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  60713. }
  60714. });
  60715. }
  60716. var target;
  60717. if (this._shareOutputWithPostProcess) {
  60718. target = this._shareOutputWithPostProcess.inputTexture;
  60719. }
  60720. else if (this._forcedOutputTexture) {
  60721. target = this._forcedOutputTexture;
  60722. this.width = this._forcedOutputTexture.width;
  60723. this.height = this._forcedOutputTexture.height;
  60724. }
  60725. else {
  60726. target = this.inputTexture;
  60727. }
  60728. // Bind the input of this post process to be used as the output of the previous post process.
  60729. if (this.enablePixelPerfectMode) {
  60730. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  60731. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  60732. }
  60733. else {
  60734. this._scaleRatio.copyFromFloats(1, 1);
  60735. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  60736. }
  60737. this.onActivateObservable.notifyObservers(camera);
  60738. // Clear
  60739. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  60740. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  60741. }
  60742. if (this._reusable) {
  60743. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  60744. }
  60745. return target;
  60746. };
  60747. Object.defineProperty(PostProcess.prototype, "isSupported", {
  60748. /**
  60749. * If the post process is supported.
  60750. */
  60751. get: function () {
  60752. return this._effect.isSupported;
  60753. },
  60754. enumerable: true,
  60755. configurable: true
  60756. });
  60757. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  60758. /**
  60759. * The aspect ratio of the output texture.
  60760. */
  60761. get: function () {
  60762. if (this._shareOutputWithPostProcess) {
  60763. return this._shareOutputWithPostProcess.aspectRatio;
  60764. }
  60765. if (this._forcedOutputTexture) {
  60766. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  60767. }
  60768. return this.width / this.height;
  60769. },
  60770. enumerable: true,
  60771. configurable: true
  60772. });
  60773. /**
  60774. * Get a value indicating if the post-process is ready to be used
  60775. * @returns true if the post-process is ready (shader is compiled)
  60776. */
  60777. PostProcess.prototype.isReady = function () {
  60778. return this._effect && this._effect.isReady();
  60779. };
  60780. /**
  60781. * Binds all textures and uniforms to the shader, this will be run on every pass.
  60782. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  60783. */
  60784. PostProcess.prototype.apply = function () {
  60785. // Check
  60786. if (!this._effect || !this._effect.isReady())
  60787. return null;
  60788. // States
  60789. this._engine.enableEffect(this._effect);
  60790. this._engine.setState(false);
  60791. this._engine.setDepthBuffer(false);
  60792. this._engine.setDepthWrite(false);
  60793. // Alpha
  60794. this._engine.setAlphaMode(this.alphaMode);
  60795. if (this.alphaConstants) {
  60796. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  60797. }
  60798. // Bind the output texture of the preivous post process as the input to this post process.
  60799. var source;
  60800. if (this._shareOutputWithPostProcess) {
  60801. source = this._shareOutputWithPostProcess.inputTexture;
  60802. }
  60803. else if (this._forcedOutputTexture) {
  60804. source = this._forcedOutputTexture;
  60805. }
  60806. else {
  60807. source = this.inputTexture;
  60808. }
  60809. this._effect._bindTexture("textureSampler", source);
  60810. // Parameters
  60811. this._effect.setVector2("scale", this._scaleRatio);
  60812. this.onApplyObservable.notifyObservers(this._effect);
  60813. return this._effect;
  60814. };
  60815. PostProcess.prototype._disposeTextures = function () {
  60816. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  60817. return;
  60818. }
  60819. if (this._textures.length > 0) {
  60820. for (var i = 0; i < this._textures.length; i++) {
  60821. this._engine._releaseTexture(this._textures.data[i]);
  60822. }
  60823. }
  60824. this._textures.dispose();
  60825. };
  60826. /**
  60827. * Disposes the post process.
  60828. * @param camera The camera to dispose the post process on.
  60829. */
  60830. PostProcess.prototype.dispose = function (camera) {
  60831. camera = camera || this._camera;
  60832. this._disposeTextures();
  60833. if (this._scene) {
  60834. var index_1 = this._scene.postProcesses.indexOf(this);
  60835. if (index_1 !== -1) {
  60836. this._scene.postProcesses.splice(index_1, 1);
  60837. }
  60838. }
  60839. else {
  60840. var index_2 = this._engine.postProcesses.indexOf(this);
  60841. if (index_2 !== -1) {
  60842. this._engine.postProcesses.splice(index_2, 1);
  60843. }
  60844. }
  60845. if (!camera) {
  60846. return;
  60847. }
  60848. camera.detachPostProcess(this);
  60849. var index = camera._postProcesses.indexOf(this);
  60850. if (index === 0 && camera._postProcesses.length > 0) {
  60851. var firstPostProcess = this._camera._getFirstPostProcess();
  60852. if (firstPostProcess) {
  60853. firstPostProcess.markTextureDirty();
  60854. }
  60855. }
  60856. this.onActivateObservable.clear();
  60857. this.onAfterRenderObservable.clear();
  60858. this.onApplyObservable.clear();
  60859. this.onBeforeRenderObservable.clear();
  60860. this.onSizeChangedObservable.clear();
  60861. };
  60862. return PostProcess;
  60863. }());
  60864. BABYLON.PostProcess = PostProcess;
  60865. })(BABYLON || (BABYLON = {}));
  60866. //# sourceMappingURL=babylon.postProcess.js.map
  60867. "use strict";
  60868. var BABYLON;
  60869. (function (BABYLON) {
  60870. var PassPostProcess = /** @class */ (function (_super) {
  60871. __extends(PassPostProcess, _super);
  60872. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  60873. if (camera === void 0) { camera = null; }
  60874. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60875. if (blockCompilation === void 0) { blockCompilation = false; }
  60876. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  60877. }
  60878. return PassPostProcess;
  60879. }(BABYLON.PostProcess));
  60880. BABYLON.PassPostProcess = PassPostProcess;
  60881. })(BABYLON || (BABYLON = {}));
  60882. //# sourceMappingURL=babylon.passPostProcess.js.map
  60883. "use strict";
  60884. var __assign = (this && this.__assign) || Object.assign || function(t) {
  60885. for (var s, i = 1, n = arguments.length; i < n; i++) {
  60886. s = arguments[i];
  60887. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  60888. t[p] = s[p];
  60889. }
  60890. return t;
  60891. };
  60892. var BABYLON;
  60893. (function (BABYLON) {
  60894. /**
  60895. * Default implementation of @see IShadowGenerator.
  60896. * This is the main object responsible of generating shadows in the framework.
  60897. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  60898. */
  60899. var ShadowGenerator = /** @class */ (function () {
  60900. /**
  60901. * Creates a ShadowGenerator object.
  60902. * A ShadowGenerator is the required tool to use the shadows.
  60903. * Each light casting shadows needs to use its own ShadowGenerator.
  60904. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  60905. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  60906. * @param light The light object generating the shadows.
  60907. * @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.
  60908. */
  60909. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  60910. this._bias = 0.00005;
  60911. this._normalBias = 0;
  60912. this._blurBoxOffset = 1;
  60913. this._blurScale = 2;
  60914. this._blurKernel = 1;
  60915. this._useKernelBlur = false;
  60916. this._filter = ShadowGenerator.FILTER_NONE;
  60917. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  60918. this._contactHardeningLightSizeUVRatio = 0.1;
  60919. this._darkness = 0;
  60920. this._transparencyShadow = false;
  60921. /**
  60922. * Controls the extent to which the shadows fade out at the edge of the frustum
  60923. * Used only by directionals and spots
  60924. */
  60925. this.frustumEdgeFalloff = 0;
  60926. /**
  60927. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  60928. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  60929. * It might on the other hand introduce peter panning.
  60930. */
  60931. this.forceBackFacesOnly = false;
  60932. this._lightDirection = BABYLON.Vector3.Zero();
  60933. this._viewMatrix = BABYLON.Matrix.Zero();
  60934. this._projectionMatrix = BABYLON.Matrix.Zero();
  60935. this._transformMatrix = BABYLON.Matrix.Zero();
  60936. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  60937. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  60938. this._currentFaceIndex = 0;
  60939. this._currentFaceIndexCache = 0;
  60940. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  60941. this._mapSize = mapSize;
  60942. this._light = light;
  60943. this._scene = light.getScene();
  60944. light._shadowGenerator = this;
  60945. // Texture type fallback from float to int if not supported.
  60946. var caps = this._scene.getEngine().getCaps();
  60947. if (!useFullFloatFirst) {
  60948. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60949. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60950. }
  60951. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60952. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60953. }
  60954. else {
  60955. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60956. }
  60957. }
  60958. else {
  60959. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60960. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60961. }
  60962. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60963. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60964. }
  60965. else {
  60966. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60967. }
  60968. }
  60969. this._initializeGenerator();
  60970. this._applyFilterValues();
  60971. }
  60972. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  60973. /**
  60974. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  60975. */
  60976. get: function () {
  60977. return this._bias;
  60978. },
  60979. /**
  60980. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  60981. */
  60982. set: function (bias) {
  60983. this._bias = bias;
  60984. },
  60985. enumerable: true,
  60986. configurable: true
  60987. });
  60988. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  60989. /**
  60990. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  60991. */
  60992. get: function () {
  60993. return this._normalBias;
  60994. },
  60995. /**
  60996. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  60997. */
  60998. set: function (normalBias) {
  60999. this._normalBias = normalBias;
  61000. },
  61001. enumerable: true,
  61002. configurable: true
  61003. });
  61004. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  61005. /**
  61006. * Gets the blur box offset: offset applied during the blur pass.
  61007. * Only usefull if useKernelBlur = false
  61008. */
  61009. get: function () {
  61010. return this._blurBoxOffset;
  61011. },
  61012. /**
  61013. * Sets the blur box offset: offset applied during the blur pass.
  61014. * Only usefull if useKernelBlur = false
  61015. */
  61016. set: function (value) {
  61017. if (this._blurBoxOffset === value) {
  61018. return;
  61019. }
  61020. this._blurBoxOffset = value;
  61021. this._disposeBlurPostProcesses();
  61022. },
  61023. enumerable: true,
  61024. configurable: true
  61025. });
  61026. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  61027. /**
  61028. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  61029. * 2 means half of the size.
  61030. */
  61031. get: function () {
  61032. return this._blurScale;
  61033. },
  61034. /**
  61035. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  61036. * 2 means half of the size.
  61037. */
  61038. set: function (value) {
  61039. if (this._blurScale === value) {
  61040. return;
  61041. }
  61042. this._blurScale = value;
  61043. this._disposeBlurPostProcesses();
  61044. },
  61045. enumerable: true,
  61046. configurable: true
  61047. });
  61048. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  61049. /**
  61050. * Gets the blur kernel: kernel size of the blur pass.
  61051. * Only usefull if useKernelBlur = true
  61052. */
  61053. get: function () {
  61054. return this._blurKernel;
  61055. },
  61056. /**
  61057. * Sets the blur kernel: kernel size of the blur pass.
  61058. * Only usefull if useKernelBlur = true
  61059. */
  61060. set: function (value) {
  61061. if (this._blurKernel === value) {
  61062. return;
  61063. }
  61064. this._blurKernel = value;
  61065. this._disposeBlurPostProcesses();
  61066. },
  61067. enumerable: true,
  61068. configurable: true
  61069. });
  61070. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  61071. /**
  61072. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  61073. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  61074. */
  61075. get: function () {
  61076. return this._useKernelBlur;
  61077. },
  61078. /**
  61079. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  61080. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  61081. */
  61082. set: function (value) {
  61083. if (this._useKernelBlur === value) {
  61084. return;
  61085. }
  61086. this._useKernelBlur = value;
  61087. this._disposeBlurPostProcesses();
  61088. },
  61089. enumerable: true,
  61090. configurable: true
  61091. });
  61092. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  61093. /**
  61094. * Gets the depth scale used in ESM mode.
  61095. */
  61096. get: function () {
  61097. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  61098. },
  61099. /**
  61100. * Sets the depth scale used in ESM mode.
  61101. * This can override the scale stored on the light.
  61102. */
  61103. set: function (value) {
  61104. this._depthScale = value;
  61105. },
  61106. enumerable: true,
  61107. configurable: true
  61108. });
  61109. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  61110. /**
  61111. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  61112. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  61113. */
  61114. get: function () {
  61115. return this._filter;
  61116. },
  61117. /**
  61118. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  61119. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  61120. */
  61121. set: function (value) {
  61122. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  61123. if (this._light.needCube()) {
  61124. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  61125. this.useExponentialShadowMap = true;
  61126. return;
  61127. }
  61128. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  61129. this.useCloseExponentialShadowMap = true;
  61130. return;
  61131. }
  61132. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  61133. this.usePoissonSampling = true;
  61134. return;
  61135. }
  61136. }
  61137. // Weblg1 fallback for PCF.
  61138. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  61139. if (this._scene.getEngine().webGLVersion === 1) {
  61140. this.usePoissonSampling = true;
  61141. return;
  61142. }
  61143. }
  61144. if (this._filter === value) {
  61145. return;
  61146. }
  61147. this._filter = value;
  61148. this._disposeBlurPostProcesses();
  61149. this._applyFilterValues();
  61150. this._light._markMeshesAsLightDirty();
  61151. },
  61152. enumerable: true,
  61153. configurable: true
  61154. });
  61155. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  61156. /**
  61157. * Gets if the current filter is set to Poisson Sampling.
  61158. */
  61159. get: function () {
  61160. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  61161. },
  61162. /**
  61163. * Sets the current filter to Poisson Sampling.
  61164. */
  61165. set: function (value) {
  61166. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  61167. return;
  61168. }
  61169. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  61170. },
  61171. enumerable: true,
  61172. configurable: true
  61173. });
  61174. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  61175. /**
  61176. * Gets if the current filter is set to VSM.
  61177. * DEPRECATED. Should use useExponentialShadowMap instead.
  61178. */
  61179. get: function () {
  61180. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  61181. return this.useExponentialShadowMap;
  61182. },
  61183. /**
  61184. * Sets the current filter is to VSM.
  61185. * DEPRECATED. Should use useExponentialShadowMap instead.
  61186. */
  61187. set: function (value) {
  61188. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  61189. this.useExponentialShadowMap = value;
  61190. },
  61191. enumerable: true,
  61192. configurable: true
  61193. });
  61194. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  61195. /**
  61196. * Gets if the current filter is set to blurred VSM.
  61197. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  61198. */
  61199. get: function () {
  61200. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  61201. return this.useBlurExponentialShadowMap;
  61202. },
  61203. /**
  61204. * Sets the current filter is to blurred VSM.
  61205. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  61206. */
  61207. set: function (value) {
  61208. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  61209. this.useBlurExponentialShadowMap = value;
  61210. },
  61211. enumerable: true,
  61212. configurable: true
  61213. });
  61214. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  61215. /**
  61216. * Gets if the current filter is set to ESM.
  61217. */
  61218. get: function () {
  61219. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  61220. },
  61221. /**
  61222. * Sets the current filter is to ESM.
  61223. */
  61224. set: function (value) {
  61225. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  61226. return;
  61227. }
  61228. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61229. },
  61230. enumerable: true,
  61231. configurable: true
  61232. });
  61233. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  61234. /**
  61235. * Gets if the current filter is set to filtered ESM.
  61236. */
  61237. get: function () {
  61238. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  61239. },
  61240. /**
  61241. * Gets if the current filter is set to filtered ESM.
  61242. */
  61243. set: function (value) {
  61244. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  61245. return;
  61246. }
  61247. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61248. },
  61249. enumerable: true,
  61250. configurable: true
  61251. });
  61252. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  61253. /**
  61254. * Gets if the current filter is set to "close ESM" (using the inverse of the
  61255. * exponential to prevent steep falloff artifacts).
  61256. */
  61257. get: function () {
  61258. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  61259. },
  61260. /**
  61261. * Sets the current filter to "close ESM" (using the inverse of the
  61262. * exponential to prevent steep falloff artifacts).
  61263. */
  61264. set: function (value) {
  61265. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  61266. return;
  61267. }
  61268. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61269. },
  61270. enumerable: true,
  61271. configurable: true
  61272. });
  61273. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  61274. /**
  61275. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  61276. * exponential to prevent steep falloff artifacts).
  61277. */
  61278. get: function () {
  61279. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  61280. },
  61281. /**
  61282. * Sets the current filter to filtered "close ESM" (using the inverse of the
  61283. * exponential to prevent steep falloff artifacts).
  61284. */
  61285. set: function (value) {
  61286. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  61287. return;
  61288. }
  61289. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61290. },
  61291. enumerable: true,
  61292. configurable: true
  61293. });
  61294. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  61295. /**
  61296. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  61297. */
  61298. get: function () {
  61299. return this.filter === ShadowGenerator.FILTER_PCF;
  61300. },
  61301. /**
  61302. * Sets the current filter to "PCF" (percentage closer filtering).
  61303. */
  61304. set: function (value) {
  61305. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  61306. return;
  61307. }
  61308. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  61309. },
  61310. enumerable: true,
  61311. configurable: true
  61312. });
  61313. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  61314. /**
  61315. * Gets the PCF or PCSS Quality.
  61316. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  61317. */
  61318. get: function () {
  61319. return this._filteringQuality;
  61320. },
  61321. /**
  61322. * Sets the PCF or PCSS Quality.
  61323. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  61324. */
  61325. set: function (filteringQuality) {
  61326. this._filteringQuality = filteringQuality;
  61327. },
  61328. enumerable: true,
  61329. configurable: true
  61330. });
  61331. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  61332. /**
  61333. * Gets if the current filter is set to "PCSS" (contact hardening).
  61334. */
  61335. get: function () {
  61336. return this.filter === ShadowGenerator.FILTER_PCSS;
  61337. },
  61338. /**
  61339. * Sets the current filter to "PCSS" (contact hardening).
  61340. */
  61341. set: function (value) {
  61342. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  61343. return;
  61344. }
  61345. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  61346. },
  61347. enumerable: true,
  61348. configurable: true
  61349. });
  61350. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  61351. /**
  61352. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  61353. * Using a ratio helps keeping shape stability independently of the map size.
  61354. *
  61355. * It does not account for the light projection as it was having too much
  61356. * instability during the light setup or during light position changes.
  61357. *
  61358. * Only valid if useContactHardeningShadow is true.
  61359. */
  61360. get: function () {
  61361. return this._contactHardeningLightSizeUVRatio;
  61362. },
  61363. /**
  61364. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  61365. * Using a ratio helps keeping shape stability independently of the map size.
  61366. *
  61367. * It does not account for the light projection as it was having too much
  61368. * instability during the light setup or during light position changes.
  61369. *
  61370. * Only valid if useContactHardeningShadow is true.
  61371. */
  61372. set: function (contactHardeningLightSizeUVRatio) {
  61373. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  61374. },
  61375. enumerable: true,
  61376. configurable: true
  61377. });
  61378. /**
  61379. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  61380. * 0 means strongest and 1 would means no shadow.
  61381. * @returns the darkness.
  61382. */
  61383. ShadowGenerator.prototype.getDarkness = function () {
  61384. return this._darkness;
  61385. };
  61386. /**
  61387. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  61388. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  61389. * @returns the shadow generator allowing fluent coding.
  61390. */
  61391. ShadowGenerator.prototype.setDarkness = function (darkness) {
  61392. if (darkness >= 1.0)
  61393. this._darkness = 1.0;
  61394. else if (darkness <= 0.0)
  61395. this._darkness = 0.0;
  61396. else
  61397. this._darkness = darkness;
  61398. return this;
  61399. };
  61400. /**
  61401. * Sets the ability to have transparent shadow (boolean).
  61402. * @param transparent True if transparent else False
  61403. * @returns the shadow generator allowing fluent coding
  61404. */
  61405. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  61406. this._transparencyShadow = transparent;
  61407. return this;
  61408. };
  61409. /**
  61410. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  61411. * @returns The render target texture if present otherwise, null
  61412. */
  61413. ShadowGenerator.prototype.getShadowMap = function () {
  61414. return this._shadowMap;
  61415. };
  61416. /**
  61417. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  61418. * @returns The render target texture if the shadow map is present otherwise, null
  61419. */
  61420. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  61421. if (this._shadowMap2) {
  61422. return this._shadowMap2;
  61423. }
  61424. return this._shadowMap;
  61425. };
  61426. /**
  61427. * Helper function to add a mesh and its descendants to the list of shadow casters.
  61428. * @param mesh Mesh to add
  61429. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  61430. * @returns the Shadow Generator itself
  61431. */
  61432. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  61433. if (includeDescendants === void 0) { includeDescendants = true; }
  61434. if (!this._shadowMap) {
  61435. return this;
  61436. }
  61437. if (!this._shadowMap.renderList) {
  61438. this._shadowMap.renderList = [];
  61439. }
  61440. this._shadowMap.renderList.push(mesh);
  61441. if (includeDescendants) {
  61442. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  61443. }
  61444. return this;
  61445. var _a;
  61446. };
  61447. /**
  61448. * Helper function to remove a mesh and its descendants from the list of shadow casters
  61449. * @param mesh Mesh to remove
  61450. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  61451. * @returns the Shadow Generator itself
  61452. */
  61453. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  61454. if (includeDescendants === void 0) { includeDescendants = true; }
  61455. if (!this._shadowMap || !this._shadowMap.renderList) {
  61456. return this;
  61457. }
  61458. var index = this._shadowMap.renderList.indexOf(mesh);
  61459. if (index !== -1) {
  61460. this._shadowMap.renderList.splice(index, 1);
  61461. }
  61462. if (includeDescendants) {
  61463. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  61464. var child = _a[_i];
  61465. this.removeShadowCaster(child);
  61466. }
  61467. }
  61468. return this;
  61469. };
  61470. /**
  61471. * Returns the associated light object.
  61472. * @returns the light generating the shadow
  61473. */
  61474. ShadowGenerator.prototype.getLight = function () {
  61475. return this._light;
  61476. };
  61477. ShadowGenerator.prototype._initializeGenerator = function () {
  61478. this._light._markMeshesAsLightDirty();
  61479. this._initializeShadowMap();
  61480. };
  61481. ShadowGenerator.prototype._initializeShadowMap = function () {
  61482. var _this = this;
  61483. // Render target
  61484. var engine = this._scene.getEngine();
  61485. if (engine.webGLVersion > 1) {
  61486. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  61487. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  61488. }
  61489. else {
  61490. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  61491. }
  61492. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61493. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61494. this._shadowMap.anisotropicFilteringLevel = 1;
  61495. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61496. this._shadowMap.renderParticles = false;
  61497. this._shadowMap.ignoreCameraViewport = true;
  61498. // Record Face Index before render.
  61499. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  61500. _this._currentFaceIndex = faceIndex;
  61501. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61502. engine.setColorWrite(false);
  61503. }
  61504. });
  61505. // Custom render function.
  61506. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  61507. // Blur if required afer render.
  61508. this._shadowMap.onAfterUnbindObservable.add(function () {
  61509. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61510. engine.setColorWrite(true);
  61511. }
  61512. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  61513. return;
  61514. }
  61515. var shadowMap = _this.getShadowMapForRendering();
  61516. if (shadowMap) {
  61517. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  61518. }
  61519. });
  61520. // Clear according to the chosen filter.
  61521. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  61522. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  61523. this._shadowMap.onClearObservable.add(function (engine) {
  61524. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61525. engine.clear(clearOne, false, true, false);
  61526. }
  61527. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  61528. engine.clear(clearZero, true, true, false);
  61529. }
  61530. else {
  61531. engine.clear(clearOne, true, true, false);
  61532. }
  61533. });
  61534. };
  61535. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  61536. var _this = this;
  61537. var engine = this._scene.getEngine();
  61538. var targetSize = this._mapSize / this.blurScale;
  61539. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  61540. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  61541. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61542. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61543. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61544. }
  61545. if (this.useKernelBlur) {
  61546. 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);
  61547. this._kernelBlurXPostprocess.width = targetSize;
  61548. this._kernelBlurXPostprocess.height = targetSize;
  61549. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  61550. effect.setTexture("textureSampler", _this._shadowMap);
  61551. });
  61552. 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);
  61553. this._kernelBlurXPostprocess.autoClear = false;
  61554. this._kernelBlurYPostprocess.autoClear = false;
  61555. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  61556. this._kernelBlurXPostprocess.packedFloat = true;
  61557. this._kernelBlurYPostprocess.packedFloat = true;
  61558. }
  61559. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  61560. }
  61561. else {
  61562. 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);
  61563. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  61564. effect.setFloat2("screenSize", targetSize, targetSize);
  61565. effect.setTexture("textureSampler", _this._shadowMap);
  61566. });
  61567. this._boxBlurPostprocess.autoClear = false;
  61568. this._blurPostProcesses = [this._boxBlurPostprocess];
  61569. }
  61570. };
  61571. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  61572. var index;
  61573. var engine = this._scene.getEngine();
  61574. if (depthOnlySubMeshes.length) {
  61575. engine.setColorWrite(false);
  61576. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  61577. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  61578. }
  61579. engine.setColorWrite(true);
  61580. }
  61581. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61582. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  61583. }
  61584. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61585. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  61586. }
  61587. if (this._transparencyShadow) {
  61588. for (index = 0; index < transparentSubMeshes.length; index++) {
  61589. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  61590. }
  61591. }
  61592. };
  61593. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  61594. var _this = this;
  61595. var mesh = subMesh.getRenderingMesh();
  61596. var scene = this._scene;
  61597. var engine = scene.getEngine();
  61598. var material = subMesh.getMaterial();
  61599. if (!material) {
  61600. return;
  61601. }
  61602. // Culling
  61603. engine.setState(material.backFaceCulling);
  61604. // Managing instances
  61605. var batch = mesh._getInstancesRenderList(subMesh._id);
  61606. if (batch.mustReturn) {
  61607. return;
  61608. }
  61609. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  61610. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  61611. engine.enableEffect(this._effect);
  61612. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  61613. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  61614. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  61615. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  61616. this._effect.setVector3("lightData", this._cachedDirection);
  61617. }
  61618. else {
  61619. this._effect.setVector3("lightData", this._cachedPosition);
  61620. }
  61621. if (scene.activeCamera) {
  61622. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  61623. }
  61624. // Alpha test
  61625. if (material && material.needAlphaTesting()) {
  61626. var alphaTexture = material.getAlphaTestTexture();
  61627. if (alphaTexture) {
  61628. this._effect.setTexture("diffuseSampler", alphaTexture);
  61629. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  61630. }
  61631. }
  61632. // Bones
  61633. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61634. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  61635. }
  61636. if (this.forceBackFacesOnly) {
  61637. engine.setState(true, 0, false, true);
  61638. }
  61639. // Draw
  61640. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  61641. if (this.forceBackFacesOnly) {
  61642. engine.setState(true, 0, false, false);
  61643. }
  61644. }
  61645. else {
  61646. // Need to reset refresh rate of the shadowMap
  61647. if (this._shadowMap) {
  61648. this._shadowMap.resetRefreshCounter();
  61649. }
  61650. }
  61651. };
  61652. ShadowGenerator.prototype._applyFilterValues = function () {
  61653. if (!this._shadowMap) {
  61654. return;
  61655. }
  61656. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  61657. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61658. }
  61659. else {
  61660. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61661. }
  61662. };
  61663. /**
  61664. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  61665. * @param onCompiled Callback triggered at the and of the effects compilation
  61666. * @param options Sets of optional options forcing the compilation with different modes
  61667. */
  61668. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  61669. var _this = this;
  61670. var localOptions = __assign({ useInstances: false }, options);
  61671. var shadowMap = this.getShadowMap();
  61672. if (!shadowMap) {
  61673. if (onCompiled) {
  61674. onCompiled(this);
  61675. }
  61676. return;
  61677. }
  61678. var renderList = shadowMap.renderList;
  61679. if (!renderList) {
  61680. if (onCompiled) {
  61681. onCompiled(this);
  61682. }
  61683. return;
  61684. }
  61685. var subMeshes = new Array();
  61686. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  61687. var mesh = renderList_1[_i];
  61688. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  61689. }
  61690. if (subMeshes.length === 0) {
  61691. if (onCompiled) {
  61692. onCompiled(this);
  61693. }
  61694. return;
  61695. }
  61696. var currentIndex = 0;
  61697. var checkReady = function () {
  61698. if (!_this._scene || !_this._scene.getEngine()) {
  61699. return;
  61700. }
  61701. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  61702. currentIndex++;
  61703. if (currentIndex >= subMeshes.length) {
  61704. if (onCompiled) {
  61705. onCompiled(_this);
  61706. }
  61707. return;
  61708. }
  61709. }
  61710. setTimeout(checkReady, 16);
  61711. };
  61712. checkReady();
  61713. };
  61714. /**
  61715. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  61716. * @param options Sets of optional options forcing the compilation with different modes
  61717. * @returns A promise that resolves when the compilation completes
  61718. */
  61719. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  61720. var _this = this;
  61721. return new Promise(function (resolve) {
  61722. _this.forceCompilation(function () {
  61723. resolve();
  61724. }, options);
  61725. });
  61726. };
  61727. /**
  61728. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  61729. * @param subMesh The submesh we want to render in the shadow map
  61730. * @param useInstances Defines wether will draw in the map using instances
  61731. * @returns true if ready otherwise, false
  61732. */
  61733. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  61734. var defines = [];
  61735. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  61736. defines.push("#define FLOAT");
  61737. }
  61738. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  61739. defines.push("#define ESM");
  61740. }
  61741. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  61742. defines.push("#define DEPTHTEXTURE");
  61743. }
  61744. var attribs = [BABYLON.VertexBuffer.PositionKind];
  61745. var mesh = subMesh.getMesh();
  61746. var material = subMesh.getMaterial();
  61747. // Normal bias.
  61748. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  61749. attribs.push(BABYLON.VertexBuffer.NormalKind);
  61750. defines.push("#define NORMAL");
  61751. if (mesh.nonUniformScaling) {
  61752. defines.push("#define NONUNIFORMSCALING");
  61753. }
  61754. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  61755. defines.push("#define DIRECTIONINLIGHTDATA");
  61756. }
  61757. }
  61758. // Alpha test
  61759. if (material && material.needAlphaTesting()) {
  61760. var alphaTexture = material.getAlphaTestTexture();
  61761. if (alphaTexture) {
  61762. defines.push("#define ALPHATEST");
  61763. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61764. attribs.push(BABYLON.VertexBuffer.UVKind);
  61765. defines.push("#define UV1");
  61766. }
  61767. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61768. if (alphaTexture.coordinatesIndex === 1) {
  61769. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61770. defines.push("#define UV2");
  61771. }
  61772. }
  61773. }
  61774. }
  61775. // Bones
  61776. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61777. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61778. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61779. if (mesh.numBoneInfluencers > 4) {
  61780. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61781. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61782. }
  61783. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61784. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  61785. }
  61786. else {
  61787. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61788. }
  61789. // Instances
  61790. if (useInstances) {
  61791. defines.push("#define INSTANCES");
  61792. attribs.push("world0");
  61793. attribs.push("world1");
  61794. attribs.push("world2");
  61795. attribs.push("world3");
  61796. }
  61797. // Get correct effect
  61798. var join = defines.join("\n");
  61799. if (this._cachedDefines !== join) {
  61800. this._cachedDefines = join;
  61801. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  61802. }
  61803. if (!this._effect.isReady()) {
  61804. return false;
  61805. }
  61806. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  61807. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  61808. this._initializeBlurRTTAndPostProcesses();
  61809. }
  61810. }
  61811. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  61812. return false;
  61813. }
  61814. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  61815. return false;
  61816. }
  61817. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  61818. return false;
  61819. }
  61820. return true;
  61821. };
  61822. /**
  61823. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  61824. * @param defines Defines of the material we want to update
  61825. * @param lightIndex Index of the light in the enabled light list of the material
  61826. */
  61827. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  61828. var scene = this._scene;
  61829. var light = this._light;
  61830. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  61831. return;
  61832. }
  61833. defines["SHADOW" + lightIndex] = true;
  61834. if (this.useContactHardeningShadow) {
  61835. defines["SHADOWPCSS" + lightIndex] = true;
  61836. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  61837. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  61838. }
  61839. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  61840. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  61841. }
  61842. // else default to high.
  61843. }
  61844. if (this.usePercentageCloserFiltering) {
  61845. defines["SHADOWPCF" + lightIndex] = true;
  61846. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  61847. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  61848. }
  61849. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  61850. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  61851. }
  61852. // else default to high.
  61853. }
  61854. else if (this.usePoissonSampling) {
  61855. defines["SHADOWPOISSON" + lightIndex] = true;
  61856. }
  61857. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  61858. defines["SHADOWESM" + lightIndex] = true;
  61859. }
  61860. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  61861. defines["SHADOWCLOSEESM" + lightIndex] = true;
  61862. }
  61863. if (light.needCube()) {
  61864. defines["SHADOWCUBE" + lightIndex] = true;
  61865. }
  61866. };
  61867. /**
  61868. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  61869. * defined in the generator but impacting the effect).
  61870. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  61871. * @param effect The effect we are binfing the information for
  61872. */
  61873. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  61874. var light = this._light;
  61875. var scene = this._scene;
  61876. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  61877. return;
  61878. }
  61879. var camera = scene.activeCamera;
  61880. if (!camera) {
  61881. return;
  61882. }
  61883. var shadowMap = this.getShadowMap();
  61884. if (!shadowMap) {
  61885. return;
  61886. }
  61887. if (!light.needCube()) {
  61888. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  61889. }
  61890. // Only PCF uses depth stencil texture.
  61891. if (this._filter === ShadowGenerator.FILTER_PCF) {
  61892. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61893. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  61894. }
  61895. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  61896. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61897. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  61898. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  61899. }
  61900. else {
  61901. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61902. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  61903. }
  61904. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  61905. };
  61906. /**
  61907. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  61908. * (eq to shadow prjection matrix * light transform matrix)
  61909. * @returns The transform matrix used to create the shadow map
  61910. */
  61911. ShadowGenerator.prototype.getTransformMatrix = function () {
  61912. var scene = this._scene;
  61913. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  61914. return this._transformMatrix;
  61915. }
  61916. this._currentRenderID = scene.getRenderId();
  61917. this._currentFaceIndexCache = this._currentFaceIndex;
  61918. var lightPosition = this._light.position;
  61919. if (this._light.computeTransformedInformation()) {
  61920. lightPosition = this._light.transformedPosition;
  61921. }
  61922. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  61923. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  61924. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  61925. }
  61926. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  61927. this._cachedPosition.copyFrom(lightPosition);
  61928. this._cachedDirection.copyFrom(this._lightDirection);
  61929. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  61930. var shadowMap = this.getShadowMap();
  61931. if (shadowMap) {
  61932. var renderList = shadowMap.renderList;
  61933. if (renderList) {
  61934. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  61935. }
  61936. }
  61937. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  61938. }
  61939. return this._transformMatrix;
  61940. };
  61941. /**
  61942. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  61943. * Cube and 2D textures for instance.
  61944. */
  61945. ShadowGenerator.prototype.recreateShadowMap = function () {
  61946. var shadowMap = this._shadowMap;
  61947. if (!shadowMap) {
  61948. return;
  61949. }
  61950. // Track render list.
  61951. var renderList = shadowMap.renderList;
  61952. // Clean up existing data.
  61953. this._disposeRTTandPostProcesses();
  61954. // Reinitializes.
  61955. this._initializeGenerator();
  61956. // Reaffect the filter to ensure a correct fallback if necessary.
  61957. this.filter = this.filter;
  61958. // Reaffect the filter.
  61959. this._applyFilterValues();
  61960. // Reaffect Render List.
  61961. this._shadowMap.renderList = renderList;
  61962. };
  61963. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  61964. if (this._shadowMap2) {
  61965. this._shadowMap2.dispose();
  61966. this._shadowMap2 = null;
  61967. }
  61968. if (this._boxBlurPostprocess) {
  61969. this._boxBlurPostprocess.dispose();
  61970. this._boxBlurPostprocess = null;
  61971. }
  61972. if (this._kernelBlurXPostprocess) {
  61973. this._kernelBlurXPostprocess.dispose();
  61974. this._kernelBlurXPostprocess = null;
  61975. }
  61976. if (this._kernelBlurYPostprocess) {
  61977. this._kernelBlurYPostprocess.dispose();
  61978. this._kernelBlurYPostprocess = null;
  61979. }
  61980. this._blurPostProcesses = [];
  61981. };
  61982. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  61983. if (this._shadowMap) {
  61984. this._shadowMap.dispose();
  61985. this._shadowMap = null;
  61986. }
  61987. this._disposeBlurPostProcesses();
  61988. };
  61989. /**
  61990. * Disposes the ShadowGenerator.
  61991. * Returns nothing.
  61992. */
  61993. ShadowGenerator.prototype.dispose = function () {
  61994. this._disposeRTTandPostProcesses();
  61995. if (this._light) {
  61996. this._light._shadowGenerator = null;
  61997. this._light._markMeshesAsLightDirty();
  61998. }
  61999. };
  62000. /**
  62001. * Serializes the shadow generator setup to a json object.
  62002. * @returns The serialized JSON object
  62003. */
  62004. ShadowGenerator.prototype.serialize = function () {
  62005. var serializationObject = {};
  62006. var shadowMap = this.getShadowMap();
  62007. if (!shadowMap) {
  62008. return serializationObject;
  62009. }
  62010. serializationObject.lightId = this._light.id;
  62011. serializationObject.mapSize = shadowMap.getRenderSize();
  62012. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  62013. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  62014. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  62015. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  62016. serializationObject.usePoissonSampling = this.usePoissonSampling;
  62017. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  62018. serializationObject.depthScale = this.depthScale;
  62019. serializationObject.darkness = this.getDarkness();
  62020. serializationObject.blurBoxOffset = this.blurBoxOffset;
  62021. serializationObject.blurKernel = this.blurKernel;
  62022. serializationObject.blurScale = this.blurScale;
  62023. serializationObject.useKernelBlur = this.useKernelBlur;
  62024. serializationObject.transparencyShadow = this._transparencyShadow;
  62025. serializationObject.bias = this.bias;
  62026. serializationObject.normalBias = this.normalBias;
  62027. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  62028. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  62029. serializationObject.filteringQuality = this.filteringQuality;
  62030. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  62031. serializationObject.renderList = [];
  62032. if (shadowMap.renderList) {
  62033. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  62034. var mesh = shadowMap.renderList[meshIndex];
  62035. serializationObject.renderList.push(mesh.id);
  62036. }
  62037. }
  62038. return serializationObject;
  62039. };
  62040. /**
  62041. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  62042. * @param parsedShadowGenerator The JSON object to parse
  62043. * @param scene The scene to create the shadow map for
  62044. * @returns The parsed shadow generator
  62045. */
  62046. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  62047. //casting to point light, as light is missing the position attr and typescript complains.
  62048. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  62049. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  62050. var shadowMap = shadowGenerator.getShadowMap();
  62051. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  62052. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  62053. meshes.forEach(function (mesh) {
  62054. if (!shadowMap) {
  62055. return;
  62056. }
  62057. if (!shadowMap.renderList) {
  62058. shadowMap.renderList = [];
  62059. }
  62060. shadowMap.renderList.push(mesh);
  62061. });
  62062. }
  62063. if (parsedShadowGenerator.usePoissonSampling) {
  62064. shadowGenerator.usePoissonSampling = true;
  62065. }
  62066. else if (parsedShadowGenerator.useExponentialShadowMap) {
  62067. shadowGenerator.useExponentialShadowMap = true;
  62068. }
  62069. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  62070. shadowGenerator.useBlurExponentialShadowMap = true;
  62071. }
  62072. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  62073. shadowGenerator.useCloseExponentialShadowMap = true;
  62074. }
  62075. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  62076. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  62077. }
  62078. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  62079. shadowGenerator.usePercentageCloserFiltering = true;
  62080. }
  62081. else if (parsedShadowGenerator.useContactHardeningShadow) {
  62082. shadowGenerator.useContactHardeningShadow = true;
  62083. }
  62084. if (parsedShadowGenerator.filteringQuality) {
  62085. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  62086. }
  62087. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  62088. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  62089. }
  62090. else if (parsedShadowGenerator.useVarianceShadowMap) {
  62091. shadowGenerator.useExponentialShadowMap = true;
  62092. }
  62093. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  62094. shadowGenerator.useBlurExponentialShadowMap = true;
  62095. }
  62096. if (parsedShadowGenerator.depthScale) {
  62097. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  62098. }
  62099. if (parsedShadowGenerator.blurScale) {
  62100. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  62101. }
  62102. if (parsedShadowGenerator.blurBoxOffset) {
  62103. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  62104. }
  62105. if (parsedShadowGenerator.useKernelBlur) {
  62106. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  62107. }
  62108. if (parsedShadowGenerator.blurKernel) {
  62109. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  62110. }
  62111. if (parsedShadowGenerator.bias !== undefined) {
  62112. shadowGenerator.bias = parsedShadowGenerator.bias;
  62113. }
  62114. if (parsedShadowGenerator.normalBias !== undefined) {
  62115. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  62116. }
  62117. if (parsedShadowGenerator.darkness) {
  62118. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  62119. }
  62120. if (parsedShadowGenerator.transparencyShadow) {
  62121. shadowGenerator.setTransparencyShadow(true);
  62122. }
  62123. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  62124. return shadowGenerator;
  62125. };
  62126. /**
  62127. * Shadow generator mode None: no filtering applied.
  62128. */
  62129. ShadowGenerator.FILTER_NONE = 0;
  62130. /**
  62131. * Shadow generator mode ESM: Exponential Shadow Mapping.
  62132. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62133. */
  62134. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  62135. /**
  62136. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  62137. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  62138. */
  62139. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  62140. /**
  62141. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  62142. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62143. */
  62144. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  62145. /**
  62146. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  62147. * edge artifacts on steep falloff.
  62148. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62149. */
  62150. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  62151. /**
  62152. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  62153. * edge artifacts on steep falloff.
  62154. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62155. */
  62156. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  62157. /**
  62158. * Shadow generator mode PCF: Percentage Closer Filtering
  62159. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  62160. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  62161. */
  62162. ShadowGenerator.FILTER_PCF = 6;
  62163. /**
  62164. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  62165. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  62166. * Contact Hardening
  62167. */
  62168. ShadowGenerator.FILTER_PCSS = 7;
  62169. /**
  62170. * Reserved for PCF and PCSS
  62171. * Highest Quality.
  62172. *
  62173. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  62174. *
  62175. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  62176. */
  62177. ShadowGenerator.QUALITY_HIGH = 0;
  62178. /**
  62179. * Reserved for PCF and PCSS
  62180. * Good tradeoff for quality/perf cross devices
  62181. *
  62182. * Execute PCF on a 3*3 kernel.
  62183. *
  62184. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  62185. */
  62186. ShadowGenerator.QUALITY_MEDIUM = 1;
  62187. /**
  62188. * Reserved for PCF and PCSS
  62189. * The lowest quality but the fastest.
  62190. *
  62191. * Execute PCF on a 1*1 kernel.
  62192. *
  62193. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  62194. */
  62195. ShadowGenerator.QUALITY_LOW = 2;
  62196. return ShadowGenerator;
  62197. }());
  62198. BABYLON.ShadowGenerator = ShadowGenerator;
  62199. })(BABYLON || (BABYLON = {}));
  62200. //# sourceMappingURL=babylon.shadowGenerator.js.map
  62201. "use strict";
  62202. var BABYLON;
  62203. (function (BABYLON) {
  62204. var DefaultLoadingScreen = /** @class */ (function () {
  62205. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  62206. if (_loadingText === void 0) { _loadingText = ""; }
  62207. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  62208. var _this = this;
  62209. this._renderingCanvas = _renderingCanvas;
  62210. this._loadingText = _loadingText;
  62211. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  62212. // Resize
  62213. this._resizeLoadingUI = function () {
  62214. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  62215. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  62216. if (!_this._loadingDiv) {
  62217. return;
  62218. }
  62219. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  62220. _this._loadingDiv.style.left = canvasRect.left + "px";
  62221. _this._loadingDiv.style.top = canvasRect.top + "px";
  62222. _this._loadingDiv.style.width = canvasRect.width + "px";
  62223. _this._loadingDiv.style.height = canvasRect.height + "px";
  62224. };
  62225. }
  62226. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  62227. if (this._loadingDiv) {
  62228. // Do not add a loading screen if there is already one
  62229. return;
  62230. }
  62231. this._loadingDiv = document.createElement("div");
  62232. this._loadingDiv.id = "babylonjsLoadingDiv";
  62233. this._loadingDiv.style.opacity = "0";
  62234. this._loadingDiv.style.transition = "opacity 1.5s ease";
  62235. this._loadingDiv.style.pointerEvents = "none";
  62236. // Loading text
  62237. this._loadingTextDiv = document.createElement("div");
  62238. this._loadingTextDiv.style.position = "absolute";
  62239. this._loadingTextDiv.style.left = "0";
  62240. this._loadingTextDiv.style.top = "50%";
  62241. this._loadingTextDiv.style.marginTop = "80px";
  62242. this._loadingTextDiv.style.width = "100%";
  62243. this._loadingTextDiv.style.height = "20px";
  62244. this._loadingTextDiv.style.fontFamily = "Arial";
  62245. this._loadingTextDiv.style.fontSize = "14px";
  62246. this._loadingTextDiv.style.color = "white";
  62247. this._loadingTextDiv.style.textAlign = "center";
  62248. this._loadingTextDiv.innerHTML = "Loading";
  62249. this._loadingDiv.appendChild(this._loadingTextDiv);
  62250. //set the predefined text
  62251. this._loadingTextDiv.innerHTML = this._loadingText;
  62252. // Generating keyframes
  62253. var style = document.createElement('style');
  62254. style.type = 'text/css';
  62255. 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 }";
  62256. style.innerHTML = keyFrames;
  62257. document.getElementsByTagName('head')[0].appendChild(style);
  62258. // Loading img
  62259. var imgBack = new Image();
  62260. 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";
  62261. imgBack.style.position = "absolute";
  62262. imgBack.style.left = "50%";
  62263. imgBack.style.top = "50%";
  62264. imgBack.style.marginLeft = "-60px";
  62265. imgBack.style.marginTop = "-60px";
  62266. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  62267. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  62268. imgBack.style.transformOrigin = "50% 50%";
  62269. imgBack.style.webkitTransformOrigin = "50% 50%";
  62270. this._loadingDiv.appendChild(imgBack);
  62271. this._resizeLoadingUI();
  62272. window.addEventListener("resize", this._resizeLoadingUI);
  62273. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  62274. document.body.appendChild(this._loadingDiv);
  62275. this._loadingDiv.style.opacity = "1";
  62276. };
  62277. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  62278. var _this = this;
  62279. if (!this._loadingDiv) {
  62280. return;
  62281. }
  62282. var onTransitionEnd = function () {
  62283. if (!_this._loadingDiv) {
  62284. return;
  62285. }
  62286. document.body.removeChild(_this._loadingDiv);
  62287. window.removeEventListener("resize", _this._resizeLoadingUI);
  62288. _this._loadingDiv = null;
  62289. };
  62290. this._loadingDiv.style.opacity = "0";
  62291. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  62292. };
  62293. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  62294. set: function (text) {
  62295. this._loadingText = text;
  62296. if (this._loadingTextDiv) {
  62297. this._loadingTextDiv.innerHTML = this._loadingText;
  62298. }
  62299. },
  62300. enumerable: true,
  62301. configurable: true
  62302. });
  62303. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  62304. get: function () {
  62305. return this._loadingDivBackgroundColor;
  62306. },
  62307. set: function (color) {
  62308. this._loadingDivBackgroundColor = color;
  62309. if (!this._loadingDiv) {
  62310. return;
  62311. }
  62312. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  62313. },
  62314. enumerable: true,
  62315. configurable: true
  62316. });
  62317. return DefaultLoadingScreen;
  62318. }());
  62319. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  62320. })(BABYLON || (BABYLON = {}));
  62321. //# sourceMappingURL=babylon.loadingScreen.js.map
  62322. "use strict";
  62323. var BABYLON;
  62324. (function (BABYLON) {
  62325. var SceneLoaderProgressEvent = /** @class */ (function () {
  62326. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  62327. this.lengthComputable = lengthComputable;
  62328. this.loaded = loaded;
  62329. this.total = total;
  62330. }
  62331. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  62332. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  62333. };
  62334. return SceneLoaderProgressEvent;
  62335. }());
  62336. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  62337. var SceneLoader = /** @class */ (function () {
  62338. function SceneLoader() {
  62339. }
  62340. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  62341. get: function () {
  62342. return 0;
  62343. },
  62344. enumerable: true,
  62345. configurable: true
  62346. });
  62347. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  62348. get: function () {
  62349. return 1;
  62350. },
  62351. enumerable: true,
  62352. configurable: true
  62353. });
  62354. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  62355. get: function () {
  62356. return 2;
  62357. },
  62358. enumerable: true,
  62359. configurable: true
  62360. });
  62361. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  62362. get: function () {
  62363. return 3;
  62364. },
  62365. enumerable: true,
  62366. configurable: true
  62367. });
  62368. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  62369. get: function () {
  62370. return SceneLoader._ForceFullSceneLoadingForIncremental;
  62371. },
  62372. set: function (value) {
  62373. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  62374. },
  62375. enumerable: true,
  62376. configurable: true
  62377. });
  62378. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  62379. get: function () {
  62380. return SceneLoader._ShowLoadingScreen;
  62381. },
  62382. set: function (value) {
  62383. SceneLoader._ShowLoadingScreen = value;
  62384. },
  62385. enumerable: true,
  62386. configurable: true
  62387. });
  62388. Object.defineProperty(SceneLoader, "loggingLevel", {
  62389. get: function () {
  62390. return SceneLoader._loggingLevel;
  62391. },
  62392. set: function (value) {
  62393. SceneLoader._loggingLevel = value;
  62394. },
  62395. enumerable: true,
  62396. configurable: true
  62397. });
  62398. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  62399. get: function () {
  62400. return SceneLoader._CleanBoneMatrixWeights;
  62401. },
  62402. set: function (value) {
  62403. SceneLoader._CleanBoneMatrixWeights = value;
  62404. },
  62405. enumerable: true,
  62406. configurable: true
  62407. });
  62408. SceneLoader._getDefaultPlugin = function () {
  62409. return SceneLoader._registeredPlugins[".babylon"];
  62410. };
  62411. SceneLoader._getPluginForExtension = function (extension) {
  62412. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  62413. if (registeredPlugin) {
  62414. return registeredPlugin;
  62415. }
  62416. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  62417. return SceneLoader._getDefaultPlugin();
  62418. };
  62419. SceneLoader._getPluginForDirectLoad = function (data) {
  62420. for (var extension in SceneLoader._registeredPlugins) {
  62421. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  62422. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  62423. return SceneLoader._registeredPlugins[extension];
  62424. }
  62425. }
  62426. return SceneLoader._getDefaultPlugin();
  62427. };
  62428. SceneLoader._getPluginForFilename = function (sceneFilename) {
  62429. if (sceneFilename.name) {
  62430. sceneFilename = sceneFilename.name;
  62431. }
  62432. var queryStringPosition = sceneFilename.indexOf("?");
  62433. if (queryStringPosition !== -1) {
  62434. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  62435. }
  62436. var dotPosition = sceneFilename.lastIndexOf(".");
  62437. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  62438. return SceneLoader._getPluginForExtension(extension);
  62439. };
  62440. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  62441. SceneLoader._getDirectLoad = function (sceneFilename) {
  62442. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  62443. return sceneFilename.substr(5);
  62444. }
  62445. return null;
  62446. };
  62447. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  62448. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  62449. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  62450. var plugin;
  62451. if (registeredPlugin.plugin.createPlugin) {
  62452. plugin = registeredPlugin.plugin.createPlugin();
  62453. }
  62454. else {
  62455. plugin = registeredPlugin.plugin;
  62456. }
  62457. var useArrayBuffer = registeredPlugin.isBinary;
  62458. var database;
  62459. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  62460. var dataCallback = function (data, responseURL) {
  62461. if (scene.isDisposed) {
  62462. onError("Scene has been disposed");
  62463. return;
  62464. }
  62465. scene.database = database;
  62466. onSuccess(plugin, data, responseURL);
  62467. };
  62468. var request = null;
  62469. var pluginDisposed = false;
  62470. var onDisposeObservable = plugin.onDisposeObservable;
  62471. if (onDisposeObservable) {
  62472. onDisposeObservable.add(function () {
  62473. pluginDisposed = true;
  62474. if (request) {
  62475. request.abort();
  62476. request = null;
  62477. }
  62478. onDispose();
  62479. });
  62480. }
  62481. var manifestChecked = function () {
  62482. if (pluginDisposed) {
  62483. return;
  62484. }
  62485. var url = rootUrl + sceneFilename;
  62486. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  62487. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  62488. } : undefined, database, useArrayBuffer, function (request, exception) {
  62489. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  62490. });
  62491. };
  62492. if (directLoad) {
  62493. dataCallback(directLoad);
  62494. return plugin;
  62495. }
  62496. if (rootUrl.indexOf("file:") === -1) {
  62497. if (scene.getEngine().enableOfflineSupport) {
  62498. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  62499. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  62500. }
  62501. else {
  62502. manifestChecked();
  62503. }
  62504. }
  62505. else {
  62506. var fileOrString = sceneFilename;
  62507. if (fileOrString.name) {
  62508. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  62509. }
  62510. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  62511. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  62512. }
  62513. else {
  62514. onError("Unable to find file named " + sceneFilename);
  62515. }
  62516. }
  62517. return plugin;
  62518. };
  62519. // Public functions
  62520. SceneLoader.GetPluginForExtension = function (extension) {
  62521. return SceneLoader._getPluginForExtension(extension).plugin;
  62522. };
  62523. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  62524. return !!SceneLoader._registeredPlugins[extension];
  62525. };
  62526. SceneLoader.RegisterPlugin = function (plugin) {
  62527. if (typeof plugin.extensions === "string") {
  62528. var extension = plugin.extensions;
  62529. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  62530. plugin: plugin,
  62531. isBinary: false
  62532. };
  62533. }
  62534. else {
  62535. var extensions = plugin.extensions;
  62536. Object.keys(extensions).forEach(function (extension) {
  62537. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  62538. plugin: plugin,
  62539. isBinary: extensions[extension].isBinary
  62540. };
  62541. });
  62542. }
  62543. };
  62544. /**
  62545. * Import meshes into a scene
  62546. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  62547. * @param rootUrl a string that defines the root url for scene and resources
  62548. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62549. * @param scene the instance of BABYLON.Scene to append to
  62550. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  62551. * @param onProgress a callback with a progress event for each file being loaded
  62552. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62553. * @param pluginExtension the extension used to determine the plugin
  62554. * @returns The loaded plugin
  62555. */
  62556. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62557. if (onSuccess === void 0) { onSuccess = null; }
  62558. if (onProgress === void 0) { onProgress = null; }
  62559. if (onError === void 0) { onError = null; }
  62560. if (pluginExtension === void 0) { pluginExtension = null; }
  62561. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62562. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62563. return null;
  62564. }
  62565. var loadingToken = {};
  62566. scene._addPendingData(loadingToken);
  62567. var disposeHandler = function () {
  62568. scene._removePendingData(loadingToken);
  62569. };
  62570. var errorHandler = function (message, exception) {
  62571. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  62572. if (onError) {
  62573. onError(scene, errorMessage, exception);
  62574. }
  62575. else {
  62576. BABYLON.Tools.Error(errorMessage);
  62577. // should the exception be thrown?
  62578. }
  62579. disposeHandler();
  62580. };
  62581. var progressHandler = onProgress ? function (event) {
  62582. try {
  62583. onProgress(event);
  62584. }
  62585. catch (e) {
  62586. errorHandler("Error in onProgress callback", e);
  62587. }
  62588. } : undefined;
  62589. var successHandler = function (meshes, particleSystems, skeletons) {
  62590. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  62591. if (onSuccess) {
  62592. try {
  62593. onSuccess(meshes, particleSystems, skeletons);
  62594. }
  62595. catch (e) {
  62596. errorHandler("Error in onSuccess callback", e);
  62597. }
  62598. }
  62599. scene._removePendingData(loadingToken);
  62600. };
  62601. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62602. if (plugin.rewriteRootURL) {
  62603. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  62604. }
  62605. if (sceneFilename === "") {
  62606. if (sceneFilename === "") {
  62607. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  62608. }
  62609. }
  62610. if (plugin.importMesh) {
  62611. var syncedPlugin = plugin;
  62612. var meshes = new Array();
  62613. var particleSystems = new Array();
  62614. var skeletons = new Array();
  62615. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  62616. return;
  62617. }
  62618. scene.loadingPluginName = plugin.name;
  62619. successHandler(meshes, particleSystems, skeletons);
  62620. }
  62621. else {
  62622. var asyncedPlugin = plugin;
  62623. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  62624. scene.loadingPluginName = plugin.name;
  62625. successHandler(result.meshes, result.particleSystems, result.skeletons);
  62626. }).catch(function (error) {
  62627. errorHandler(error.message, error);
  62628. });
  62629. }
  62630. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62631. };
  62632. /**
  62633. * Import meshes into a scene
  62634. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  62635. * @param rootUrl a string that defines the root url for scene and resources
  62636. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62637. * @param scene the instance of BABYLON.Scene to append to
  62638. * @param onProgress a callback with a progress event for each file being loaded
  62639. * @param pluginExtension the extension used to determine the plugin
  62640. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  62641. */
  62642. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62643. if (onProgress === void 0) { onProgress = null; }
  62644. if (pluginExtension === void 0) { pluginExtension = null; }
  62645. return new Promise(function (resolve, reject) {
  62646. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  62647. resolve({
  62648. meshes: meshes,
  62649. particleSystems: particleSystems,
  62650. skeletons: skeletons
  62651. });
  62652. }, onProgress, function (scene, message, exception) {
  62653. reject(exception || new Error(message));
  62654. });
  62655. });
  62656. };
  62657. /**
  62658. * Load a scene
  62659. * @param rootUrl a string that defines the root url for scene and resources
  62660. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62661. * @param engine is the instance of BABYLON.Engine to use to create the scene
  62662. * @param onSuccess a callback with the scene when import succeeds
  62663. * @param onProgress a callback with a progress event for each file being loaded
  62664. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62665. * @param pluginExtension the extension used to determine the plugin
  62666. * @returns The loaded plugin
  62667. */
  62668. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  62669. if (onSuccess === void 0) { onSuccess = null; }
  62670. if (onProgress === void 0) { onProgress = null; }
  62671. if (onError === void 0) { onError = null; }
  62672. if (pluginExtension === void 0) { pluginExtension = null; }
  62673. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  62674. };
  62675. /**
  62676. * Load a scene
  62677. * @param rootUrl a string that defines the root url for scene and resources
  62678. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62679. * @param engine is the instance of BABYLON.Engine to use to create the scene
  62680. * @param onProgress a callback with a progress event for each file being loaded
  62681. * @param pluginExtension the extension used to determine the plugin
  62682. * @returns The loaded scene
  62683. */
  62684. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  62685. if (onProgress === void 0) { onProgress = null; }
  62686. if (pluginExtension === void 0) { pluginExtension = null; }
  62687. return new Promise(function (resolve, reject) {
  62688. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  62689. resolve(scene);
  62690. }, onProgress, function (scene, message, exception) {
  62691. reject(exception || new Error(message));
  62692. }, pluginExtension);
  62693. });
  62694. };
  62695. /**
  62696. * Append a scene
  62697. * @param rootUrl a string that defines the root url for scene and resources
  62698. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62699. * @param scene is the instance of BABYLON.Scene to append to
  62700. * @param onSuccess a callback with the scene when import succeeds
  62701. * @param onProgress a callback with a progress event for each file being loaded
  62702. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62703. * @param pluginExtension the extension used to determine the plugin
  62704. * @returns The loaded plugin
  62705. */
  62706. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62707. if (onSuccess === void 0) { onSuccess = null; }
  62708. if (onProgress === void 0) { onProgress = null; }
  62709. if (onError === void 0) { onError = null; }
  62710. if (pluginExtension === void 0) { pluginExtension = null; }
  62711. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62712. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62713. return null;
  62714. }
  62715. if (SceneLoader.ShowLoadingScreen) {
  62716. scene.getEngine().displayLoadingUI();
  62717. }
  62718. var loadingToken = {};
  62719. scene._addPendingData(loadingToken);
  62720. var disposeHandler = function () {
  62721. scene._removePendingData(loadingToken);
  62722. scene.getEngine().hideLoadingUI();
  62723. };
  62724. var errorHandler = function (message, exception) {
  62725. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  62726. if (onError) {
  62727. onError(scene, errorMessage, exception);
  62728. }
  62729. else {
  62730. BABYLON.Tools.Error(errorMessage);
  62731. // should the exception be thrown?
  62732. }
  62733. disposeHandler();
  62734. };
  62735. var progressHandler = onProgress ? function (event) {
  62736. try {
  62737. onProgress(event);
  62738. }
  62739. catch (e) {
  62740. errorHandler("Error in onProgress callback", e);
  62741. }
  62742. } : undefined;
  62743. var successHandler = function () {
  62744. if (onSuccess) {
  62745. try {
  62746. onSuccess(scene);
  62747. }
  62748. catch (e) {
  62749. errorHandler("Error in onSuccess callback", e);
  62750. }
  62751. }
  62752. scene._removePendingData(loadingToken);
  62753. };
  62754. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62755. if (sceneFilename === "") {
  62756. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  62757. }
  62758. if (plugin.load) {
  62759. var syncedPlugin = plugin;
  62760. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  62761. return;
  62762. }
  62763. scene.loadingPluginName = plugin.name;
  62764. successHandler();
  62765. }
  62766. else {
  62767. var asyncedPlugin = plugin;
  62768. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  62769. scene.loadingPluginName = plugin.name;
  62770. successHandler();
  62771. }).catch(function (error) {
  62772. errorHandler(error.message, error);
  62773. });
  62774. }
  62775. if (SceneLoader.ShowLoadingScreen) {
  62776. scene.executeWhenReady(function () {
  62777. scene.getEngine().hideLoadingUI();
  62778. });
  62779. }
  62780. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62781. };
  62782. /**
  62783. * Append a scene
  62784. * @param rootUrl a string that defines the root url for scene and resources
  62785. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62786. * @param scene is the instance of BABYLON.Scene to append to
  62787. * @param onProgress a callback with a progress event for each file being loaded
  62788. * @param pluginExtension the extension used to determine the plugin
  62789. * @returns The given scene
  62790. */
  62791. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62792. if (onProgress === void 0) { onProgress = null; }
  62793. if (pluginExtension === void 0) { pluginExtension = null; }
  62794. return new Promise(function (resolve, reject) {
  62795. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  62796. resolve(scene);
  62797. }, onProgress, function (scene, message, exception) {
  62798. reject(exception || new Error(message));
  62799. }, pluginExtension);
  62800. });
  62801. };
  62802. /**
  62803. * Load a scene into an asset container
  62804. * @param rootUrl a string that defines the root url for scene and resources
  62805. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62806. * @param scene is the instance of BABYLON.Scene to append to
  62807. * @param onSuccess a callback with the scene when import succeeds
  62808. * @param onProgress a callback with a progress event for each file being loaded
  62809. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62810. * @param pluginExtension the extension used to determine the plugin
  62811. * @returns The loaded plugin
  62812. */
  62813. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62814. if (onSuccess === void 0) { onSuccess = null; }
  62815. if (onProgress === void 0) { onProgress = null; }
  62816. if (onError === void 0) { onError = null; }
  62817. if (pluginExtension === void 0) { pluginExtension = null; }
  62818. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62819. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62820. return null;
  62821. }
  62822. var loadingToken = {};
  62823. scene._addPendingData(loadingToken);
  62824. var disposeHandler = function () {
  62825. scene._removePendingData(loadingToken);
  62826. };
  62827. var errorHandler = function (message, exception) {
  62828. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  62829. if (onError) {
  62830. onError(scene, errorMessage, exception);
  62831. }
  62832. else {
  62833. BABYLON.Tools.Error(errorMessage);
  62834. // should the exception be thrown?
  62835. }
  62836. disposeHandler();
  62837. };
  62838. var progressHandler = onProgress ? function (event) {
  62839. try {
  62840. onProgress(event);
  62841. }
  62842. catch (e) {
  62843. errorHandler("Error in onProgress callback", e);
  62844. }
  62845. } : undefined;
  62846. var successHandler = function (assets) {
  62847. if (onSuccess) {
  62848. try {
  62849. onSuccess(assets);
  62850. }
  62851. catch (e) {
  62852. errorHandler("Error in onSuccess callback", e);
  62853. }
  62854. }
  62855. scene._removePendingData(loadingToken);
  62856. };
  62857. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62858. if (plugin.loadAssetContainer) {
  62859. var syncedPlugin = plugin;
  62860. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  62861. if (!assetContainer) {
  62862. return;
  62863. }
  62864. scene.loadingPluginName = plugin.name;
  62865. successHandler(assetContainer);
  62866. }
  62867. else if (plugin.loadAssetContainerAsync) {
  62868. var asyncedPlugin = plugin;
  62869. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  62870. scene.loadingPluginName = plugin.name;
  62871. successHandler(assetContainer);
  62872. }).catch(function (error) {
  62873. errorHandler(error.message, error);
  62874. });
  62875. }
  62876. else {
  62877. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  62878. }
  62879. if (SceneLoader.ShowLoadingScreen) {
  62880. scene.executeWhenReady(function () {
  62881. scene.getEngine().hideLoadingUI();
  62882. });
  62883. }
  62884. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62885. };
  62886. /**
  62887. * Load a scene into an asset container
  62888. * @param rootUrl a string that defines the root url for scene and resources
  62889. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62890. * @param scene is the instance of BABYLON.Scene to append to
  62891. * @param onProgress a callback with a progress event for each file being loaded
  62892. * @param pluginExtension the extension used to determine the plugin
  62893. * @returns The loaded asset container
  62894. */
  62895. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62896. if (onProgress === void 0) { onProgress = null; }
  62897. if (pluginExtension === void 0) { pluginExtension = null; }
  62898. return new Promise(function (resolve, reject) {
  62899. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  62900. resolve(assetContainer);
  62901. }, onProgress, function (scene, message, exception) {
  62902. reject(exception || new Error(message));
  62903. }, pluginExtension);
  62904. });
  62905. };
  62906. // Flags
  62907. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  62908. SceneLoader._ShowLoadingScreen = true;
  62909. SceneLoader._CleanBoneMatrixWeights = false;
  62910. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  62911. // Members
  62912. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  62913. SceneLoader._registeredPlugins = {};
  62914. return SceneLoader;
  62915. }());
  62916. BABYLON.SceneLoader = SceneLoader;
  62917. ;
  62918. })(BABYLON || (BABYLON = {}));
  62919. //# sourceMappingURL=babylon.sceneLoader.js.map
  62920. "use strict";
  62921. var BABYLON;
  62922. (function (BABYLON) {
  62923. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  62924. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  62925. var parsedMaterial = parsedData.materials[index];
  62926. if (parsedMaterial.id === id) {
  62927. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  62928. }
  62929. }
  62930. return null;
  62931. };
  62932. var isDescendantOf = function (mesh, names, hierarchyIds) {
  62933. for (var i in names) {
  62934. if (mesh.name === names[i]) {
  62935. hierarchyIds.push(mesh.id);
  62936. return true;
  62937. }
  62938. }
  62939. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  62940. hierarchyIds.push(mesh.id);
  62941. return true;
  62942. }
  62943. return false;
  62944. };
  62945. var logOperation = function (operation, producer) {
  62946. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  62947. };
  62948. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  62949. if (addToScene === void 0) { addToScene = false; }
  62950. var container = new BABYLON.AssetContainer(scene);
  62951. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62952. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62953. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62954. // and avoid problems with multiple concurrent .babylon loads.
  62955. var log = "importScene has failed JSON parse";
  62956. try {
  62957. var parsedData = JSON.parse(data);
  62958. log = "";
  62959. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  62960. var index;
  62961. var cache;
  62962. // Lights
  62963. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  62964. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  62965. var parsedLight = parsedData.lights[index];
  62966. var light = BABYLON.Light.Parse(parsedLight, scene);
  62967. if (light) {
  62968. container.lights.push(light);
  62969. log += (index === 0 ? "\n\tLights:" : "");
  62970. log += "\n\t\t" + light.toString(fullDetails);
  62971. }
  62972. }
  62973. }
  62974. // Animations
  62975. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  62976. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  62977. var parsedAnimation = parsedData.animations[index];
  62978. var animation = BABYLON.Animation.Parse(parsedAnimation);
  62979. scene.animations.push(animation);
  62980. container.animations.push(animation);
  62981. log += (index === 0 ? "\n\tAnimations:" : "");
  62982. log += "\n\t\t" + animation.toString(fullDetails);
  62983. }
  62984. }
  62985. // Materials
  62986. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  62987. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  62988. var parsedMaterial = parsedData.materials[index];
  62989. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  62990. container.materials.push(mat);
  62991. log += (index === 0 ? "\n\tMaterials:" : "");
  62992. log += "\n\t\t" + mat.toString(fullDetails);
  62993. }
  62994. }
  62995. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  62996. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  62997. var parsedMultiMaterial = parsedData.multiMaterials[index];
  62998. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  62999. container.multiMaterials.push(mmat);
  63000. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  63001. log += "\n\t\t" + mmat.toString(fullDetails);
  63002. }
  63003. }
  63004. // Morph targets
  63005. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  63006. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  63007. var managerData = _a[_i];
  63008. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  63009. }
  63010. }
  63011. // Skeletons
  63012. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  63013. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  63014. var parsedSkeleton = parsedData.skeletons[index];
  63015. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  63016. container.skeletons.push(skeleton);
  63017. log += (index === 0 ? "\n\tSkeletons:" : "");
  63018. log += "\n\t\t" + skeleton.toString(fullDetails);
  63019. }
  63020. }
  63021. // Geometries
  63022. var geometries = parsedData.geometries;
  63023. if (geometries !== undefined && geometries !== null) {
  63024. var addedGeometry = new Array();
  63025. // Boxes
  63026. var boxes = geometries.boxes;
  63027. if (boxes !== undefined && boxes !== null) {
  63028. for (index = 0, cache = boxes.length; index < cache; index++) {
  63029. var parsedBox = boxes[index];
  63030. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  63031. }
  63032. }
  63033. // Spheres
  63034. var spheres = geometries.spheres;
  63035. if (spheres !== undefined && spheres !== null) {
  63036. for (index = 0, cache = spheres.length; index < cache; index++) {
  63037. var parsedSphere = spheres[index];
  63038. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  63039. }
  63040. }
  63041. // Cylinders
  63042. var cylinders = geometries.cylinders;
  63043. if (cylinders !== undefined && cylinders !== null) {
  63044. for (index = 0, cache = cylinders.length; index < cache; index++) {
  63045. var parsedCylinder = cylinders[index];
  63046. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  63047. }
  63048. }
  63049. // Toruses
  63050. var toruses = geometries.toruses;
  63051. if (toruses !== undefined && toruses !== null) {
  63052. for (index = 0, cache = toruses.length; index < cache; index++) {
  63053. var parsedTorus = toruses[index];
  63054. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  63055. }
  63056. }
  63057. // Grounds
  63058. var grounds = geometries.grounds;
  63059. if (grounds !== undefined && grounds !== null) {
  63060. for (index = 0, cache = grounds.length; index < cache; index++) {
  63061. var parsedGround = grounds[index];
  63062. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  63063. }
  63064. }
  63065. // Planes
  63066. var planes = geometries.planes;
  63067. if (planes !== undefined && planes !== null) {
  63068. for (index = 0, cache = planes.length; index < cache; index++) {
  63069. var parsedPlane = planes[index];
  63070. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  63071. }
  63072. }
  63073. // TorusKnots
  63074. var torusKnots = geometries.torusKnots;
  63075. if (torusKnots !== undefined && torusKnots !== null) {
  63076. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  63077. var parsedTorusKnot = torusKnots[index];
  63078. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  63079. }
  63080. }
  63081. // VertexData
  63082. var vertexData = geometries.vertexData;
  63083. if (vertexData !== undefined && vertexData !== null) {
  63084. for (index = 0, cache = vertexData.length; index < cache; index++) {
  63085. var parsedVertexData = vertexData[index];
  63086. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  63087. }
  63088. }
  63089. addedGeometry.forEach(function (g) {
  63090. if (g) {
  63091. container.geometries.push(g);
  63092. }
  63093. });
  63094. }
  63095. // Transform nodes
  63096. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  63097. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  63098. var parsedTransformNode = parsedData.transformNodes[index];
  63099. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  63100. container.transformNodes.push(node);
  63101. }
  63102. }
  63103. // Meshes
  63104. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  63105. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  63106. var parsedMesh = parsedData.meshes[index];
  63107. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  63108. container.meshes.push(mesh);
  63109. log += (index === 0 ? "\n\tMeshes:" : "");
  63110. log += "\n\t\t" + mesh.toString(fullDetails);
  63111. }
  63112. }
  63113. // Cameras
  63114. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  63115. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  63116. var parsedCamera = parsedData.cameras[index];
  63117. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  63118. container.cameras.push(camera);
  63119. log += (index === 0 ? "\n\tCameras:" : "");
  63120. log += "\n\t\t" + camera.toString(fullDetails);
  63121. }
  63122. }
  63123. // Browsing all the graph to connect the dots
  63124. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  63125. var camera = scene.cameras[index];
  63126. if (camera._waitingParentId) {
  63127. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  63128. camera._waitingParentId = null;
  63129. }
  63130. }
  63131. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  63132. var light_1 = scene.lights[index];
  63133. if (light_1 && light_1._waitingParentId) {
  63134. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  63135. light_1._waitingParentId = null;
  63136. }
  63137. }
  63138. // Sounds
  63139. // TODO: add sound
  63140. var loadedSounds = [];
  63141. var loadedSound;
  63142. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  63143. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  63144. var parsedSound = parsedData.sounds[index];
  63145. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63146. if (!parsedSound.url)
  63147. parsedSound.url = parsedSound.name;
  63148. if (!loadedSounds[parsedSound.url]) {
  63149. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  63150. loadedSounds[parsedSound.url] = loadedSound;
  63151. container.sounds.push(loadedSound);
  63152. }
  63153. else {
  63154. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  63155. }
  63156. }
  63157. else {
  63158. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  63159. }
  63160. }
  63161. }
  63162. loadedSounds = [];
  63163. // Connect parents & children and parse actions
  63164. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  63165. var transformNode = scene.transformNodes[index];
  63166. if (transformNode._waitingParentId) {
  63167. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  63168. transformNode._waitingParentId = null;
  63169. }
  63170. }
  63171. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63172. var mesh = scene.meshes[index];
  63173. if (mesh._waitingParentId) {
  63174. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  63175. mesh._waitingParentId = null;
  63176. }
  63177. if (mesh._waitingActions) {
  63178. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  63179. mesh._waitingActions = null;
  63180. }
  63181. }
  63182. // freeze world matrix application
  63183. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63184. var currentMesh = scene.meshes[index];
  63185. if (currentMesh._waitingFreezeWorldMatrix) {
  63186. currentMesh.freezeWorldMatrix();
  63187. currentMesh._waitingFreezeWorldMatrix = null;
  63188. }
  63189. else {
  63190. currentMesh.computeWorldMatrix(true);
  63191. }
  63192. }
  63193. // Particles Systems
  63194. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63195. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63196. var parsedParticleSystem = parsedData.particleSystems[index];
  63197. if (parsedParticleSystem.activeParticleCount) {
  63198. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63199. container.particleSystems.push(ps);
  63200. }
  63201. else {
  63202. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63203. container.particleSystems.push(ps);
  63204. }
  63205. }
  63206. }
  63207. // Lens flares
  63208. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  63209. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  63210. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  63211. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  63212. container.lensFlareSystems.push(lf);
  63213. }
  63214. }
  63215. // Shadows
  63216. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  63217. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  63218. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  63219. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  63220. container.shadowGenerators.push(sg);
  63221. }
  63222. }
  63223. // Lights exclusions / inclusions
  63224. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  63225. var light_2 = scene.lights[index];
  63226. // Excluded check
  63227. if (light_2._excludedMeshesIds.length > 0) {
  63228. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  63229. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  63230. if (excludedMesh) {
  63231. light_2.excludedMeshes.push(excludedMesh);
  63232. }
  63233. }
  63234. light_2._excludedMeshesIds = [];
  63235. }
  63236. // Included check
  63237. if (light_2._includedOnlyMeshesIds.length > 0) {
  63238. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  63239. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  63240. if (includedOnlyMesh) {
  63241. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  63242. }
  63243. }
  63244. light_2._includedOnlyMeshesIds = [];
  63245. }
  63246. }
  63247. // Actions (scene)
  63248. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  63249. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  63250. }
  63251. if (!addToScene) {
  63252. container.removeAllFromScene();
  63253. }
  63254. }
  63255. catch (err) {
  63256. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  63257. if (onError) {
  63258. onError(msg, err);
  63259. }
  63260. else {
  63261. BABYLON.Tools.Log(msg);
  63262. throw err;
  63263. }
  63264. }
  63265. finally {
  63266. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63267. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63268. }
  63269. }
  63270. return container;
  63271. };
  63272. BABYLON.SceneLoader.RegisterPlugin({
  63273. name: "babylon.js",
  63274. extensions: ".babylon",
  63275. canDirectLoad: function (data) {
  63276. if (data.indexOf("babylon") !== -1) {
  63277. return true;
  63278. }
  63279. return false;
  63280. },
  63281. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  63282. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63283. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63284. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63285. // and avoid problems with multiple concurrent .babylon loads.
  63286. var log = "importMesh has failed JSON parse";
  63287. try {
  63288. var parsedData = JSON.parse(data);
  63289. log = "";
  63290. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  63291. if (!meshesNames) {
  63292. meshesNames = null;
  63293. }
  63294. else if (!Array.isArray(meshesNames)) {
  63295. meshesNames = [meshesNames];
  63296. }
  63297. var hierarchyIds = new Array();
  63298. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  63299. var loadedSkeletonsIds = [];
  63300. var loadedMaterialsIds = [];
  63301. var index;
  63302. var cache;
  63303. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  63304. var parsedMesh = parsedData.meshes[index];
  63305. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  63306. if (meshesNames !== null) {
  63307. // Remove found mesh name from list.
  63308. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  63309. }
  63310. //Geometry?
  63311. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  63312. //does the file contain geometries?
  63313. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  63314. //find the correct geometry and add it to the scene
  63315. var found = false;
  63316. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  63317. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  63318. return;
  63319. }
  63320. else {
  63321. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  63322. if (parsedGeometryData.id === parsedMesh.geometryId) {
  63323. switch (geometryType) {
  63324. case "boxes":
  63325. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  63326. break;
  63327. case "spheres":
  63328. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  63329. break;
  63330. case "cylinders":
  63331. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  63332. break;
  63333. case "toruses":
  63334. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  63335. break;
  63336. case "grounds":
  63337. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  63338. break;
  63339. case "planes":
  63340. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  63341. break;
  63342. case "torusKnots":
  63343. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  63344. break;
  63345. case "vertexData":
  63346. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  63347. break;
  63348. }
  63349. found = true;
  63350. }
  63351. });
  63352. }
  63353. });
  63354. if (found === false) {
  63355. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  63356. }
  63357. }
  63358. }
  63359. // Material ?
  63360. if (parsedMesh.materialId) {
  63361. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  63362. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  63363. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  63364. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  63365. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  63366. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  63367. var subMatId = parsedMultiMaterial.materials[matIndex];
  63368. loadedMaterialsIds.push(subMatId);
  63369. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  63370. if (mat) {
  63371. log += "\n\tMaterial " + mat.toString(fullDetails);
  63372. }
  63373. }
  63374. loadedMaterialsIds.push(parsedMultiMaterial.id);
  63375. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  63376. if (mmat) {
  63377. materialFound = true;
  63378. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  63379. }
  63380. break;
  63381. }
  63382. }
  63383. }
  63384. if (materialFound === false) {
  63385. loadedMaterialsIds.push(parsedMesh.materialId);
  63386. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  63387. if (!mat) {
  63388. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  63389. }
  63390. else {
  63391. log += "\n\tMaterial " + mat.toString(fullDetails);
  63392. }
  63393. }
  63394. }
  63395. // Skeleton ?
  63396. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  63397. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  63398. if (skeletonAlreadyLoaded === false) {
  63399. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  63400. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  63401. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  63402. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  63403. skeletons.push(skeleton);
  63404. loadedSkeletonsIds.push(parsedSkeleton.id);
  63405. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  63406. }
  63407. }
  63408. }
  63409. }
  63410. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  63411. meshes.push(mesh);
  63412. log += "\n\tMesh " + mesh.toString(fullDetails);
  63413. }
  63414. }
  63415. // Connecting parents
  63416. var currentMesh;
  63417. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63418. currentMesh = scene.meshes[index];
  63419. if (currentMesh._waitingParentId) {
  63420. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  63421. currentMesh._waitingParentId = null;
  63422. }
  63423. }
  63424. // freeze and compute world matrix application
  63425. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63426. currentMesh = scene.meshes[index];
  63427. if (currentMesh._waitingFreezeWorldMatrix) {
  63428. currentMesh.freezeWorldMatrix();
  63429. currentMesh._waitingFreezeWorldMatrix = null;
  63430. }
  63431. else {
  63432. currentMesh.computeWorldMatrix(true);
  63433. }
  63434. }
  63435. }
  63436. // Particles
  63437. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63438. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63439. var parsedParticleSystem = parsedData.particleSystems[index];
  63440. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  63441. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  63442. }
  63443. }
  63444. }
  63445. return true;
  63446. }
  63447. catch (err) {
  63448. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  63449. if (onError) {
  63450. onError(msg, err);
  63451. }
  63452. else {
  63453. BABYLON.Tools.Log(msg);
  63454. throw err;
  63455. }
  63456. }
  63457. finally {
  63458. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63459. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63460. }
  63461. }
  63462. return false;
  63463. },
  63464. load: function (scene, data, rootUrl, onError) {
  63465. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63466. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63467. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63468. // and avoid problems with multiple concurrent .babylon loads.
  63469. var log = "importScene has failed JSON parse";
  63470. try {
  63471. var parsedData = JSON.parse(data);
  63472. log = "";
  63473. // Scene
  63474. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  63475. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  63476. }
  63477. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  63478. scene.autoClear = parsedData.autoClear;
  63479. }
  63480. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  63481. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  63482. }
  63483. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  63484. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  63485. }
  63486. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  63487. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  63488. }
  63489. // Fog
  63490. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  63491. scene.fogMode = parsedData.fogMode;
  63492. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  63493. scene.fogStart = parsedData.fogStart;
  63494. scene.fogEnd = parsedData.fogEnd;
  63495. scene.fogDensity = parsedData.fogDensity;
  63496. log += "\tFog mode for scene: ";
  63497. switch (scene.fogMode) {
  63498. // getters not compiling, so using hardcoded
  63499. case 1:
  63500. log += "exp\n";
  63501. break;
  63502. case 2:
  63503. log += "exp2\n";
  63504. break;
  63505. case 3:
  63506. log += "linear\n";
  63507. break;
  63508. }
  63509. }
  63510. //Physics
  63511. if (parsedData.physicsEnabled) {
  63512. var physicsPlugin;
  63513. if (parsedData.physicsEngine === "cannon") {
  63514. physicsPlugin = new BABYLON.CannonJSPlugin();
  63515. }
  63516. else if (parsedData.physicsEngine === "oimo") {
  63517. physicsPlugin = new BABYLON.OimoJSPlugin();
  63518. }
  63519. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  63520. //else - default engine, which is currently oimo
  63521. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  63522. scene.enablePhysics(physicsGravity, physicsPlugin);
  63523. }
  63524. // Metadata
  63525. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  63526. scene.metadata = parsedData.metadata;
  63527. }
  63528. //collisions, if defined. otherwise, default is true
  63529. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  63530. scene.collisionsEnabled = parsedData.collisionsEnabled;
  63531. }
  63532. scene.workerCollisions = !!parsedData.workerCollisions;
  63533. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  63534. if (!container) {
  63535. return false;
  63536. }
  63537. if (parsedData.autoAnimate) {
  63538. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  63539. }
  63540. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  63541. scene.setActiveCameraByID(parsedData.activeCameraID);
  63542. }
  63543. // Environment texture
  63544. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  63545. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  63546. if (parsedData.createDefaultSkybox === true) {
  63547. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  63548. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  63549. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  63550. }
  63551. }
  63552. // Finish
  63553. return true;
  63554. }
  63555. catch (err) {
  63556. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  63557. if (onError) {
  63558. onError(msg, err);
  63559. }
  63560. else {
  63561. BABYLON.Tools.Log(msg);
  63562. throw err;
  63563. }
  63564. }
  63565. finally {
  63566. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63567. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63568. }
  63569. }
  63570. return false;
  63571. },
  63572. loadAssetContainer: function (scene, data, rootUrl, onError) {
  63573. var container = loadAssetContainer(scene, data, rootUrl, onError);
  63574. return container;
  63575. }
  63576. });
  63577. })(BABYLON || (BABYLON = {}));
  63578. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  63579. "use strict";
  63580. var BABYLON;
  63581. (function (BABYLON) {
  63582. var FilesInput = /** @class */ (function () {
  63583. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  63584. this.onProcessFileCallback = function () { return true; };
  63585. this._engine = engine;
  63586. this._currentScene = scene;
  63587. this._sceneLoadedCallback = sceneLoadedCallback;
  63588. this._progressCallback = progressCallback;
  63589. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  63590. this._textureLoadingCallback = textureLoadingCallback;
  63591. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  63592. this._onReloadCallback = onReloadCallback;
  63593. this._errorCallback = errorCallback;
  63594. }
  63595. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  63596. var _this = this;
  63597. if (elementToMonitor) {
  63598. this._elementToMonitor = elementToMonitor;
  63599. this._dragEnterHandler = function (e) { _this.drag(e); };
  63600. this._dragOverHandler = function (e) { _this.drag(e); };
  63601. this._dropHandler = function (e) { _this.drop(e); };
  63602. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  63603. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  63604. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  63605. }
  63606. };
  63607. FilesInput.prototype.dispose = function () {
  63608. if (!this._elementToMonitor) {
  63609. return;
  63610. }
  63611. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  63612. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  63613. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  63614. };
  63615. FilesInput.prototype.renderFunction = function () {
  63616. if (this._additionalRenderLoopLogicCallback) {
  63617. this._additionalRenderLoopLogicCallback();
  63618. }
  63619. if (this._currentScene) {
  63620. if (this._textureLoadingCallback) {
  63621. var remaining = this._currentScene.getWaitingItemsCount();
  63622. if (remaining > 0) {
  63623. this._textureLoadingCallback(remaining);
  63624. }
  63625. }
  63626. this._currentScene.render();
  63627. }
  63628. };
  63629. FilesInput.prototype.drag = function (e) {
  63630. e.stopPropagation();
  63631. e.preventDefault();
  63632. };
  63633. FilesInput.prototype.drop = function (eventDrop) {
  63634. eventDrop.stopPropagation();
  63635. eventDrop.preventDefault();
  63636. this.loadFiles(eventDrop);
  63637. };
  63638. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  63639. var _this = this;
  63640. var reader = folder.createReader();
  63641. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  63642. reader.readEntries(function (entries) {
  63643. remaining.count += entries.length;
  63644. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  63645. var entry = entries_1[_i];
  63646. if (entry.isFile) {
  63647. entry.file(function (file) {
  63648. file.correctName = relativePath + file.name;
  63649. files.push(file);
  63650. if (--remaining.count === 0) {
  63651. callback();
  63652. }
  63653. });
  63654. }
  63655. else if (entry.isDirectory) {
  63656. _this._traverseFolder(entry, files, remaining, callback);
  63657. }
  63658. }
  63659. if (--remaining.count) {
  63660. callback();
  63661. }
  63662. });
  63663. };
  63664. FilesInput.prototype._processFiles = function (files) {
  63665. for (var i = 0; i < files.length; i++) {
  63666. var name = files[i].correctName.toLowerCase();
  63667. var extension = name.split('.').pop();
  63668. if (!this.onProcessFileCallback(files[i], name, extension)) {
  63669. continue;
  63670. }
  63671. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  63672. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  63673. this._sceneFileToLoad = files[i];
  63674. }
  63675. else {
  63676. FilesInput.FilesToLoad[name] = files[i];
  63677. }
  63678. }
  63679. };
  63680. FilesInput.prototype.loadFiles = function (event) {
  63681. var _this = this;
  63682. if (this._startingProcessingFilesCallback)
  63683. this._startingProcessingFilesCallback();
  63684. // Handling data transfer via drag'n'drop
  63685. if (event && event.dataTransfer && event.dataTransfer.files) {
  63686. this._filesToLoad = event.dataTransfer.files;
  63687. }
  63688. // Handling files from input files
  63689. if (event && event.target && event.target.files) {
  63690. this._filesToLoad = event.target.files;
  63691. }
  63692. if (this._filesToLoad && this._filesToLoad.length > 0) {
  63693. var files_1 = new Array();
  63694. var folders = [];
  63695. var items = event.dataTransfer ? event.dataTransfer.items : null;
  63696. for (var i = 0; i < this._filesToLoad.length; i++) {
  63697. var fileToLoad = this._filesToLoad[i];
  63698. var name_1 = fileToLoad.name.toLowerCase();
  63699. var entry = void 0;
  63700. fileToLoad.correctName = name_1;
  63701. if (items) {
  63702. var item = items[i];
  63703. if (item.getAsEntry) {
  63704. entry = item.getAsEntry();
  63705. }
  63706. else if (item.webkitGetAsEntry) {
  63707. entry = item.webkitGetAsEntry();
  63708. }
  63709. }
  63710. if (!entry) {
  63711. files_1.push(fileToLoad);
  63712. }
  63713. else {
  63714. if (entry.isDirectory) {
  63715. folders.push(entry);
  63716. }
  63717. else {
  63718. files_1.push(fileToLoad);
  63719. }
  63720. }
  63721. }
  63722. if (folders.length === 0) {
  63723. this._processFiles(files_1);
  63724. this._processReload();
  63725. }
  63726. else {
  63727. var remaining = { count: folders.length };
  63728. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  63729. var folder = folders_1[_i];
  63730. this._traverseFolder(folder, files_1, remaining, function () {
  63731. _this._processFiles(files_1);
  63732. if (remaining.count === 0) {
  63733. _this._processReload();
  63734. }
  63735. });
  63736. }
  63737. }
  63738. }
  63739. };
  63740. FilesInput.prototype._processReload = function () {
  63741. if (this._onReloadCallback) {
  63742. this._onReloadCallback(this._sceneFileToLoad);
  63743. }
  63744. else {
  63745. this.reload();
  63746. }
  63747. };
  63748. FilesInput.prototype.reload = function () {
  63749. var _this = this;
  63750. // If a scene file has been provided
  63751. if (this._sceneFileToLoad) {
  63752. if (this._currentScene) {
  63753. if (BABYLON.Tools.errorsCount > 0) {
  63754. BABYLON.Tools.ClearLogCache();
  63755. }
  63756. this._engine.stopRenderLoop();
  63757. this._currentScene.dispose();
  63758. }
  63759. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  63760. if (_this._progressCallback) {
  63761. _this._progressCallback(progress);
  63762. }
  63763. }).then(function (scene) {
  63764. _this._currentScene = scene;
  63765. if (_this._sceneLoadedCallback) {
  63766. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  63767. }
  63768. // Wait for textures and shaders to be ready
  63769. _this._currentScene.executeWhenReady(function () {
  63770. _this._engine.runRenderLoop(function () {
  63771. _this.renderFunction();
  63772. });
  63773. });
  63774. }).catch(function (error) {
  63775. if (_this._errorCallback) {
  63776. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  63777. }
  63778. });
  63779. }
  63780. else {
  63781. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  63782. }
  63783. };
  63784. FilesInput.FilesToLoad = {};
  63785. return FilesInput;
  63786. }());
  63787. BABYLON.FilesInput = FilesInput;
  63788. })(BABYLON || (BABYLON = {}));
  63789. //# sourceMappingURL=babylon.filesInput.js.map
  63790. "use strict";
  63791. var BABYLON;
  63792. (function (BABYLON) {
  63793. /**
  63794. * This class implement a typical dictionary using a string as key and the generic type T as value.
  63795. * The underlying implementation relies on an associative array to ensure the best performances.
  63796. * The value can be anything including 'null' but except 'undefined'
  63797. */
  63798. var StringDictionary = /** @class */ (function () {
  63799. function StringDictionary() {
  63800. this._count = 0;
  63801. this._data = {};
  63802. }
  63803. /**
  63804. * This will clear this dictionary and copy the content from the 'source' one.
  63805. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  63806. * @param source the dictionary to take the content from and copy to this dictionary
  63807. */
  63808. StringDictionary.prototype.copyFrom = function (source) {
  63809. var _this = this;
  63810. this.clear();
  63811. source.forEach(function (t, v) { return _this.add(t, v); });
  63812. };
  63813. /**
  63814. * Get a value based from its key
  63815. * @param key the given key to get the matching value from
  63816. * @return the value if found, otherwise undefined is returned
  63817. */
  63818. StringDictionary.prototype.get = function (key) {
  63819. var val = this._data[key];
  63820. if (val !== undefined) {
  63821. return val;
  63822. }
  63823. return undefined;
  63824. };
  63825. /**
  63826. * Get a value from its key or add it if it doesn't exist.
  63827. * This method will ensure you that a given key/data will be present in the dictionary.
  63828. * @param key the given key to get the matching value from
  63829. * @param factory the factory that will create the value if the key is not present in the dictionary.
  63830. * The factory will only be invoked if there's no data for the given key.
  63831. * @return the value corresponding to the key.
  63832. */
  63833. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  63834. var val = this.get(key);
  63835. if (val !== undefined) {
  63836. return val;
  63837. }
  63838. val = factory(key);
  63839. if (val) {
  63840. this.add(key, val);
  63841. }
  63842. return val;
  63843. };
  63844. /**
  63845. * Get a value from its key if present in the dictionary otherwise add it
  63846. * @param key the key to get the value from
  63847. * @param val if there's no such key/value pair in the dictionary add it with this value
  63848. * @return the value corresponding to the key
  63849. */
  63850. StringDictionary.prototype.getOrAdd = function (key, val) {
  63851. var curVal = this.get(key);
  63852. if (curVal !== undefined) {
  63853. return curVal;
  63854. }
  63855. this.add(key, val);
  63856. return val;
  63857. };
  63858. /**
  63859. * Check if there's a given key in the dictionary
  63860. * @param key the key to check for
  63861. * @return true if the key is present, false otherwise
  63862. */
  63863. StringDictionary.prototype.contains = function (key) {
  63864. return this._data[key] !== undefined;
  63865. };
  63866. /**
  63867. * Add a new key and its corresponding value
  63868. * @param key the key to add
  63869. * @param value the value corresponding to the key
  63870. * @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
  63871. */
  63872. StringDictionary.prototype.add = function (key, value) {
  63873. if (this._data[key] !== undefined) {
  63874. return false;
  63875. }
  63876. this._data[key] = value;
  63877. ++this._count;
  63878. return true;
  63879. };
  63880. StringDictionary.prototype.set = function (key, value) {
  63881. if (this._data[key] === undefined) {
  63882. return false;
  63883. }
  63884. this._data[key] = value;
  63885. return true;
  63886. };
  63887. /**
  63888. * Get the element of the given key and remove it from the dictionary
  63889. * @param key
  63890. */
  63891. StringDictionary.prototype.getAndRemove = function (key) {
  63892. var val = this.get(key);
  63893. if (val !== undefined) {
  63894. delete this._data[key];
  63895. --this._count;
  63896. return val;
  63897. }
  63898. return null;
  63899. };
  63900. /**
  63901. * Remove a key/value from the dictionary.
  63902. * @param key the key to remove
  63903. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  63904. */
  63905. StringDictionary.prototype.remove = function (key) {
  63906. if (this.contains(key)) {
  63907. delete this._data[key];
  63908. --this._count;
  63909. return true;
  63910. }
  63911. return false;
  63912. };
  63913. /**
  63914. * Clear the whole content of the dictionary
  63915. */
  63916. StringDictionary.prototype.clear = function () {
  63917. this._data = {};
  63918. this._count = 0;
  63919. };
  63920. Object.defineProperty(StringDictionary.prototype, "count", {
  63921. get: function () {
  63922. return this._count;
  63923. },
  63924. enumerable: true,
  63925. configurable: true
  63926. });
  63927. /**
  63928. * Execute a callback on each key/val of the dictionary.
  63929. * Note that you can remove any element in this dictionary in the callback implementation
  63930. * @param callback the callback to execute on a given key/value pair
  63931. */
  63932. StringDictionary.prototype.forEach = function (callback) {
  63933. for (var cur in this._data) {
  63934. var val = this._data[cur];
  63935. callback(cur, val);
  63936. }
  63937. };
  63938. /**
  63939. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  63940. * If the callback returns null or undefined the method will iterate to the next key/value pair
  63941. * Note that you can remove any element in this dictionary in the callback implementation
  63942. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  63943. */
  63944. StringDictionary.prototype.first = function (callback) {
  63945. for (var cur in this._data) {
  63946. var val = this._data[cur];
  63947. var res = callback(cur, val);
  63948. if (res) {
  63949. return res;
  63950. }
  63951. }
  63952. return null;
  63953. };
  63954. return StringDictionary;
  63955. }());
  63956. BABYLON.StringDictionary = StringDictionary;
  63957. })(BABYLON || (BABYLON = {}));
  63958. //# sourceMappingURL=babylon.stringDictionary.js.map
  63959. "use strict";
  63960. var BABYLON;
  63961. (function (BABYLON) {
  63962. var Tags = /** @class */ (function () {
  63963. function Tags() {
  63964. }
  63965. Tags.EnableFor = function (obj) {
  63966. obj._tags = obj._tags || {};
  63967. obj.hasTags = function () {
  63968. return Tags.HasTags(obj);
  63969. };
  63970. obj.addTags = function (tagsString) {
  63971. return Tags.AddTagsTo(obj, tagsString);
  63972. };
  63973. obj.removeTags = function (tagsString) {
  63974. return Tags.RemoveTagsFrom(obj, tagsString);
  63975. };
  63976. obj.matchesTagsQuery = function (tagsQuery) {
  63977. return Tags.MatchesQuery(obj, tagsQuery);
  63978. };
  63979. };
  63980. Tags.DisableFor = function (obj) {
  63981. delete obj._tags;
  63982. delete obj.hasTags;
  63983. delete obj.addTags;
  63984. delete obj.removeTags;
  63985. delete obj.matchesTagsQuery;
  63986. };
  63987. Tags.HasTags = function (obj) {
  63988. if (!obj._tags) {
  63989. return false;
  63990. }
  63991. return !BABYLON.Tools.IsEmpty(obj._tags);
  63992. };
  63993. Tags.GetTags = function (obj, asString) {
  63994. if (asString === void 0) { asString = true; }
  63995. if (!obj._tags) {
  63996. return null;
  63997. }
  63998. if (asString) {
  63999. var tagsArray = [];
  64000. for (var tag in obj._tags) {
  64001. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  64002. tagsArray.push(tag);
  64003. }
  64004. }
  64005. return tagsArray.join(" ");
  64006. }
  64007. else {
  64008. return obj._tags;
  64009. }
  64010. };
  64011. // the tags 'true' and 'false' are reserved and cannot be used as tags
  64012. // a tag cannot start with '||', '&&', and '!'
  64013. // it cannot contain whitespaces
  64014. Tags.AddTagsTo = function (obj, tagsString) {
  64015. if (!tagsString) {
  64016. return;
  64017. }
  64018. if (typeof tagsString !== "string") {
  64019. return;
  64020. }
  64021. var tags = tagsString.split(" ");
  64022. tags.forEach(function (tag, index, array) {
  64023. Tags._AddTagTo(obj, tag);
  64024. });
  64025. };
  64026. Tags._AddTagTo = function (obj, tag) {
  64027. tag = tag.trim();
  64028. if (tag === "" || tag === "true" || tag === "false") {
  64029. return;
  64030. }
  64031. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  64032. return;
  64033. }
  64034. Tags.EnableFor(obj);
  64035. obj._tags[tag] = true;
  64036. };
  64037. Tags.RemoveTagsFrom = function (obj, tagsString) {
  64038. if (!Tags.HasTags(obj)) {
  64039. return;
  64040. }
  64041. var tags = tagsString.split(" ");
  64042. for (var t in tags) {
  64043. Tags._RemoveTagFrom(obj, tags[t]);
  64044. }
  64045. };
  64046. Tags._RemoveTagFrom = function (obj, tag) {
  64047. delete obj._tags[tag];
  64048. };
  64049. Tags.MatchesQuery = function (obj, tagsQuery) {
  64050. if (tagsQuery === undefined) {
  64051. return true;
  64052. }
  64053. if (tagsQuery === "") {
  64054. return Tags.HasTags(obj);
  64055. }
  64056. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  64057. };
  64058. return Tags;
  64059. }());
  64060. BABYLON.Tags = Tags;
  64061. })(BABYLON || (BABYLON = {}));
  64062. //# sourceMappingURL=babylon.tags.js.map
  64063. "use strict";
  64064. var BABYLON;
  64065. (function (BABYLON) {
  64066. var AndOrNotEvaluator = /** @class */ (function () {
  64067. function AndOrNotEvaluator() {
  64068. }
  64069. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  64070. if (!query.match(/\([^\(\)]*\)/g)) {
  64071. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  64072. }
  64073. else {
  64074. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  64075. // remove parenthesis
  64076. r = r.slice(1, r.length - 1);
  64077. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  64078. });
  64079. }
  64080. if (query === "true") {
  64081. return true;
  64082. }
  64083. if (query === "false") {
  64084. return false;
  64085. }
  64086. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  64087. };
  64088. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  64089. evaluateCallback = evaluateCallback || (function (r) {
  64090. return r === "true" ? true : false;
  64091. });
  64092. var result;
  64093. var or = parenthesisContent.split("||");
  64094. for (var i in or) {
  64095. if (or.hasOwnProperty(i)) {
  64096. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  64097. var and = ori.split("&&");
  64098. if (and.length > 1) {
  64099. for (var j = 0; j < and.length; ++j) {
  64100. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  64101. if (andj !== "true" && andj !== "false") {
  64102. if (andj[0] === "!") {
  64103. result = !evaluateCallback(andj.substring(1));
  64104. }
  64105. else {
  64106. result = evaluateCallback(andj);
  64107. }
  64108. }
  64109. else {
  64110. result = andj === "true" ? true : false;
  64111. }
  64112. if (!result) {
  64113. ori = "false";
  64114. break;
  64115. }
  64116. }
  64117. }
  64118. if (result || ori === "true") {
  64119. result = true;
  64120. break;
  64121. }
  64122. // result equals false (or undefined)
  64123. if (ori !== "true" && ori !== "false") {
  64124. if (ori[0] === "!") {
  64125. result = !evaluateCallback(ori.substring(1));
  64126. }
  64127. else {
  64128. result = evaluateCallback(ori);
  64129. }
  64130. }
  64131. else {
  64132. result = ori === "true" ? true : false;
  64133. }
  64134. }
  64135. }
  64136. // the whole parenthesis scope is replaced by 'true' or 'false'
  64137. return result ? "true" : "false";
  64138. };
  64139. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  64140. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  64141. // remove whitespaces
  64142. r = r.replace(/[\s]/g, function () { return ""; });
  64143. return r.length % 2 ? "!" : "";
  64144. });
  64145. booleanString = booleanString.trim();
  64146. if (booleanString === "!true") {
  64147. booleanString = "false";
  64148. }
  64149. else if (booleanString === "!false") {
  64150. booleanString = "true";
  64151. }
  64152. return booleanString;
  64153. };
  64154. return AndOrNotEvaluator;
  64155. }());
  64156. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  64157. })(BABYLON || (BABYLON = {}));
  64158. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  64159. "use strict";
  64160. var BABYLON;
  64161. (function (BABYLON) {
  64162. var Database = /** @class */ (function () {
  64163. function Database(urlToScene, callbackManifestChecked) {
  64164. // Handling various flavors of prefixed version of IndexedDB
  64165. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  64166. this.callbackManifestChecked = callbackManifestChecked;
  64167. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  64168. this.db = null;
  64169. this._enableSceneOffline = false;
  64170. this._enableTexturesOffline = false;
  64171. this.manifestVersionFound = 0;
  64172. this.mustUpdateRessources = false;
  64173. this.hasReachedQuota = false;
  64174. if (!Database.IDBStorageEnabled) {
  64175. this.callbackManifestChecked(true);
  64176. }
  64177. else {
  64178. this.checkManifestFile();
  64179. }
  64180. }
  64181. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  64182. get: function () {
  64183. return this._enableSceneOffline;
  64184. },
  64185. enumerable: true,
  64186. configurable: true
  64187. });
  64188. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  64189. get: function () {
  64190. return this._enableTexturesOffline;
  64191. },
  64192. enumerable: true,
  64193. configurable: true
  64194. });
  64195. Database.prototype.checkManifestFile = function () {
  64196. var _this = this;
  64197. var noManifestFile = function () {
  64198. _this._enableSceneOffline = false;
  64199. _this._enableTexturesOffline = false;
  64200. _this.callbackManifestChecked(false);
  64201. };
  64202. var timeStampUsed = false;
  64203. var manifestURL = this.currentSceneUrl + ".manifest";
  64204. var xhr = new XMLHttpRequest();
  64205. if (navigator.onLine) {
  64206. // Adding a timestamp to by-pass browsers' cache
  64207. timeStampUsed = true;
  64208. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  64209. }
  64210. xhr.open("GET", manifestURL, true);
  64211. xhr.addEventListener("load", function () {
  64212. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  64213. try {
  64214. var manifestFile = JSON.parse(xhr.response);
  64215. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  64216. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  64217. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  64218. _this.manifestVersionFound = manifestFile.version;
  64219. }
  64220. if (_this.callbackManifestChecked) {
  64221. _this.callbackManifestChecked(true);
  64222. }
  64223. }
  64224. catch (ex) {
  64225. noManifestFile();
  64226. }
  64227. }
  64228. else {
  64229. noManifestFile();
  64230. }
  64231. }, false);
  64232. xhr.addEventListener("error", function (event) {
  64233. if (timeStampUsed) {
  64234. timeStampUsed = false;
  64235. // Let's retry without the timeStamp
  64236. // It could fail when coupled with HTML5 Offline API
  64237. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  64238. xhr.open("GET", retryManifestURL, true);
  64239. xhr.send();
  64240. }
  64241. else {
  64242. noManifestFile();
  64243. }
  64244. }, false);
  64245. try {
  64246. xhr.send();
  64247. }
  64248. catch (ex) {
  64249. BABYLON.Tools.Error("Error on XHR send request.");
  64250. this.callbackManifestChecked(false);
  64251. }
  64252. };
  64253. Database.prototype.openAsync = function (successCallback, errorCallback) {
  64254. var _this = this;
  64255. var handleError = function () {
  64256. _this.isSupported = false;
  64257. if (errorCallback)
  64258. errorCallback();
  64259. };
  64260. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  64261. // Your browser doesn't support IndexedDB
  64262. this.isSupported = false;
  64263. if (errorCallback)
  64264. errorCallback();
  64265. }
  64266. else {
  64267. // If the DB hasn't been opened or created yet
  64268. if (!this.db) {
  64269. this.hasReachedQuota = false;
  64270. this.isSupported = true;
  64271. var request = this.idbFactory.open("babylonjs", 1);
  64272. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  64273. request.onerror = function (event) {
  64274. handleError();
  64275. };
  64276. // executes when a version change transaction cannot complete due to other active transactions
  64277. request.onblocked = function (event) {
  64278. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  64279. handleError();
  64280. };
  64281. // DB has been opened successfully
  64282. request.onsuccess = function (event) {
  64283. _this.db = request.result;
  64284. successCallback();
  64285. };
  64286. // Initialization of the DB. Creating Scenes & Textures stores
  64287. request.onupgradeneeded = function (event) {
  64288. _this.db = (event.target).result;
  64289. if (_this.db) {
  64290. try {
  64291. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  64292. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  64293. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  64294. }
  64295. catch (ex) {
  64296. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  64297. handleError();
  64298. }
  64299. }
  64300. };
  64301. }
  64302. else {
  64303. if (successCallback)
  64304. successCallback();
  64305. }
  64306. }
  64307. };
  64308. Database.prototype.loadImageFromDB = function (url, image) {
  64309. var _this = this;
  64310. var completeURL = Database.ReturnFullUrlLocation(url);
  64311. var saveAndLoadImage = function () {
  64312. if (!_this.hasReachedQuota && _this.db !== null) {
  64313. // the texture is not yet in the DB, let's try to save it
  64314. _this._saveImageIntoDBAsync(completeURL, image);
  64315. }
  64316. else {
  64317. image.src = url;
  64318. }
  64319. };
  64320. if (!this.mustUpdateRessources) {
  64321. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  64322. }
  64323. else {
  64324. saveAndLoadImage();
  64325. }
  64326. };
  64327. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  64328. if (this.isSupported && this.db !== null) {
  64329. var texture;
  64330. var transaction = this.db.transaction(["textures"]);
  64331. transaction.onabort = function (event) {
  64332. image.src = url;
  64333. };
  64334. transaction.oncomplete = function (event) {
  64335. var blobTextureURL;
  64336. if (texture) {
  64337. var URL = window.URL || window.webkitURL;
  64338. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  64339. image.onerror = function () {
  64340. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  64341. image.src = url;
  64342. };
  64343. image.src = blobTextureURL;
  64344. }
  64345. else {
  64346. notInDBCallback();
  64347. }
  64348. };
  64349. var getRequest = transaction.objectStore("textures").get(url);
  64350. getRequest.onsuccess = function (event) {
  64351. texture = (event.target).result;
  64352. };
  64353. getRequest.onerror = function (event) {
  64354. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  64355. image.src = url;
  64356. };
  64357. }
  64358. else {
  64359. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64360. image.src = url;
  64361. }
  64362. };
  64363. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  64364. var _this = this;
  64365. if (this.isSupported) {
  64366. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  64367. var generateBlobUrl = function () {
  64368. var blobTextureURL;
  64369. if (blob) {
  64370. var URL = window.URL || window.webkitURL;
  64371. try {
  64372. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  64373. }
  64374. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  64375. catch (ex) {
  64376. blobTextureURL = URL.createObjectURL(blob);
  64377. }
  64378. }
  64379. if (blobTextureURL) {
  64380. image.src = blobTextureURL;
  64381. }
  64382. };
  64383. if (Database.IsUASupportingBlobStorage) {
  64384. var xhr = new XMLHttpRequest(), blob;
  64385. xhr.open("GET", url, true);
  64386. xhr.responseType = "blob";
  64387. xhr.addEventListener("load", function () {
  64388. if (xhr.status === 200 && _this.db) {
  64389. // Blob as response (XHR2)
  64390. blob = xhr.response;
  64391. var transaction = _this.db.transaction(["textures"], "readwrite");
  64392. // the transaction could abort because of a QuotaExceededError error
  64393. transaction.onabort = function (event) {
  64394. try {
  64395. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  64396. var srcElement = (event.srcElement || event.target);
  64397. var error = srcElement.error;
  64398. if (error && error.name === "QuotaExceededError") {
  64399. _this.hasReachedQuota = true;
  64400. }
  64401. }
  64402. catch (ex) { }
  64403. generateBlobUrl();
  64404. };
  64405. transaction.oncomplete = function (event) {
  64406. generateBlobUrl();
  64407. };
  64408. var newTexture = { textureUrl: url, data: blob };
  64409. try {
  64410. // Put the blob into the dabase
  64411. var addRequest = transaction.objectStore("textures").put(newTexture);
  64412. addRequest.onsuccess = function (event) {
  64413. };
  64414. addRequest.onerror = function (event) {
  64415. generateBlobUrl();
  64416. };
  64417. }
  64418. catch (ex) {
  64419. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  64420. if (ex.code === 25) {
  64421. Database.IsUASupportingBlobStorage = false;
  64422. }
  64423. image.src = url;
  64424. }
  64425. }
  64426. else {
  64427. image.src = url;
  64428. }
  64429. }, false);
  64430. xhr.addEventListener("error", function (event) {
  64431. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  64432. image.src = url;
  64433. }, false);
  64434. xhr.send();
  64435. }
  64436. else {
  64437. image.src = url;
  64438. }
  64439. }
  64440. else {
  64441. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64442. image.src = url;
  64443. }
  64444. };
  64445. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  64446. var _this = this;
  64447. var updateVersion = function () {
  64448. // the version is not yet in the DB or we need to update it
  64449. _this._saveVersionIntoDBAsync(url, versionLoaded);
  64450. };
  64451. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  64452. };
  64453. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  64454. var _this = this;
  64455. if (this.isSupported && this.db) {
  64456. var version;
  64457. try {
  64458. var transaction = this.db.transaction(["versions"]);
  64459. transaction.oncomplete = function (event) {
  64460. if (version) {
  64461. // If the version in the JSON file is > than the version in DB
  64462. if (_this.manifestVersionFound > version.data) {
  64463. _this.mustUpdateRessources = true;
  64464. updateInDBCallback();
  64465. }
  64466. else {
  64467. callback(version.data);
  64468. }
  64469. }
  64470. else {
  64471. _this.mustUpdateRessources = true;
  64472. updateInDBCallback();
  64473. }
  64474. };
  64475. transaction.onabort = function (event) {
  64476. callback(-1);
  64477. };
  64478. var getRequest = transaction.objectStore("versions").get(url);
  64479. getRequest.onsuccess = function (event) {
  64480. version = (event.target).result;
  64481. };
  64482. getRequest.onerror = function (event) {
  64483. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  64484. callback(-1);
  64485. };
  64486. }
  64487. catch (ex) {
  64488. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  64489. callback(-1);
  64490. }
  64491. }
  64492. else {
  64493. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64494. callback(-1);
  64495. }
  64496. };
  64497. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  64498. var _this = this;
  64499. if (this.isSupported && !this.hasReachedQuota && this.db) {
  64500. try {
  64501. // Open a transaction to the database
  64502. var transaction = this.db.transaction(["versions"], "readwrite");
  64503. // the transaction could abort because of a QuotaExceededError error
  64504. transaction.onabort = function (event) {
  64505. try {
  64506. var error = event.srcElement['error'];
  64507. if (error && error.name === "QuotaExceededError") {
  64508. _this.hasReachedQuota = true;
  64509. }
  64510. }
  64511. catch (ex) { }
  64512. callback(-1);
  64513. };
  64514. transaction.oncomplete = function (event) {
  64515. callback(_this.manifestVersionFound);
  64516. };
  64517. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  64518. // Put the scene into the database
  64519. var addRequest = transaction.objectStore("versions").put(newVersion);
  64520. addRequest.onsuccess = function (event) {
  64521. };
  64522. addRequest.onerror = function (event) {
  64523. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  64524. };
  64525. }
  64526. catch (ex) {
  64527. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  64528. callback(-1);
  64529. }
  64530. }
  64531. else {
  64532. callback(-1);
  64533. }
  64534. };
  64535. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  64536. var _this = this;
  64537. var completeUrl = Database.ReturnFullUrlLocation(url);
  64538. var saveAndLoadFile = function () {
  64539. // the scene is not yet in the DB, let's try to save it
  64540. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  64541. };
  64542. this._checkVersionFromDB(completeUrl, function (version) {
  64543. if (version !== -1) {
  64544. if (!_this.mustUpdateRessources) {
  64545. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  64546. }
  64547. else {
  64548. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  64549. }
  64550. }
  64551. else {
  64552. if (errorCallback) {
  64553. errorCallback();
  64554. }
  64555. }
  64556. });
  64557. };
  64558. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  64559. if (this.isSupported && this.db) {
  64560. var targetStore;
  64561. if (url.indexOf(".babylon") !== -1) {
  64562. targetStore = "scenes";
  64563. }
  64564. else {
  64565. targetStore = "textures";
  64566. }
  64567. var file;
  64568. var transaction = this.db.transaction([targetStore]);
  64569. transaction.oncomplete = function (event) {
  64570. if (file) {
  64571. callback(file.data);
  64572. }
  64573. else {
  64574. notInDBCallback();
  64575. }
  64576. };
  64577. transaction.onabort = function (event) {
  64578. notInDBCallback();
  64579. };
  64580. var getRequest = transaction.objectStore(targetStore).get(url);
  64581. getRequest.onsuccess = function (event) {
  64582. file = (event.target).result;
  64583. };
  64584. getRequest.onerror = function (event) {
  64585. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  64586. notInDBCallback();
  64587. };
  64588. }
  64589. else {
  64590. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64591. callback();
  64592. }
  64593. };
  64594. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  64595. var _this = this;
  64596. if (this.isSupported) {
  64597. var targetStore;
  64598. if (url.indexOf(".babylon") !== -1) {
  64599. targetStore = "scenes";
  64600. }
  64601. else {
  64602. targetStore = "textures";
  64603. }
  64604. // Create XHR
  64605. var xhr = new XMLHttpRequest();
  64606. var fileData;
  64607. xhr.open("GET", url, true);
  64608. if (useArrayBuffer) {
  64609. xhr.responseType = "arraybuffer";
  64610. }
  64611. if (progressCallback) {
  64612. xhr.onprogress = progressCallback;
  64613. }
  64614. xhr.addEventListener("load", function () {
  64615. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  64616. // Blob as response (XHR2)
  64617. //fileData = xhr.responseText;
  64618. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  64619. if (!_this.hasReachedQuota && _this.db) {
  64620. // Open a transaction to the database
  64621. var transaction = _this.db.transaction([targetStore], "readwrite");
  64622. // the transaction could abort because of a QuotaExceededError error
  64623. transaction.onabort = function (event) {
  64624. try {
  64625. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  64626. var error = event.srcElement['error'];
  64627. if (error && error.name === "QuotaExceededError") {
  64628. _this.hasReachedQuota = true;
  64629. }
  64630. }
  64631. catch (ex) { }
  64632. callback(fileData);
  64633. };
  64634. transaction.oncomplete = function (event) {
  64635. callback(fileData);
  64636. };
  64637. var newFile;
  64638. if (targetStore === "scenes") {
  64639. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  64640. }
  64641. else {
  64642. newFile = { textureUrl: url, data: fileData };
  64643. }
  64644. try {
  64645. // Put the scene into the database
  64646. var addRequest = transaction.objectStore(targetStore).put(newFile);
  64647. addRequest.onsuccess = function (event) {
  64648. };
  64649. addRequest.onerror = function (event) {
  64650. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  64651. };
  64652. }
  64653. catch (ex) {
  64654. callback(fileData);
  64655. }
  64656. }
  64657. else {
  64658. callback(fileData);
  64659. }
  64660. }
  64661. else {
  64662. callback();
  64663. }
  64664. }, false);
  64665. xhr.addEventListener("error", function (event) {
  64666. BABYLON.Tools.Error("error on XHR request.");
  64667. callback();
  64668. }, false);
  64669. xhr.send();
  64670. }
  64671. else {
  64672. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64673. callback();
  64674. }
  64675. };
  64676. Database.IsUASupportingBlobStorage = true;
  64677. Database.IDBStorageEnabled = true;
  64678. Database.parseURL = function (url) {
  64679. var a = document.createElement('a');
  64680. a.href = url;
  64681. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  64682. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  64683. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  64684. return absLocation;
  64685. };
  64686. Database.ReturnFullUrlLocation = function (url) {
  64687. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  64688. return (Database.parseURL(window.location.href) + url);
  64689. }
  64690. else {
  64691. return url;
  64692. }
  64693. };
  64694. return Database;
  64695. }());
  64696. BABYLON.Database = Database;
  64697. })(BABYLON || (BABYLON = {}));
  64698. //# sourceMappingURL=babylon.database.js.map
  64699. "use strict";
  64700. var BABYLON;
  64701. (function (BABYLON) {
  64702. var FresnelParameters = /** @class */ (function () {
  64703. function FresnelParameters() {
  64704. this._isEnabled = true;
  64705. this.leftColor = BABYLON.Color3.White();
  64706. this.rightColor = BABYLON.Color3.Black();
  64707. this.bias = 0;
  64708. this.power = 1;
  64709. }
  64710. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  64711. get: function () {
  64712. return this._isEnabled;
  64713. },
  64714. set: function (value) {
  64715. if (this._isEnabled === value) {
  64716. return;
  64717. }
  64718. this._isEnabled = value;
  64719. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  64720. },
  64721. enumerable: true,
  64722. configurable: true
  64723. });
  64724. FresnelParameters.prototype.clone = function () {
  64725. var newFresnelParameters = new FresnelParameters();
  64726. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  64727. return newFresnelParameters;
  64728. };
  64729. FresnelParameters.prototype.serialize = function () {
  64730. var serializationObject = {};
  64731. serializationObject.isEnabled = this.isEnabled;
  64732. serializationObject.leftColor = this.leftColor;
  64733. serializationObject.rightColor = this.rightColor;
  64734. serializationObject.bias = this.bias;
  64735. serializationObject.power = this.power;
  64736. return serializationObject;
  64737. };
  64738. FresnelParameters.Parse = function (parsedFresnelParameters) {
  64739. var fresnelParameters = new FresnelParameters();
  64740. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  64741. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  64742. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  64743. fresnelParameters.bias = parsedFresnelParameters.bias;
  64744. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  64745. return fresnelParameters;
  64746. };
  64747. return FresnelParameters;
  64748. }());
  64749. BABYLON.FresnelParameters = FresnelParameters;
  64750. })(BABYLON || (BABYLON = {}));
  64751. //# sourceMappingURL=babylon.fresnelParameters.js.map
  64752. "use strict";
  64753. var BABYLON;
  64754. (function (BABYLON) {
  64755. var MultiMaterial = /** @class */ (function (_super) {
  64756. __extends(MultiMaterial, _super);
  64757. function MultiMaterial(name, scene) {
  64758. var _this = _super.call(this, name, scene, true) || this;
  64759. scene.multiMaterials.push(_this);
  64760. _this.subMaterials = new Array();
  64761. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  64762. return _this;
  64763. }
  64764. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  64765. get: function () {
  64766. return this._subMaterials;
  64767. },
  64768. set: function (value) {
  64769. this._subMaterials = value;
  64770. this._hookArray(value);
  64771. },
  64772. enumerable: true,
  64773. configurable: true
  64774. });
  64775. MultiMaterial.prototype._hookArray = function (array) {
  64776. var _this = this;
  64777. var oldPush = array.push;
  64778. array.push = function () {
  64779. var items = [];
  64780. for (var _i = 0; _i < arguments.length; _i++) {
  64781. items[_i] = arguments[_i];
  64782. }
  64783. var result = oldPush.apply(array, items);
  64784. _this._markAllSubMeshesAsTexturesDirty();
  64785. return result;
  64786. };
  64787. var oldSplice = array.splice;
  64788. array.splice = function (index, deleteCount) {
  64789. var deleted = oldSplice.apply(array, [index, deleteCount]);
  64790. _this._markAllSubMeshesAsTexturesDirty();
  64791. return deleted;
  64792. };
  64793. };
  64794. // Properties
  64795. MultiMaterial.prototype.getSubMaterial = function (index) {
  64796. if (index < 0 || index >= this.subMaterials.length) {
  64797. return this.getScene().defaultMaterial;
  64798. }
  64799. return this.subMaterials[index];
  64800. };
  64801. MultiMaterial.prototype.getActiveTextures = function () {
  64802. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  64803. if (subMaterial) {
  64804. return subMaterial.getActiveTextures();
  64805. }
  64806. else {
  64807. return [];
  64808. }
  64809. }));
  64810. var _a;
  64811. };
  64812. // Methods
  64813. MultiMaterial.prototype.getClassName = function () {
  64814. return "MultiMaterial";
  64815. };
  64816. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  64817. for (var index = 0; index < this.subMaterials.length; index++) {
  64818. var subMaterial = this.subMaterials[index];
  64819. if (subMaterial) {
  64820. if (subMaterial.storeEffectOnSubMeshes) {
  64821. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  64822. return false;
  64823. }
  64824. continue;
  64825. }
  64826. if (!subMaterial.isReady(mesh)) {
  64827. return false;
  64828. }
  64829. }
  64830. }
  64831. return true;
  64832. };
  64833. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  64834. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  64835. for (var index = 0; index < this.subMaterials.length; index++) {
  64836. var subMaterial = null;
  64837. var current = this.subMaterials[index];
  64838. if (cloneChildren && current) {
  64839. subMaterial = current.clone(name + "-" + current.name);
  64840. }
  64841. else {
  64842. subMaterial = this.subMaterials[index];
  64843. }
  64844. newMultiMaterial.subMaterials.push(subMaterial);
  64845. }
  64846. return newMultiMaterial;
  64847. };
  64848. MultiMaterial.prototype.serialize = function () {
  64849. var serializationObject = {};
  64850. serializationObject.name = this.name;
  64851. serializationObject.id = this.id;
  64852. if (BABYLON.Tags) {
  64853. serializationObject.tags = BABYLON.Tags.GetTags(this);
  64854. }
  64855. serializationObject.materials = [];
  64856. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  64857. var subMat = this.subMaterials[matIndex];
  64858. if (subMat) {
  64859. serializationObject.materials.push(subMat.id);
  64860. }
  64861. else {
  64862. serializationObject.materials.push(null);
  64863. }
  64864. }
  64865. return serializationObject;
  64866. };
  64867. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  64868. var scene = this.getScene();
  64869. if (!scene) {
  64870. return;
  64871. }
  64872. var index = scene.multiMaterials.indexOf(this);
  64873. if (index >= 0) {
  64874. scene.multiMaterials.splice(index, 1);
  64875. }
  64876. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  64877. };
  64878. return MultiMaterial;
  64879. }(BABYLON.Material));
  64880. BABYLON.MultiMaterial = MultiMaterial;
  64881. })(BABYLON || (BABYLON = {}));
  64882. //# sourceMappingURL=babylon.multiMaterial.js.map
  64883. "use strict";
  64884. var BABYLON;
  64885. (function (BABYLON) {
  64886. var FreeCameraTouchInput = /** @class */ (function () {
  64887. function FreeCameraTouchInput() {
  64888. this._offsetX = null;
  64889. this._offsetY = null;
  64890. this._pointerPressed = new Array();
  64891. this.touchAngularSensibility = 200000.0;
  64892. this.touchMoveSensibility = 250.0;
  64893. }
  64894. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  64895. var _this = this;
  64896. var previousPosition = null;
  64897. if (this._pointerInput === undefined) {
  64898. this._onLostFocus = function (evt) {
  64899. _this._offsetX = null;
  64900. _this._offsetY = null;
  64901. };
  64902. this._pointerInput = function (p, s) {
  64903. var evt = p.event;
  64904. if (evt.pointerType === "mouse") {
  64905. return;
  64906. }
  64907. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  64908. if (!noPreventDefault) {
  64909. evt.preventDefault();
  64910. }
  64911. _this._pointerPressed.push(evt.pointerId);
  64912. if (_this._pointerPressed.length !== 1) {
  64913. return;
  64914. }
  64915. previousPosition = {
  64916. x: evt.clientX,
  64917. y: evt.clientY
  64918. };
  64919. }
  64920. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  64921. if (!noPreventDefault) {
  64922. evt.preventDefault();
  64923. }
  64924. var index = _this._pointerPressed.indexOf(evt.pointerId);
  64925. if (index === -1) {
  64926. return;
  64927. }
  64928. _this._pointerPressed.splice(index, 1);
  64929. if (index != 0) {
  64930. return;
  64931. }
  64932. previousPosition = null;
  64933. _this._offsetX = null;
  64934. _this._offsetY = null;
  64935. }
  64936. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  64937. if (!noPreventDefault) {
  64938. evt.preventDefault();
  64939. }
  64940. if (!previousPosition) {
  64941. return;
  64942. }
  64943. var index = _this._pointerPressed.indexOf(evt.pointerId);
  64944. if (index != 0) {
  64945. return;
  64946. }
  64947. _this._offsetX = evt.clientX - previousPosition.x;
  64948. _this._offsetY = -(evt.clientY - previousPosition.y);
  64949. }
  64950. };
  64951. }
  64952. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  64953. if (this._onLostFocus) {
  64954. element.addEventListener("blur", this._onLostFocus);
  64955. }
  64956. };
  64957. FreeCameraTouchInput.prototype.detachControl = function (element) {
  64958. if (this._pointerInput && element) {
  64959. if (this._observer) {
  64960. this.camera.getScene().onPointerObservable.remove(this._observer);
  64961. this._observer = null;
  64962. }
  64963. if (this._onLostFocus) {
  64964. element.removeEventListener("blur", this._onLostFocus);
  64965. this._onLostFocus = null;
  64966. }
  64967. this._pointerPressed = [];
  64968. this._offsetX = null;
  64969. this._offsetY = null;
  64970. }
  64971. };
  64972. FreeCameraTouchInput.prototype.checkInputs = function () {
  64973. if (this._offsetX && this._offsetY) {
  64974. var camera = this.camera;
  64975. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  64976. if (this._pointerPressed.length > 1) {
  64977. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  64978. }
  64979. else {
  64980. var speed = camera._computeLocalCameraSpeed();
  64981. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  64982. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  64983. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  64984. }
  64985. }
  64986. };
  64987. FreeCameraTouchInput.prototype.getClassName = function () {
  64988. return "FreeCameraTouchInput";
  64989. };
  64990. FreeCameraTouchInput.prototype.getSimpleName = function () {
  64991. return "touch";
  64992. };
  64993. __decorate([
  64994. BABYLON.serialize()
  64995. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  64996. __decorate([
  64997. BABYLON.serialize()
  64998. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  64999. return FreeCameraTouchInput;
  65000. }());
  65001. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  65002. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  65003. })(BABYLON || (BABYLON = {}));
  65004. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  65005. "use strict";
  65006. var BABYLON;
  65007. (function (BABYLON) {
  65008. // We're mainly based on the logic defined into the FreeCamera code
  65009. var TouchCamera = /** @class */ (function (_super) {
  65010. __extends(TouchCamera, _super);
  65011. //-- end properties for backward compatibility for inputs
  65012. function TouchCamera(name, position, scene) {
  65013. var _this = _super.call(this, name, position, scene) || this;
  65014. _this.inputs.addTouch();
  65015. _this._setupInputs();
  65016. return _this;
  65017. }
  65018. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  65019. //-- Begin properties for backward compatibility for inputs
  65020. get: function () {
  65021. var touch = this.inputs.attached["touch"];
  65022. if (touch)
  65023. return touch.touchAngularSensibility;
  65024. return 0;
  65025. },
  65026. set: function (value) {
  65027. var touch = this.inputs.attached["touch"];
  65028. if (touch)
  65029. touch.touchAngularSensibility = value;
  65030. },
  65031. enumerable: true,
  65032. configurable: true
  65033. });
  65034. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  65035. get: function () {
  65036. var touch = this.inputs.attached["touch"];
  65037. if (touch)
  65038. return touch.touchMoveSensibility;
  65039. return 0;
  65040. },
  65041. set: function (value) {
  65042. var touch = this.inputs.attached["touch"];
  65043. if (touch)
  65044. touch.touchMoveSensibility = value;
  65045. },
  65046. enumerable: true,
  65047. configurable: true
  65048. });
  65049. TouchCamera.prototype.getClassName = function () {
  65050. return "TouchCamera";
  65051. };
  65052. TouchCamera.prototype._setupInputs = function () {
  65053. var mouse = this.inputs.attached["mouse"];
  65054. if (mouse) {
  65055. mouse.touchEnabled = false;
  65056. }
  65057. };
  65058. return TouchCamera;
  65059. }(BABYLON.FreeCamera));
  65060. BABYLON.TouchCamera = TouchCamera;
  65061. })(BABYLON || (BABYLON = {}));
  65062. //# sourceMappingURL=babylon.touchCamera.js.map
  65063. "use strict";
  65064. var BABYLON;
  65065. (function (BABYLON) {
  65066. var ProceduralTexture = /** @class */ (function (_super) {
  65067. __extends(ProceduralTexture, _super);
  65068. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  65069. if (fallbackTexture === void 0) { fallbackTexture = null; }
  65070. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65071. if (isCube === void 0) { isCube = false; }
  65072. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  65073. _this.isCube = isCube;
  65074. _this.isEnabled = true;
  65075. _this._currentRefreshId = -1;
  65076. _this._refreshRate = 1;
  65077. _this._vertexBuffers = {};
  65078. _this._uniforms = new Array();
  65079. _this._samplers = new Array();
  65080. _this._textures = {};
  65081. _this._floats = {};
  65082. _this._floatsArrays = {};
  65083. _this._colors3 = {};
  65084. _this._colors4 = {};
  65085. _this._vectors2 = {};
  65086. _this._vectors3 = {};
  65087. _this._matrices = {};
  65088. _this._fallbackTextureUsed = false;
  65089. scene._proceduralTextures.push(_this);
  65090. _this._engine = scene.getEngine();
  65091. _this.name = name;
  65092. _this.isRenderTarget = true;
  65093. _this._size = size;
  65094. _this._generateMipMaps = generateMipMaps;
  65095. _this.setFragment(fragment);
  65096. _this._fallbackTexture = fallbackTexture;
  65097. if (isCube) {
  65098. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  65099. _this.setFloat("face", 0);
  65100. }
  65101. else {
  65102. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  65103. }
  65104. // VBO
  65105. var vertices = [];
  65106. vertices.push(1, 1);
  65107. vertices.push(-1, 1);
  65108. vertices.push(-1, -1);
  65109. vertices.push(1, -1);
  65110. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65111. _this._createIndexBuffer();
  65112. return _this;
  65113. }
  65114. ProceduralTexture.prototype._createIndexBuffer = function () {
  65115. var engine = this._engine;
  65116. // Indices
  65117. var indices = [];
  65118. indices.push(0);
  65119. indices.push(1);
  65120. indices.push(2);
  65121. indices.push(0);
  65122. indices.push(2);
  65123. indices.push(3);
  65124. this._indexBuffer = engine.createIndexBuffer(indices);
  65125. };
  65126. ProceduralTexture.prototype._rebuild = function () {
  65127. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65128. if (vb) {
  65129. vb._rebuild();
  65130. }
  65131. this._createIndexBuffer();
  65132. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  65133. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  65134. }
  65135. };
  65136. ProceduralTexture.prototype.reset = function () {
  65137. if (this._effect === undefined) {
  65138. return;
  65139. }
  65140. var engine = this._engine;
  65141. engine._releaseEffect(this._effect);
  65142. };
  65143. ProceduralTexture.prototype.isReady = function () {
  65144. var _this = this;
  65145. var engine = this._engine;
  65146. var shaders;
  65147. if (!this._fragment) {
  65148. return false;
  65149. }
  65150. if (this._fallbackTextureUsed) {
  65151. return true;
  65152. }
  65153. if (this._fragment.fragmentElement !== undefined) {
  65154. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  65155. }
  65156. else {
  65157. shaders = { vertex: "procedural", fragment: this._fragment };
  65158. }
  65159. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  65160. _this.releaseInternalTexture();
  65161. if (_this._fallbackTexture) {
  65162. _this._texture = _this._fallbackTexture._texture;
  65163. if (_this._texture) {
  65164. _this._texture.incrementReferences();
  65165. }
  65166. }
  65167. _this._fallbackTextureUsed = true;
  65168. });
  65169. return this._effect.isReady();
  65170. };
  65171. ProceduralTexture.prototype.resetRefreshCounter = function () {
  65172. this._currentRefreshId = -1;
  65173. };
  65174. ProceduralTexture.prototype.setFragment = function (fragment) {
  65175. this._fragment = fragment;
  65176. };
  65177. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  65178. get: function () {
  65179. return this._refreshRate;
  65180. },
  65181. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  65182. set: function (value) {
  65183. this._refreshRate = value;
  65184. this.resetRefreshCounter();
  65185. },
  65186. enumerable: true,
  65187. configurable: true
  65188. });
  65189. ProceduralTexture.prototype._shouldRender = function () {
  65190. if (!this.isEnabled || !this.isReady() || !this._texture) {
  65191. return false;
  65192. }
  65193. if (this._fallbackTextureUsed) {
  65194. return false;
  65195. }
  65196. if (this._currentRefreshId === -1) {
  65197. this._currentRefreshId = 1;
  65198. return true;
  65199. }
  65200. if (this.refreshRate === this._currentRefreshId) {
  65201. this._currentRefreshId = 1;
  65202. return true;
  65203. }
  65204. this._currentRefreshId++;
  65205. return false;
  65206. };
  65207. ProceduralTexture.prototype.getRenderSize = function () {
  65208. return this._size;
  65209. };
  65210. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  65211. if (this._fallbackTextureUsed) {
  65212. return;
  65213. }
  65214. this.releaseInternalTexture();
  65215. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  65216. };
  65217. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  65218. if (this._uniforms.indexOf(uniformName) === -1) {
  65219. this._uniforms.push(uniformName);
  65220. }
  65221. };
  65222. ProceduralTexture.prototype.setTexture = function (name, texture) {
  65223. if (this._samplers.indexOf(name) === -1) {
  65224. this._samplers.push(name);
  65225. }
  65226. this._textures[name] = texture;
  65227. return this;
  65228. };
  65229. ProceduralTexture.prototype.setFloat = function (name, value) {
  65230. this._checkUniform(name);
  65231. this._floats[name] = value;
  65232. return this;
  65233. };
  65234. ProceduralTexture.prototype.setFloats = function (name, value) {
  65235. this._checkUniform(name);
  65236. this._floatsArrays[name] = value;
  65237. return this;
  65238. };
  65239. ProceduralTexture.prototype.setColor3 = function (name, value) {
  65240. this._checkUniform(name);
  65241. this._colors3[name] = value;
  65242. return this;
  65243. };
  65244. ProceduralTexture.prototype.setColor4 = function (name, value) {
  65245. this._checkUniform(name);
  65246. this._colors4[name] = value;
  65247. return this;
  65248. };
  65249. ProceduralTexture.prototype.setVector2 = function (name, value) {
  65250. this._checkUniform(name);
  65251. this._vectors2[name] = value;
  65252. return this;
  65253. };
  65254. ProceduralTexture.prototype.setVector3 = function (name, value) {
  65255. this._checkUniform(name);
  65256. this._vectors3[name] = value;
  65257. return this;
  65258. };
  65259. ProceduralTexture.prototype.setMatrix = function (name, value) {
  65260. this._checkUniform(name);
  65261. this._matrices[name] = value;
  65262. return this;
  65263. };
  65264. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  65265. var scene = this.getScene();
  65266. if (!scene) {
  65267. return;
  65268. }
  65269. var engine = this._engine;
  65270. // Render
  65271. engine.enableEffect(this._effect);
  65272. engine.setState(false);
  65273. // Texture
  65274. for (var name in this._textures) {
  65275. this._effect.setTexture(name, this._textures[name]);
  65276. }
  65277. // Float
  65278. for (name in this._floats) {
  65279. this._effect.setFloat(name, this._floats[name]);
  65280. }
  65281. // Floats
  65282. for (name in this._floatsArrays) {
  65283. this._effect.setArray(name, this._floatsArrays[name]);
  65284. }
  65285. // Color3
  65286. for (name in this._colors3) {
  65287. this._effect.setColor3(name, this._colors3[name]);
  65288. }
  65289. // Color4
  65290. for (name in this._colors4) {
  65291. var color = this._colors4[name];
  65292. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  65293. }
  65294. // Vector2
  65295. for (name in this._vectors2) {
  65296. this._effect.setVector2(name, this._vectors2[name]);
  65297. }
  65298. // Vector3
  65299. for (name in this._vectors3) {
  65300. this._effect.setVector3(name, this._vectors3[name]);
  65301. }
  65302. // Matrix
  65303. for (name in this._matrices) {
  65304. this._effect.setMatrix(name, this._matrices[name]);
  65305. }
  65306. if (!this._texture) {
  65307. return;
  65308. }
  65309. if (this.isCube) {
  65310. for (var face = 0; face < 6; face++) {
  65311. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  65312. // VBOs
  65313. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65314. this._effect.setFloat("face", face);
  65315. // Clear
  65316. engine.clear(scene.clearColor, true, true, true);
  65317. // Draw order
  65318. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65319. // Mipmaps
  65320. if (face === 5) {
  65321. engine.generateMipMapsForCubemap(this._texture);
  65322. }
  65323. }
  65324. }
  65325. else {
  65326. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  65327. // VBOs
  65328. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65329. // Clear
  65330. engine.clear(scene.clearColor, true, true, true);
  65331. // Draw order
  65332. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65333. }
  65334. // Unbind
  65335. engine.unBindFramebuffer(this._texture, this.isCube);
  65336. if (this.onGenerated) {
  65337. this.onGenerated();
  65338. }
  65339. };
  65340. ProceduralTexture.prototype.clone = function () {
  65341. var textureSize = this.getSize();
  65342. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  65343. // Base texture
  65344. newTexture.hasAlpha = this.hasAlpha;
  65345. newTexture.level = this.level;
  65346. // RenderTarget Texture
  65347. newTexture.coordinatesMode = this.coordinatesMode;
  65348. return newTexture;
  65349. };
  65350. ProceduralTexture.prototype.dispose = function () {
  65351. var scene = this.getScene();
  65352. if (!scene) {
  65353. return;
  65354. }
  65355. var index = scene._proceduralTextures.indexOf(this);
  65356. if (index >= 0) {
  65357. scene._proceduralTextures.splice(index, 1);
  65358. }
  65359. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65360. if (vertexBuffer) {
  65361. vertexBuffer.dispose();
  65362. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65363. }
  65364. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  65365. this._indexBuffer = null;
  65366. }
  65367. _super.prototype.dispose.call(this);
  65368. };
  65369. return ProceduralTexture;
  65370. }(BABYLON.Texture));
  65371. BABYLON.ProceduralTexture = ProceduralTexture;
  65372. })(BABYLON || (BABYLON = {}));
  65373. //# sourceMappingURL=babylon.proceduralTexture.js.map
  65374. "use strict";
  65375. var BABYLON;
  65376. (function (BABYLON) {
  65377. var CustomProceduralTexture = /** @class */ (function (_super) {
  65378. __extends(CustomProceduralTexture, _super);
  65379. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  65380. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  65381. _this._animate = true;
  65382. _this._time = 0;
  65383. _this._texturePath = texturePath;
  65384. //Try to load json
  65385. _this.loadJson(texturePath);
  65386. _this.refreshRate = 1;
  65387. return _this;
  65388. }
  65389. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  65390. var _this = this;
  65391. var noConfigFile = function () {
  65392. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  65393. try {
  65394. _this.setFragment(_this._texturePath);
  65395. }
  65396. catch (ex) {
  65397. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  65398. }
  65399. };
  65400. var configFileUrl = jsonUrl + "/config.json";
  65401. var xhr = new XMLHttpRequest();
  65402. xhr.open("GET", configFileUrl, true);
  65403. xhr.addEventListener("load", function () {
  65404. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  65405. try {
  65406. _this._config = JSON.parse(xhr.response);
  65407. _this.updateShaderUniforms();
  65408. _this.updateTextures();
  65409. _this.setFragment(_this._texturePath + "/custom");
  65410. _this._animate = _this._config.animate;
  65411. _this.refreshRate = _this._config.refreshrate;
  65412. }
  65413. catch (ex) {
  65414. noConfigFile();
  65415. }
  65416. }
  65417. else {
  65418. noConfigFile();
  65419. }
  65420. }, false);
  65421. xhr.addEventListener("error", function () {
  65422. noConfigFile();
  65423. }, false);
  65424. try {
  65425. xhr.send();
  65426. }
  65427. catch (ex) {
  65428. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  65429. }
  65430. };
  65431. CustomProceduralTexture.prototype.isReady = function () {
  65432. if (!_super.prototype.isReady.call(this)) {
  65433. return false;
  65434. }
  65435. for (var name in this._textures) {
  65436. var texture = this._textures[name];
  65437. if (!texture.isReady()) {
  65438. return false;
  65439. }
  65440. }
  65441. return true;
  65442. };
  65443. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  65444. var scene = this.getScene();
  65445. if (this._animate && scene) {
  65446. this._time += scene.getAnimationRatio() * 0.03;
  65447. this.updateShaderUniforms();
  65448. }
  65449. _super.prototype.render.call(this, useCameraPostProcess);
  65450. };
  65451. CustomProceduralTexture.prototype.updateTextures = function () {
  65452. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  65453. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  65454. }
  65455. };
  65456. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  65457. if (this._config) {
  65458. for (var j = 0; j < this._config.uniforms.length; j++) {
  65459. var uniform = this._config.uniforms[j];
  65460. switch (uniform.type) {
  65461. case "float":
  65462. this.setFloat(uniform.name, uniform.value);
  65463. break;
  65464. case "color3":
  65465. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  65466. break;
  65467. case "color4":
  65468. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  65469. break;
  65470. case "vector2":
  65471. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  65472. break;
  65473. case "vector3":
  65474. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  65475. break;
  65476. }
  65477. }
  65478. }
  65479. this.setFloat("time", this._time);
  65480. };
  65481. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  65482. get: function () {
  65483. return this._animate;
  65484. },
  65485. set: function (value) {
  65486. this._animate = value;
  65487. },
  65488. enumerable: true,
  65489. configurable: true
  65490. });
  65491. return CustomProceduralTexture;
  65492. }(BABYLON.ProceduralTexture));
  65493. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  65494. })(BABYLON || (BABYLON = {}));
  65495. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  65496. "use strict";
  65497. var BABYLON;
  65498. (function (BABYLON) {
  65499. var FreeCameraGamepadInput = /** @class */ (function () {
  65500. function FreeCameraGamepadInput() {
  65501. this.gamepadAngularSensibility = 200;
  65502. this.gamepadMoveSensibility = 40;
  65503. // private members
  65504. this._cameraTransform = BABYLON.Matrix.Identity();
  65505. this._deltaTransform = BABYLON.Vector3.Zero();
  65506. this._vector3 = BABYLON.Vector3.Zero();
  65507. this._vector2 = BABYLON.Vector2.Zero();
  65508. }
  65509. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  65510. var _this = this;
  65511. var manager = this.camera.getScene().gamepadManager;
  65512. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65513. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  65514. // prioritize XBOX gamepads.
  65515. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  65516. _this.gamepad = gamepad;
  65517. }
  65518. }
  65519. });
  65520. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65521. if (_this.gamepad === gamepad) {
  65522. _this.gamepad = null;
  65523. }
  65524. });
  65525. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  65526. };
  65527. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  65528. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65529. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65530. this.gamepad = null;
  65531. };
  65532. FreeCameraGamepadInput.prototype.checkInputs = function () {
  65533. if (this.gamepad && this.gamepad.leftStick) {
  65534. var camera = this.camera;
  65535. var LSValues = this.gamepad.leftStick;
  65536. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  65537. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  65538. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  65539. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  65540. var RSValues = this.gamepad.rightStick;
  65541. if (RSValues) {
  65542. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  65543. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  65544. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  65545. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  65546. }
  65547. else {
  65548. RSValues = { x: 0, y: 0 };
  65549. }
  65550. if (!camera.rotationQuaternion) {
  65551. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  65552. }
  65553. else {
  65554. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  65555. }
  65556. var speed = camera._computeLocalCameraSpeed() * 50.0;
  65557. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  65558. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  65559. camera.cameraDirection.addInPlace(this._deltaTransform);
  65560. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  65561. camera.cameraRotation.addInPlace(this._vector2);
  65562. }
  65563. };
  65564. FreeCameraGamepadInput.prototype.getClassName = function () {
  65565. return "FreeCameraGamepadInput";
  65566. };
  65567. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  65568. return "gamepad";
  65569. };
  65570. __decorate([
  65571. BABYLON.serialize()
  65572. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  65573. __decorate([
  65574. BABYLON.serialize()
  65575. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  65576. return FreeCameraGamepadInput;
  65577. }());
  65578. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  65579. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  65580. })(BABYLON || (BABYLON = {}));
  65581. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  65582. "use strict";
  65583. var BABYLON;
  65584. (function (BABYLON) {
  65585. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  65586. function ArcRotateCameraGamepadInput() {
  65587. this.gamepadRotationSensibility = 80;
  65588. this.gamepadMoveSensibility = 40;
  65589. }
  65590. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  65591. var _this = this;
  65592. var manager = this.camera.getScene().gamepadManager;
  65593. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65594. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  65595. // prioritize XBOX gamepads.
  65596. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  65597. _this.gamepad = gamepad;
  65598. }
  65599. }
  65600. });
  65601. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65602. if (_this.gamepad === gamepad) {
  65603. _this.gamepad = null;
  65604. }
  65605. });
  65606. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  65607. };
  65608. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  65609. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65610. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65611. this.gamepad = null;
  65612. };
  65613. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  65614. if (this.gamepad) {
  65615. var camera = this.camera;
  65616. var RSValues = this.gamepad.rightStick;
  65617. if (RSValues) {
  65618. if (RSValues.x != 0) {
  65619. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  65620. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  65621. camera.inertialAlphaOffset += normalizedRX;
  65622. }
  65623. }
  65624. if (RSValues.y != 0) {
  65625. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  65626. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  65627. camera.inertialBetaOffset += normalizedRY;
  65628. }
  65629. }
  65630. }
  65631. var LSValues = this.gamepad.leftStick;
  65632. if (LSValues && LSValues.y != 0) {
  65633. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  65634. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  65635. this.camera.inertialRadiusOffset -= normalizedLY;
  65636. }
  65637. }
  65638. }
  65639. };
  65640. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  65641. return "ArcRotateCameraGamepadInput";
  65642. };
  65643. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  65644. return "gamepad";
  65645. };
  65646. __decorate([
  65647. BABYLON.serialize()
  65648. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  65649. __decorate([
  65650. BABYLON.serialize()
  65651. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  65652. return ArcRotateCameraGamepadInput;
  65653. }());
  65654. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  65655. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  65656. })(BABYLON || (BABYLON = {}));
  65657. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  65658. "use strict";
  65659. var BABYLON;
  65660. (function (BABYLON) {
  65661. var GamepadManager = /** @class */ (function () {
  65662. function GamepadManager(_scene) {
  65663. var _this = this;
  65664. this._scene = _scene;
  65665. this._babylonGamepads = [];
  65666. this._oneGamepadConnected = false;
  65667. this._isMonitoring = false;
  65668. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  65669. if (!BABYLON.Tools.IsWindowObjectExist()) {
  65670. this._gamepadEventSupported = false;
  65671. }
  65672. else {
  65673. this._gamepadEventSupported = 'GamepadEvent' in window;
  65674. this._gamepadSupport = (navigator.getGamepads ||
  65675. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  65676. }
  65677. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  65678. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  65679. for (var i in _this._babylonGamepads) {
  65680. var gamepad = _this._babylonGamepads[i];
  65681. if (gamepad && gamepad._isConnected) {
  65682. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  65683. }
  65684. }
  65685. });
  65686. this._onGamepadConnectedEvent = function (evt) {
  65687. var gamepad = evt.gamepad;
  65688. if (gamepad.index in _this._babylonGamepads) {
  65689. if (_this._babylonGamepads[gamepad.index].isConnected) {
  65690. return;
  65691. }
  65692. }
  65693. var newGamepad;
  65694. if (_this._babylonGamepads[gamepad.index]) {
  65695. newGamepad = _this._babylonGamepads[gamepad.index];
  65696. newGamepad.browserGamepad = gamepad;
  65697. newGamepad._isConnected = true;
  65698. }
  65699. else {
  65700. newGamepad = _this._addNewGamepad(gamepad);
  65701. }
  65702. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  65703. _this._startMonitoringGamepads();
  65704. };
  65705. this._onGamepadDisconnectedEvent = function (evt) {
  65706. var gamepad = evt.gamepad;
  65707. // Remove the gamepad from the list of gamepads to monitor.
  65708. for (var i in _this._babylonGamepads) {
  65709. if (_this._babylonGamepads[i].index === gamepad.index) {
  65710. var disconnectedGamepad = _this._babylonGamepads[i];
  65711. disconnectedGamepad._isConnected = false;
  65712. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  65713. break;
  65714. }
  65715. }
  65716. };
  65717. if (this._gamepadSupport) {
  65718. //first add already-connected gamepads
  65719. this._updateGamepadObjects();
  65720. if (this._babylonGamepads.length) {
  65721. this._startMonitoringGamepads();
  65722. }
  65723. // Checking if the gamepad connected event is supported (like in Firefox)
  65724. if (this._gamepadEventSupported) {
  65725. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  65726. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  65727. }
  65728. else {
  65729. this._startMonitoringGamepads();
  65730. }
  65731. }
  65732. }
  65733. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  65734. get: function () {
  65735. return this._babylonGamepads;
  65736. },
  65737. enumerable: true,
  65738. configurable: true
  65739. });
  65740. GamepadManager.prototype.getGamepadByType = function (type) {
  65741. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  65742. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  65743. var gamepad = _a[_i];
  65744. if (gamepad && gamepad.type === type) {
  65745. return gamepad;
  65746. }
  65747. }
  65748. return null;
  65749. };
  65750. GamepadManager.prototype.dispose = function () {
  65751. if (this._gamepadEventSupported) {
  65752. if (this._onGamepadConnectedEvent) {
  65753. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  65754. }
  65755. if (this._onGamepadDisconnectedEvent) {
  65756. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  65757. }
  65758. this._onGamepadConnectedEvent = null;
  65759. this._onGamepadDisconnectedEvent = null;
  65760. }
  65761. this._babylonGamepads.forEach(function (gamepad) {
  65762. gamepad.dispose();
  65763. });
  65764. this.onGamepadConnectedObservable.clear();
  65765. this.onGamepadDisconnectedObservable.clear();
  65766. this._oneGamepadConnected = false;
  65767. this._stopMonitoringGamepads();
  65768. this._babylonGamepads = [];
  65769. };
  65770. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  65771. if (!this._oneGamepadConnected) {
  65772. this._oneGamepadConnected = true;
  65773. }
  65774. var newGamepad;
  65775. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  65776. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  65777. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  65778. }
  65779. else if (gamepad.pose) {
  65780. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  65781. }
  65782. else {
  65783. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  65784. }
  65785. this._babylonGamepads[newGamepad.index] = newGamepad;
  65786. return newGamepad;
  65787. };
  65788. GamepadManager.prototype._startMonitoringGamepads = function () {
  65789. if (!this._isMonitoring) {
  65790. this._isMonitoring = true;
  65791. //back-comp
  65792. if (!this._scene) {
  65793. this._checkGamepadsStatus();
  65794. }
  65795. }
  65796. };
  65797. GamepadManager.prototype._stopMonitoringGamepads = function () {
  65798. this._isMonitoring = false;
  65799. };
  65800. GamepadManager.prototype._checkGamepadsStatus = function () {
  65801. var _this = this;
  65802. // Hack to be compatible Chrome
  65803. this._updateGamepadObjects();
  65804. for (var i in this._babylonGamepads) {
  65805. var gamepad = this._babylonGamepads[i];
  65806. if (!gamepad || !gamepad.isConnected) {
  65807. continue;
  65808. }
  65809. gamepad.update();
  65810. }
  65811. if (this._isMonitoring && !this._scene) {
  65812. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  65813. }
  65814. };
  65815. // This function is called only on Chrome, which does not properly support
  65816. // connection/disconnection events and forces you to recopy again the gamepad object
  65817. GamepadManager.prototype._updateGamepadObjects = function () {
  65818. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  65819. for (var i = 0; i < gamepads.length; i++) {
  65820. if (gamepads[i]) {
  65821. if (!this._babylonGamepads[gamepads[i].index]) {
  65822. var newGamepad = this._addNewGamepad(gamepads[i]);
  65823. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  65824. }
  65825. else {
  65826. // Forced to copy again this object for Chrome for unknown reason
  65827. this._babylonGamepads[i].browserGamepad = gamepads[i];
  65828. if (!this._babylonGamepads[i].isConnected) {
  65829. this._babylonGamepads[i]._isConnected = true;
  65830. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  65831. }
  65832. }
  65833. }
  65834. }
  65835. };
  65836. return GamepadManager;
  65837. }());
  65838. BABYLON.GamepadManager = GamepadManager;
  65839. })(BABYLON || (BABYLON = {}));
  65840. //# sourceMappingURL=babylon.gamepadManager.js.map
  65841. "use strict";
  65842. var BABYLON;
  65843. (function (BABYLON) {
  65844. var StickValues = /** @class */ (function () {
  65845. function StickValues(x, y) {
  65846. this.x = x;
  65847. this.y = y;
  65848. }
  65849. return StickValues;
  65850. }());
  65851. BABYLON.StickValues = StickValues;
  65852. var Gamepad = /** @class */ (function () {
  65853. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  65854. if (leftStickX === void 0) { leftStickX = 0; }
  65855. if (leftStickY === void 0) { leftStickY = 1; }
  65856. if (rightStickX === void 0) { rightStickX = 2; }
  65857. if (rightStickY === void 0) { rightStickY = 3; }
  65858. this.id = id;
  65859. this.index = index;
  65860. this.browserGamepad = browserGamepad;
  65861. this._isConnected = true;
  65862. this._invertLeftStickY = false;
  65863. this.type = Gamepad.GAMEPAD;
  65864. this._leftStickAxisX = leftStickX;
  65865. this._leftStickAxisY = leftStickY;
  65866. this._rightStickAxisX = rightStickX;
  65867. this._rightStickAxisY = rightStickY;
  65868. if (this.browserGamepad.axes.length >= 2) {
  65869. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  65870. }
  65871. if (this.browserGamepad.axes.length >= 4) {
  65872. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  65873. }
  65874. }
  65875. Object.defineProperty(Gamepad.prototype, "isConnected", {
  65876. get: function () {
  65877. return this._isConnected;
  65878. },
  65879. enumerable: true,
  65880. configurable: true
  65881. });
  65882. Gamepad.prototype.onleftstickchanged = function (callback) {
  65883. this._onleftstickchanged = callback;
  65884. };
  65885. Gamepad.prototype.onrightstickchanged = function (callback) {
  65886. this._onrightstickchanged = callback;
  65887. };
  65888. Object.defineProperty(Gamepad.prototype, "leftStick", {
  65889. get: function () {
  65890. return this._leftStick;
  65891. },
  65892. set: function (newValues) {
  65893. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  65894. this._onleftstickchanged(newValues);
  65895. }
  65896. this._leftStick = newValues;
  65897. },
  65898. enumerable: true,
  65899. configurable: true
  65900. });
  65901. Object.defineProperty(Gamepad.prototype, "rightStick", {
  65902. get: function () {
  65903. return this._rightStick;
  65904. },
  65905. set: function (newValues) {
  65906. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  65907. this._onrightstickchanged(newValues);
  65908. }
  65909. this._rightStick = newValues;
  65910. },
  65911. enumerable: true,
  65912. configurable: true
  65913. });
  65914. Gamepad.prototype.update = function () {
  65915. if (this._leftStick) {
  65916. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  65917. if (this._invertLeftStickY) {
  65918. this.leftStick.y *= -1;
  65919. }
  65920. }
  65921. if (this._rightStick) {
  65922. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  65923. }
  65924. };
  65925. Gamepad.prototype.dispose = function () {
  65926. };
  65927. Gamepad.GAMEPAD = 0;
  65928. Gamepad.GENERIC = 1;
  65929. Gamepad.XBOX = 2;
  65930. Gamepad.POSE_ENABLED = 3;
  65931. return Gamepad;
  65932. }());
  65933. BABYLON.Gamepad = Gamepad;
  65934. var GenericPad = /** @class */ (function (_super) {
  65935. __extends(GenericPad, _super);
  65936. function GenericPad(id, index, browserGamepad) {
  65937. var _this = _super.call(this, id, index, browserGamepad) || this;
  65938. _this.onButtonDownObservable = new BABYLON.Observable();
  65939. _this.onButtonUpObservable = new BABYLON.Observable();
  65940. _this.type = Gamepad.GENERIC;
  65941. _this._buttons = new Array(browserGamepad.buttons.length);
  65942. return _this;
  65943. }
  65944. GenericPad.prototype.onbuttondown = function (callback) {
  65945. this._onbuttondown = callback;
  65946. };
  65947. GenericPad.prototype.onbuttonup = function (callback) {
  65948. this._onbuttonup = callback;
  65949. };
  65950. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  65951. if (newValue !== currentValue) {
  65952. if (newValue === 1) {
  65953. if (this._onbuttondown) {
  65954. this._onbuttondown(buttonIndex);
  65955. }
  65956. this.onButtonDownObservable.notifyObservers(buttonIndex);
  65957. }
  65958. if (newValue === 0) {
  65959. if (this._onbuttonup) {
  65960. this._onbuttonup(buttonIndex);
  65961. }
  65962. this.onButtonUpObservable.notifyObservers(buttonIndex);
  65963. }
  65964. }
  65965. return newValue;
  65966. };
  65967. GenericPad.prototype.update = function () {
  65968. _super.prototype.update.call(this);
  65969. for (var index = 0; index < this._buttons.length; index++) {
  65970. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  65971. }
  65972. };
  65973. GenericPad.prototype.dispose = function () {
  65974. _super.prototype.dispose.call(this);
  65975. this.onButtonDownObservable.clear();
  65976. this.onButtonUpObservable.clear();
  65977. };
  65978. return GenericPad;
  65979. }(Gamepad));
  65980. BABYLON.GenericPad = GenericPad;
  65981. })(BABYLON || (BABYLON = {}));
  65982. //# sourceMappingURL=babylon.gamepad.js.map
  65983. "use strict";
  65984. var BABYLON;
  65985. (function (BABYLON) {
  65986. var Xbox360Button;
  65987. (function (Xbox360Button) {
  65988. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  65989. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  65990. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  65991. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  65992. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  65993. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  65994. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  65995. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  65996. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  65997. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  65998. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  65999. var Xbox360Dpad;
  66000. (function (Xbox360Dpad) {
  66001. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  66002. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  66003. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  66004. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  66005. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  66006. var Xbox360Pad = /** @class */ (function (_super) {
  66007. __extends(Xbox360Pad, _super);
  66008. function Xbox360Pad(id, index, gamepad, xboxOne) {
  66009. if (xboxOne === void 0) { xboxOne = false; }
  66010. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  66011. _this._leftTrigger = 0;
  66012. _this._rightTrigger = 0;
  66013. _this.onButtonDownObservable = new BABYLON.Observable();
  66014. _this.onButtonUpObservable = new BABYLON.Observable();
  66015. _this.onPadDownObservable = new BABYLON.Observable();
  66016. _this.onPadUpObservable = new BABYLON.Observable();
  66017. _this._buttonA = 0;
  66018. _this._buttonB = 0;
  66019. _this._buttonX = 0;
  66020. _this._buttonY = 0;
  66021. _this._buttonBack = 0;
  66022. _this._buttonStart = 0;
  66023. _this._buttonLB = 0;
  66024. _this._buttonRB = 0;
  66025. _this._buttonLeftStick = 0;
  66026. _this._buttonRightStick = 0;
  66027. _this._dPadUp = 0;
  66028. _this._dPadDown = 0;
  66029. _this._dPadLeft = 0;
  66030. _this._dPadRight = 0;
  66031. _this._isXboxOnePad = false;
  66032. _this.type = BABYLON.Gamepad.XBOX;
  66033. _this._isXboxOnePad = xboxOne;
  66034. return _this;
  66035. }
  66036. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  66037. this._onlefttriggerchanged = callback;
  66038. };
  66039. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  66040. this._onrighttriggerchanged = callback;
  66041. };
  66042. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  66043. get: function () {
  66044. return this._leftTrigger;
  66045. },
  66046. set: function (newValue) {
  66047. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  66048. this._onlefttriggerchanged(newValue);
  66049. }
  66050. this._leftTrigger = newValue;
  66051. },
  66052. enumerable: true,
  66053. configurable: true
  66054. });
  66055. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  66056. get: function () {
  66057. return this._rightTrigger;
  66058. },
  66059. set: function (newValue) {
  66060. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  66061. this._onrighttriggerchanged(newValue);
  66062. }
  66063. this._rightTrigger = newValue;
  66064. },
  66065. enumerable: true,
  66066. configurable: true
  66067. });
  66068. Xbox360Pad.prototype.onbuttondown = function (callback) {
  66069. this._onbuttondown = callback;
  66070. };
  66071. Xbox360Pad.prototype.onbuttonup = function (callback) {
  66072. this._onbuttonup = callback;
  66073. };
  66074. Xbox360Pad.prototype.ondpaddown = function (callback) {
  66075. this._ondpaddown = callback;
  66076. };
  66077. Xbox360Pad.prototype.ondpadup = function (callback) {
  66078. this._ondpadup = callback;
  66079. };
  66080. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  66081. if (newValue !== currentValue) {
  66082. if (newValue === 1) {
  66083. if (this._onbuttondown) {
  66084. this._onbuttondown(buttonType);
  66085. }
  66086. this.onButtonDownObservable.notifyObservers(buttonType);
  66087. }
  66088. if (newValue === 0) {
  66089. if (this._onbuttonup) {
  66090. this._onbuttonup(buttonType);
  66091. }
  66092. this.onButtonUpObservable.notifyObservers(buttonType);
  66093. }
  66094. }
  66095. return newValue;
  66096. };
  66097. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  66098. if (newValue !== currentValue) {
  66099. if (newValue === 1) {
  66100. if (this._ondpaddown) {
  66101. this._ondpaddown(buttonType);
  66102. }
  66103. this.onPadDownObservable.notifyObservers(buttonType);
  66104. }
  66105. if (newValue === 0) {
  66106. if (this._ondpadup) {
  66107. this._ondpadup(buttonType);
  66108. }
  66109. this.onPadUpObservable.notifyObservers(buttonType);
  66110. }
  66111. }
  66112. return newValue;
  66113. };
  66114. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  66115. get: function () {
  66116. return this._buttonA;
  66117. },
  66118. set: function (value) {
  66119. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  66120. },
  66121. enumerable: true,
  66122. configurable: true
  66123. });
  66124. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  66125. get: function () {
  66126. return this._buttonB;
  66127. },
  66128. set: function (value) {
  66129. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  66130. },
  66131. enumerable: true,
  66132. configurable: true
  66133. });
  66134. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  66135. get: function () {
  66136. return this._buttonX;
  66137. },
  66138. set: function (value) {
  66139. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  66140. },
  66141. enumerable: true,
  66142. configurable: true
  66143. });
  66144. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  66145. get: function () {
  66146. return this._buttonY;
  66147. },
  66148. set: function (value) {
  66149. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  66150. },
  66151. enumerable: true,
  66152. configurable: true
  66153. });
  66154. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  66155. get: function () {
  66156. return this._buttonStart;
  66157. },
  66158. set: function (value) {
  66159. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  66160. },
  66161. enumerable: true,
  66162. configurable: true
  66163. });
  66164. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  66165. get: function () {
  66166. return this._buttonBack;
  66167. },
  66168. set: function (value) {
  66169. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  66170. },
  66171. enumerable: true,
  66172. configurable: true
  66173. });
  66174. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  66175. get: function () {
  66176. return this._buttonLB;
  66177. },
  66178. set: function (value) {
  66179. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  66180. },
  66181. enumerable: true,
  66182. configurable: true
  66183. });
  66184. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  66185. get: function () {
  66186. return this._buttonRB;
  66187. },
  66188. set: function (value) {
  66189. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  66190. },
  66191. enumerable: true,
  66192. configurable: true
  66193. });
  66194. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  66195. get: function () {
  66196. return this._buttonLeftStick;
  66197. },
  66198. set: function (value) {
  66199. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  66200. },
  66201. enumerable: true,
  66202. configurable: true
  66203. });
  66204. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  66205. get: function () {
  66206. return this._buttonRightStick;
  66207. },
  66208. set: function (value) {
  66209. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  66210. },
  66211. enumerable: true,
  66212. configurable: true
  66213. });
  66214. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  66215. get: function () {
  66216. return this._dPadUp;
  66217. },
  66218. set: function (value) {
  66219. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  66220. },
  66221. enumerable: true,
  66222. configurable: true
  66223. });
  66224. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  66225. get: function () {
  66226. return this._dPadDown;
  66227. },
  66228. set: function (value) {
  66229. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  66230. },
  66231. enumerable: true,
  66232. configurable: true
  66233. });
  66234. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  66235. get: function () {
  66236. return this._dPadLeft;
  66237. },
  66238. set: function (value) {
  66239. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  66240. },
  66241. enumerable: true,
  66242. configurable: true
  66243. });
  66244. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  66245. get: function () {
  66246. return this._dPadRight;
  66247. },
  66248. set: function (value) {
  66249. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  66250. },
  66251. enumerable: true,
  66252. configurable: true
  66253. });
  66254. Xbox360Pad.prototype.update = function () {
  66255. _super.prototype.update.call(this);
  66256. if (this._isXboxOnePad) {
  66257. this.buttonA = this.browserGamepad.buttons[0].value;
  66258. this.buttonB = this.browserGamepad.buttons[1].value;
  66259. this.buttonX = this.browserGamepad.buttons[2].value;
  66260. this.buttonY = this.browserGamepad.buttons[3].value;
  66261. this.buttonLB = this.browserGamepad.buttons[4].value;
  66262. this.buttonRB = this.browserGamepad.buttons[5].value;
  66263. this.leftTrigger = this.browserGamepad.axes[2];
  66264. this.rightTrigger = this.browserGamepad.axes[5];
  66265. this.buttonBack = this.browserGamepad.buttons[9].value;
  66266. this.buttonStart = this.browserGamepad.buttons[8].value;
  66267. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  66268. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  66269. this.dPadUp = this.browserGamepad.buttons[11].value;
  66270. this.dPadDown = this.browserGamepad.buttons[12].value;
  66271. this.dPadLeft = this.browserGamepad.buttons[13].value;
  66272. this.dPadRight = this.browserGamepad.buttons[14].value;
  66273. }
  66274. else {
  66275. this.buttonA = this.browserGamepad.buttons[0].value;
  66276. this.buttonB = this.browserGamepad.buttons[1].value;
  66277. this.buttonX = this.browserGamepad.buttons[2].value;
  66278. this.buttonY = this.browserGamepad.buttons[3].value;
  66279. this.buttonLB = this.browserGamepad.buttons[4].value;
  66280. this.buttonRB = this.browserGamepad.buttons[5].value;
  66281. this.leftTrigger = this.browserGamepad.buttons[6].value;
  66282. this.rightTrigger = this.browserGamepad.buttons[7].value;
  66283. this.buttonBack = this.browserGamepad.buttons[8].value;
  66284. this.buttonStart = this.browserGamepad.buttons[9].value;
  66285. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  66286. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  66287. this.dPadUp = this.browserGamepad.buttons[12].value;
  66288. this.dPadDown = this.browserGamepad.buttons[13].value;
  66289. this.dPadLeft = this.browserGamepad.buttons[14].value;
  66290. this.dPadRight = this.browserGamepad.buttons[15].value;
  66291. }
  66292. };
  66293. Xbox360Pad.prototype.dispose = function () {
  66294. _super.prototype.dispose.call(this);
  66295. this.onButtonDownObservable.clear();
  66296. this.onButtonUpObservable.clear();
  66297. this.onPadDownObservable.clear();
  66298. this.onPadUpObservable.clear();
  66299. };
  66300. return Xbox360Pad;
  66301. }(BABYLON.Gamepad));
  66302. BABYLON.Xbox360Pad = Xbox360Pad;
  66303. })(BABYLON || (BABYLON = {}));
  66304. //# sourceMappingURL=babylon.xboxGamepad.js.map
  66305. "use strict";
  66306. var BABYLON;
  66307. (function (BABYLON) {
  66308. var PoseEnabledControllerType;
  66309. (function (PoseEnabledControllerType) {
  66310. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  66311. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  66312. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  66313. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  66314. /**
  66315. * Google Daydream
  66316. */
  66317. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  66318. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  66319. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  66320. var PoseEnabledControllerHelper = /** @class */ (function () {
  66321. function PoseEnabledControllerHelper() {
  66322. }
  66323. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  66324. // Oculus Touch
  66325. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  66326. return new BABYLON.OculusTouchController(vrGamepad);
  66327. }
  66328. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  66329. return new BABYLON.WindowsMotionController(vrGamepad);
  66330. }
  66331. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  66332. return new BABYLON.ViveController(vrGamepad);
  66333. }
  66334. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  66335. return new BABYLON.GearVRController(vrGamepad);
  66336. }
  66337. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  66338. return new BABYLON.DaydreamController(vrGamepad);
  66339. }
  66340. else {
  66341. return new BABYLON.GenericController(vrGamepad);
  66342. }
  66343. };
  66344. return PoseEnabledControllerHelper;
  66345. }());
  66346. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  66347. var PoseEnabledController = /** @class */ (function (_super) {
  66348. __extends(PoseEnabledController, _super);
  66349. function PoseEnabledController(browserGamepad) {
  66350. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  66351. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  66352. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  66353. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  66354. // Represents device position and rotation in babylon space
  66355. _this.devicePosition = BABYLON.Vector3.Zero();
  66356. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  66357. _this.deviceScaleFactor = 1;
  66358. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  66359. _this._deviceToWorld = BABYLON.Matrix.Identity();
  66360. /**
  66361. * Node to be used when casting a ray from the controller
  66362. */
  66363. _this._pointingPoseNode = null;
  66364. _this._workingMatrix = BABYLON.Matrix.Identity();
  66365. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  66366. _this.controllerType = PoseEnabledControllerType.GENERIC;
  66367. _this.position = BABYLON.Vector3.Zero();
  66368. _this.rotationQuaternion = new BABYLON.Quaternion();
  66369. _this._calculatedPosition = BABYLON.Vector3.Zero();
  66370. _this._calculatedRotation = new BABYLON.Quaternion();
  66371. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  66372. return _this;
  66373. }
  66374. PoseEnabledController.prototype.update = function () {
  66375. _super.prototype.update.call(this);
  66376. var pose = this.browserGamepad.pose;
  66377. this.updateFromDevice(pose);
  66378. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  66379. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  66380. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  66381. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  66382. if (this._mesh) {
  66383. this._mesh.position.copyFrom(this.devicePosition);
  66384. if (this._mesh.rotationQuaternion) {
  66385. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  66386. }
  66387. }
  66388. };
  66389. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  66390. if (poseData) {
  66391. this.rawPose = poseData;
  66392. if (poseData.position) {
  66393. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  66394. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  66395. this._deviceRoomPosition.z *= -1;
  66396. }
  66397. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  66398. this._calculatedPosition.addInPlace(this.position);
  66399. }
  66400. var pose = this.rawPose;
  66401. if (poseData.orientation && pose.orientation) {
  66402. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  66403. if (this._mesh) {
  66404. if (this._mesh.getScene().useRightHandedSystem) {
  66405. this._deviceRoomRotationQuaternion.z *= -1;
  66406. this._deviceRoomRotationQuaternion.w *= -1;
  66407. }
  66408. else {
  66409. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  66410. }
  66411. }
  66412. // if the camera is set, rotate to the camera's rotation
  66413. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  66414. }
  66415. }
  66416. };
  66417. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  66418. if (this._mesh) {
  66419. this._mesh.parent = null;
  66420. }
  66421. this._mesh = mesh;
  66422. if (this._poseControlledCamera) {
  66423. this._mesh.parent = this._poseControlledCamera;
  66424. }
  66425. if (!this._mesh.rotationQuaternion) {
  66426. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  66427. }
  66428. };
  66429. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  66430. this._poseControlledCamera = camera;
  66431. if (this._mesh) {
  66432. this._mesh.parent = this._poseControlledCamera;
  66433. }
  66434. };
  66435. PoseEnabledController.prototype.dispose = function () {
  66436. if (this._mesh) {
  66437. this._mesh.dispose();
  66438. }
  66439. this._mesh = null;
  66440. _super.prototype.dispose.call(this);
  66441. };
  66442. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  66443. get: function () {
  66444. return this._mesh;
  66445. },
  66446. enumerable: true,
  66447. configurable: true
  66448. });
  66449. PoseEnabledController.prototype.getForwardRay = function (length) {
  66450. if (length === void 0) { length = 100; }
  66451. if (!this.mesh) {
  66452. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  66453. }
  66454. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  66455. var origin = m.getTranslation();
  66456. var forward = new BABYLON.Vector3(0, 0, -1);
  66457. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  66458. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  66459. return new BABYLON.Ray(origin, direction, length);
  66460. };
  66461. /**
  66462. * Name of the child mesh that can be used to cast a ray from the controller
  66463. */
  66464. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  66465. return PoseEnabledController;
  66466. }(BABYLON.Gamepad));
  66467. BABYLON.PoseEnabledController = PoseEnabledController;
  66468. })(BABYLON || (BABYLON = {}));
  66469. //# sourceMappingURL=babylon.poseEnabledController.js.map
  66470. "use strict";
  66471. var BABYLON;
  66472. (function (BABYLON) {
  66473. var WebVRController = /** @class */ (function (_super) {
  66474. __extends(WebVRController, _super);
  66475. function WebVRController(vrGamepad) {
  66476. var _this = _super.call(this, vrGamepad) || this;
  66477. // Observables
  66478. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  66479. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  66480. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  66481. _this.onPadStateChangedObservable = new BABYLON.Observable();
  66482. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  66483. _this.pad = { x: 0, y: 0 };
  66484. // avoid GC, store state in a tmp object
  66485. _this._changes = {
  66486. pressChanged: false,
  66487. touchChanged: false,
  66488. valueChanged: false,
  66489. changed: false
  66490. };
  66491. _this._buttons = new Array(vrGamepad.buttons.length);
  66492. _this.hand = vrGamepad.hand;
  66493. return _this;
  66494. }
  66495. WebVRController.prototype.onButtonStateChange = function (callback) {
  66496. this._onButtonStateChange = callback;
  66497. };
  66498. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  66499. get: function () {
  66500. return this._defaultModel;
  66501. },
  66502. enumerable: true,
  66503. configurable: true
  66504. });
  66505. WebVRController.prototype.update = function () {
  66506. _super.prototype.update.call(this);
  66507. for (var index = 0; index < this._buttons.length; index++) {
  66508. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  66509. }
  66510. ;
  66511. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  66512. this.pad.x = this.leftStick.x;
  66513. this.pad.y = this.leftStick.y;
  66514. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  66515. }
  66516. };
  66517. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  66518. if (!newState) {
  66519. newState = {
  66520. pressed: false,
  66521. touched: false,
  66522. value: 0
  66523. };
  66524. }
  66525. if (!currentState) {
  66526. this._buttons[buttonIndex] = {
  66527. pressed: newState.pressed,
  66528. touched: newState.touched,
  66529. value: newState.value
  66530. };
  66531. return;
  66532. }
  66533. this._checkChanges(newState, currentState);
  66534. if (this._changes.changed) {
  66535. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  66536. this._handleButtonChange(buttonIndex, newState, this._changes);
  66537. }
  66538. this._buttons[buttonIndex].pressed = newState.pressed;
  66539. this._buttons[buttonIndex].touched = newState.touched;
  66540. // oculus triggers are never 0, thou not touched.
  66541. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  66542. };
  66543. WebVRController.prototype._checkChanges = function (newState, currentState) {
  66544. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  66545. this._changes.touchChanged = newState.touched !== currentState.touched;
  66546. this._changes.valueChanged = newState.value !== currentState.value;
  66547. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  66548. return this._changes;
  66549. };
  66550. WebVRController.prototype.dispose = function () {
  66551. _super.prototype.dispose.call(this);
  66552. this.onTriggerStateChangedObservable.clear();
  66553. this.onMainButtonStateChangedObservable.clear();
  66554. this.onSecondaryButtonStateChangedObservable.clear();
  66555. this.onPadStateChangedObservable.clear();
  66556. this.onPadValuesChangedObservable.clear();
  66557. };
  66558. return WebVRController;
  66559. }(BABYLON.PoseEnabledController));
  66560. BABYLON.WebVRController = WebVRController;
  66561. })(BABYLON || (BABYLON = {}));
  66562. //# sourceMappingURL=babylon.webVRController.js.map
  66563. "use strict";
  66564. var BABYLON;
  66565. (function (BABYLON) {
  66566. var OculusTouchController = /** @class */ (function (_super) {
  66567. __extends(OculusTouchController, _super);
  66568. function OculusTouchController(vrGamepad) {
  66569. var _this = _super.call(this, vrGamepad) || this;
  66570. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  66571. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  66572. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  66573. return _this;
  66574. }
  66575. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66576. var _this = this;
  66577. var meshName;
  66578. // Hand
  66579. if (this.hand === 'left') {
  66580. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  66581. }
  66582. else {
  66583. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  66584. }
  66585. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  66586. /*
  66587. Parent Mesh name: oculus_touch_left
  66588. - body
  66589. - trigger
  66590. - thumbstick
  66591. - grip
  66592. - button_y
  66593. - button_x
  66594. - button_enter
  66595. */
  66596. _this._defaultModel = newMeshes[1];
  66597. _this.attachToMesh(_this._defaultModel);
  66598. if (meshLoaded) {
  66599. meshLoaded(_this._defaultModel);
  66600. }
  66601. });
  66602. };
  66603. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  66604. // helper getters for left and right hand.
  66605. get: function () {
  66606. if (this.hand === 'right') {
  66607. return this.onMainButtonStateChangedObservable;
  66608. }
  66609. else {
  66610. throw new Error('No A button on left hand');
  66611. }
  66612. },
  66613. enumerable: true,
  66614. configurable: true
  66615. });
  66616. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  66617. get: function () {
  66618. if (this.hand === 'right') {
  66619. return this.onSecondaryButtonStateChangedObservable;
  66620. }
  66621. else {
  66622. throw new Error('No B button on left hand');
  66623. }
  66624. },
  66625. enumerable: true,
  66626. configurable: true
  66627. });
  66628. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  66629. get: function () {
  66630. if (this.hand === 'left') {
  66631. return this.onMainButtonStateChangedObservable;
  66632. }
  66633. else {
  66634. throw new Error('No X button on right hand');
  66635. }
  66636. },
  66637. enumerable: true,
  66638. configurable: true
  66639. });
  66640. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  66641. get: function () {
  66642. if (this.hand === 'left') {
  66643. return this.onSecondaryButtonStateChangedObservable;
  66644. }
  66645. else {
  66646. throw new Error('No Y button on right hand');
  66647. }
  66648. },
  66649. enumerable: true,
  66650. configurable: true
  66651. });
  66652. /*
  66653. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  66654. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  66655. 2) secondary trigger (same)
  66656. 3) A (right) X (left), touch, pressed = value
  66657. 4) B / Y
  66658. 5) thumb rest
  66659. */
  66660. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66661. var notifyObject = state; //{ state: state, changes: changes };
  66662. var triggerDirection = this.hand === 'right' ? -1 : 1;
  66663. switch (buttonIdx) {
  66664. case 0:
  66665. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  66666. return;
  66667. case 1:// index trigger
  66668. if (this._defaultModel) {
  66669. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  66670. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  66671. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  66672. }
  66673. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  66674. return;
  66675. case 2:// secondary trigger
  66676. if (this._defaultModel) {
  66677. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  66678. }
  66679. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  66680. return;
  66681. case 3:
  66682. if (this._defaultModel) {
  66683. if (notifyObject.pressed) {
  66684. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  66685. }
  66686. else {
  66687. (this._defaultModel.getChildren()[1]).position.y = 0;
  66688. }
  66689. }
  66690. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  66691. return;
  66692. case 4:
  66693. if (this._defaultModel) {
  66694. if (notifyObject.pressed) {
  66695. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  66696. }
  66697. else {
  66698. (this._defaultModel.getChildren()[2]).position.y = 0;
  66699. }
  66700. }
  66701. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  66702. return;
  66703. case 5:
  66704. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  66705. return;
  66706. }
  66707. };
  66708. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  66709. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  66710. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  66711. return OculusTouchController;
  66712. }(BABYLON.WebVRController));
  66713. BABYLON.OculusTouchController = OculusTouchController;
  66714. })(BABYLON || (BABYLON = {}));
  66715. //# sourceMappingURL=babylon.oculusTouchController.js.map
  66716. "use strict";
  66717. var BABYLON;
  66718. (function (BABYLON) {
  66719. var ViveController = /** @class */ (function (_super) {
  66720. __extends(ViveController, _super);
  66721. function ViveController(vrGamepad) {
  66722. var _this = _super.call(this, vrGamepad) || this;
  66723. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  66724. _this._invertLeftStickY = true;
  66725. return _this;
  66726. }
  66727. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66728. var _this = this;
  66729. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  66730. /*
  66731. Parent Mesh name: ViveWand
  66732. - body
  66733. - r_gripper
  66734. - l_gripper
  66735. - menu_button
  66736. - system_button
  66737. - trackpad
  66738. - trigger
  66739. - LED
  66740. */
  66741. _this._defaultModel = newMeshes[1];
  66742. _this.attachToMesh(_this._defaultModel);
  66743. if (meshLoaded) {
  66744. meshLoaded(_this._defaultModel);
  66745. }
  66746. });
  66747. };
  66748. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  66749. get: function () {
  66750. return this.onMainButtonStateChangedObservable;
  66751. },
  66752. enumerable: true,
  66753. configurable: true
  66754. });
  66755. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  66756. get: function () {
  66757. return this.onMainButtonStateChangedObservable;
  66758. },
  66759. enumerable: true,
  66760. configurable: true
  66761. });
  66762. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  66763. get: function () {
  66764. return this.onSecondaryButtonStateChangedObservable;
  66765. },
  66766. enumerable: true,
  66767. configurable: true
  66768. });
  66769. /**
  66770. * Vive mapping:
  66771. * 0: touchpad
  66772. * 1: trigger
  66773. * 2: left AND right buttons
  66774. * 3: menu button
  66775. */
  66776. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66777. var notifyObject = state; //{ state: state, changes: changes };
  66778. switch (buttonIdx) {
  66779. case 0:
  66780. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  66781. return;
  66782. case 1:// index trigger
  66783. if (this._defaultModel) {
  66784. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  66785. }
  66786. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  66787. return;
  66788. case 2:// left AND right button
  66789. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  66790. return;
  66791. case 3:
  66792. if (this._defaultModel) {
  66793. if (notifyObject.pressed) {
  66794. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  66795. }
  66796. else {
  66797. (this._defaultModel.getChildren()[2]).position.y = 0;
  66798. }
  66799. }
  66800. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  66801. return;
  66802. }
  66803. };
  66804. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  66805. ViveController.MODEL_FILENAME = 'wand.babylon';
  66806. return ViveController;
  66807. }(BABYLON.WebVRController));
  66808. BABYLON.ViveController = ViveController;
  66809. })(BABYLON || (BABYLON = {}));
  66810. //# sourceMappingURL=babylon.viveController.js.map
  66811. "use strict";
  66812. var BABYLON;
  66813. (function (BABYLON) {
  66814. var GenericController = /** @class */ (function (_super) {
  66815. __extends(GenericController, _super);
  66816. function GenericController(vrGamepad) {
  66817. return _super.call(this, vrGamepad) || this;
  66818. }
  66819. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66820. var _this = this;
  66821. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  66822. _this._defaultModel = newMeshes[1];
  66823. _this.attachToMesh(_this._defaultModel);
  66824. if (meshLoaded) {
  66825. meshLoaded(_this._defaultModel);
  66826. }
  66827. });
  66828. };
  66829. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66830. console.log("Button id: " + buttonIdx + "state: ");
  66831. console.dir(state);
  66832. };
  66833. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66834. GenericController.MODEL_FILENAME = 'generic.babylon';
  66835. return GenericController;
  66836. }(BABYLON.WebVRController));
  66837. BABYLON.GenericController = GenericController;
  66838. })(BABYLON || (BABYLON = {}));
  66839. //# sourceMappingURL=babylon.genericController.js.map
  66840. "use strict";
  66841. var BABYLON;
  66842. (function (BABYLON) {
  66843. var LoadedMeshInfo = /** @class */ (function () {
  66844. function LoadedMeshInfo() {
  66845. this.buttonMeshes = {};
  66846. this.axisMeshes = {};
  66847. }
  66848. return LoadedMeshInfo;
  66849. }());
  66850. var WindowsMotionController = /** @class */ (function (_super) {
  66851. __extends(WindowsMotionController, _super);
  66852. function WindowsMotionController(vrGamepad) {
  66853. var _this = _super.call(this, vrGamepad) || this;
  66854. _this._mapping = {
  66855. // Semantic button names
  66856. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  66857. // A mapping of the button name to glTF model node name
  66858. // that should be transformed by button value.
  66859. buttonMeshNames: {
  66860. 'trigger': 'SELECT',
  66861. 'menu': 'MENU',
  66862. 'grip': 'GRASP',
  66863. 'thumbstick': 'THUMBSTICK_PRESS',
  66864. 'trackpad': 'TOUCHPAD_PRESS'
  66865. },
  66866. // This mapping is used to translate from the Motion Controller to Babylon semantics
  66867. buttonObservableNames: {
  66868. 'trigger': 'onTriggerStateChangedObservable',
  66869. 'menu': 'onSecondaryButtonStateChangedObservable',
  66870. 'grip': 'onMainButtonStateChangedObservable',
  66871. 'thumbstick': 'onPadStateChangedObservable',
  66872. 'trackpad': 'onTrackpadChangedObservable'
  66873. },
  66874. // A mapping of the axis name to glTF model node name
  66875. // that should be transformed by axis value.
  66876. // This array mirrors the browserGamepad.axes array, such that
  66877. // the mesh corresponding to axis 0 is in this array index 0.
  66878. axisMeshNames: [
  66879. 'THUMBSTICK_X',
  66880. 'THUMBSTICK_Y',
  66881. 'TOUCHPAD_TOUCH_X',
  66882. 'TOUCHPAD_TOUCH_Y'
  66883. ],
  66884. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  66885. };
  66886. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  66887. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  66888. _this.trackpad = { x: 0, y: 0 };
  66889. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  66890. _this._loadedMeshInfo = null;
  66891. return _this;
  66892. }
  66893. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  66894. get: function () {
  66895. return this.onTriggerStateChangedObservable;
  66896. },
  66897. enumerable: true,
  66898. configurable: true
  66899. });
  66900. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  66901. get: function () {
  66902. return this.onSecondaryButtonStateChangedObservable;
  66903. },
  66904. enumerable: true,
  66905. configurable: true
  66906. });
  66907. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  66908. get: function () {
  66909. return this.onMainButtonStateChangedObservable;
  66910. },
  66911. enumerable: true,
  66912. configurable: true
  66913. });
  66914. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  66915. get: function () {
  66916. return this.onPadStateChangedObservable;
  66917. },
  66918. enumerable: true,
  66919. configurable: true
  66920. });
  66921. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  66922. get: function () {
  66923. return this.onTrackpadChangedObservable;
  66924. },
  66925. enumerable: true,
  66926. configurable: true
  66927. });
  66928. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  66929. get: function () {
  66930. return this.onTrackpadValuesChangedObservable;
  66931. },
  66932. enumerable: true,
  66933. configurable: true
  66934. });
  66935. /**
  66936. * Called once per frame by the engine.
  66937. */
  66938. WindowsMotionController.prototype.update = function () {
  66939. _super.prototype.update.call(this);
  66940. if (this.browserGamepad.axes) {
  66941. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  66942. this.trackpad.x = this.browserGamepad["axes"][2];
  66943. this.trackpad.y = this.browserGamepad["axes"][3];
  66944. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  66945. }
  66946. // Only need to animate axes if there is a loaded mesh
  66947. if (this._loadedMeshInfo) {
  66948. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  66949. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  66950. }
  66951. }
  66952. }
  66953. };
  66954. /**
  66955. * Called once for each button that changed state since the last frame
  66956. * @param buttonIdx Which button index changed
  66957. * @param state New state of the button
  66958. * @param changes Which properties on the state changed since last frame
  66959. */
  66960. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66961. var buttonName = this._mapping.buttons[buttonIdx];
  66962. if (!buttonName) {
  66963. return;
  66964. }
  66965. // Only emit events for buttons that we know how to map from index to name
  66966. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  66967. if (observable) {
  66968. observable.notifyObservers(state);
  66969. }
  66970. this.lerpButtonTransform(buttonName, state.value);
  66971. };
  66972. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  66973. // If there is no loaded mesh, there is nothing to transform.
  66974. if (!this._loadedMeshInfo) {
  66975. return;
  66976. }
  66977. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  66978. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  66979. return;
  66980. }
  66981. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  66982. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  66983. };
  66984. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  66985. if (!this._loadedMeshInfo) {
  66986. return;
  66987. }
  66988. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  66989. if (!meshInfo) {
  66990. return;
  66991. }
  66992. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  66993. return;
  66994. }
  66995. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  66996. var lerpValue = axisValue * 0.5 + 0.5;
  66997. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  66998. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  66999. };
  67000. /**
  67001. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  67002. * @param scene scene in which to add meshes
  67003. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  67004. */
  67005. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  67006. var _this = this;
  67007. if (forceDefault === void 0) { forceDefault = false; }
  67008. var path;
  67009. var filename;
  67010. // Checking if GLB loader is present
  67011. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  67012. // Determine the device specific folder based on the ID suffix
  67013. var device = 'default';
  67014. if (this.id && !forceDefault) {
  67015. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  67016. device = ((match && match[0]) || device);
  67017. }
  67018. // Hand
  67019. if (this.hand === 'left') {
  67020. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  67021. }
  67022. else {
  67023. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  67024. }
  67025. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  67026. }
  67027. else {
  67028. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  67029. path = BABYLON.GenericController.MODEL_BASE_URL;
  67030. filename = BABYLON.GenericController.MODEL_FILENAME;
  67031. }
  67032. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  67033. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  67034. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  67035. if (!_this._loadedMeshInfo) {
  67036. return;
  67037. }
  67038. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  67039. _this.attachToMesh(_this._defaultModel);
  67040. if (meshLoaded) {
  67041. meshLoaded(_this._defaultModel);
  67042. }
  67043. }, null, function (scene, message) {
  67044. BABYLON.Tools.Log(message);
  67045. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  67046. if (!forceDefault) {
  67047. _this.initControllerMesh(scene, meshLoaded, true);
  67048. }
  67049. });
  67050. };
  67051. /**
  67052. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  67053. * can be transformed by button presses and axes values, based on this._mapping.
  67054. *
  67055. * @param scene scene in which the meshes exist
  67056. * @param meshes list of meshes that make up the controller model to process
  67057. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  67058. */
  67059. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  67060. var loadedMeshInfo = null;
  67061. // Create a new mesh to contain the glTF hierarchy
  67062. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  67063. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  67064. var childMesh = null;
  67065. for (var i = 0; i < meshes.length; i++) {
  67066. var mesh = meshes[i];
  67067. if (!mesh.parent) {
  67068. // Exclude controller meshes from picking results
  67069. mesh.isPickable = false;
  67070. // Handle root node, attach to the new parentMesh
  67071. childMesh = mesh;
  67072. break;
  67073. }
  67074. }
  67075. if (childMesh) {
  67076. childMesh.setParent(parentMesh);
  67077. // Create our mesh info. Note that this method will always return non-null.
  67078. loadedMeshInfo = this.createMeshInfo(parentMesh);
  67079. }
  67080. else {
  67081. BABYLON.Tools.Warn('Could not find root node in model file.');
  67082. }
  67083. return loadedMeshInfo;
  67084. };
  67085. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  67086. var loadedMeshInfo = new LoadedMeshInfo();
  67087. var i;
  67088. loadedMeshInfo.rootNode = rootNode;
  67089. // Reset the caches
  67090. loadedMeshInfo.buttonMeshes = {};
  67091. loadedMeshInfo.axisMeshes = {};
  67092. // Button Meshes
  67093. for (i = 0; i < this._mapping.buttons.length; i++) {
  67094. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  67095. if (!buttonMeshName) {
  67096. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  67097. continue;
  67098. }
  67099. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  67100. if (!buttonMesh) {
  67101. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  67102. continue;
  67103. }
  67104. var buttonMeshInfo = {
  67105. index: i,
  67106. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  67107. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  67108. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  67109. };
  67110. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  67111. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  67112. }
  67113. else {
  67114. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  67115. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  67116. '(VALUE: ' + !!buttonMeshInfo.value +
  67117. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  67118. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  67119. ')');
  67120. }
  67121. }
  67122. // Axis Meshes
  67123. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  67124. var axisMeshName = this._mapping.axisMeshNames[i];
  67125. if (!axisMeshName) {
  67126. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  67127. continue;
  67128. }
  67129. var axisMesh = getChildByName(rootNode, axisMeshName);
  67130. if (!axisMesh) {
  67131. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  67132. continue;
  67133. }
  67134. var axisMeshInfo = {
  67135. index: i,
  67136. value: getImmediateChildByName(axisMesh, 'VALUE'),
  67137. min: getImmediateChildByName(axisMesh, 'MIN'),
  67138. max: getImmediateChildByName(axisMesh, 'MAX')
  67139. };
  67140. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  67141. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  67142. }
  67143. else {
  67144. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  67145. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  67146. '(VALUE: ' + !!axisMeshInfo.value +
  67147. ', MIN: ' + !!axisMeshInfo.min +
  67148. ', MAX:' + !!axisMeshInfo.max +
  67149. ')');
  67150. }
  67151. }
  67152. // Pointing Ray
  67153. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  67154. if (!loadedMeshInfo.pointingPoseNode) {
  67155. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  67156. }
  67157. return loadedMeshInfo;
  67158. // Look through all children recursively. This will return null if no mesh exists with the given name.
  67159. function getChildByName(node, name) {
  67160. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  67161. }
  67162. // Look through only immediate children. This will return null if no mesh exists with the given name.
  67163. function getImmediateChildByName(node, name) {
  67164. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  67165. }
  67166. };
  67167. WindowsMotionController.prototype.getForwardRay = function (length) {
  67168. if (length === void 0) { length = 100; }
  67169. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  67170. return _super.prototype.getForwardRay.call(this, length);
  67171. }
  67172. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  67173. var origin = m.getTranslation();
  67174. var forward = new BABYLON.Vector3(0, 0, -1);
  67175. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  67176. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  67177. return new BABYLON.Ray(origin, direction, length);
  67178. };
  67179. WindowsMotionController.prototype.dispose = function () {
  67180. _super.prototype.dispose.call(this);
  67181. this.onTrackpadChangedObservable.clear();
  67182. };
  67183. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  67184. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  67185. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  67186. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  67187. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  67188. return WindowsMotionController;
  67189. }(BABYLON.WebVRController));
  67190. BABYLON.WindowsMotionController = WindowsMotionController;
  67191. })(BABYLON || (BABYLON = {}));
  67192. //# sourceMappingURL=babylon.windowsMotionController.js.map
  67193. "use strict";
  67194. var BABYLON;
  67195. (function (BABYLON) {
  67196. var GearVRController = /** @class */ (function (_super) {
  67197. __extends(GearVRController, _super);
  67198. function GearVRController(vrGamepad) {
  67199. var _this = _super.call(this, vrGamepad) || this;
  67200. _this._buttonIndexToObservableNameMap = [
  67201. 'onTrackpadChangedObservable',
  67202. 'onTriggerStateChangedObservable' // Trigger
  67203. ];
  67204. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  67205. return _this;
  67206. }
  67207. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67208. var _this = this;
  67209. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  67210. _this._defaultModel = newMeshes[1];
  67211. _this.attachToMesh(_this._defaultModel);
  67212. if (meshLoaded) {
  67213. meshLoaded(_this._defaultModel);
  67214. }
  67215. });
  67216. };
  67217. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67218. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  67219. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  67220. // Only emit events for buttons that we know how to map from index to observable
  67221. var observable = this[observableName];
  67222. if (observable) {
  67223. observable.notifyObservers(state);
  67224. }
  67225. }
  67226. };
  67227. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67228. GearVRController.MODEL_FILENAME = 'generic.babylon';
  67229. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  67230. return GearVRController;
  67231. }(BABYLON.WebVRController));
  67232. BABYLON.GearVRController = GearVRController;
  67233. })(BABYLON || (BABYLON = {}));
  67234. //# sourceMappingURL=babylon.gearVRController.js.map
  67235. "use strict";
  67236. var BABYLON;
  67237. (function (BABYLON) {
  67238. /**
  67239. * Google Daydream controller
  67240. */
  67241. var DaydreamController = /** @class */ (function (_super) {
  67242. __extends(DaydreamController, _super);
  67243. function DaydreamController(vrGamepad) {
  67244. var _this = _super.call(this, vrGamepad) || this;
  67245. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  67246. return _this;
  67247. }
  67248. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67249. var _this = this;
  67250. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  67251. _this._defaultModel = newMeshes[1];
  67252. _this.attachToMesh(_this._defaultModel);
  67253. if (meshLoaded) {
  67254. meshLoaded(_this._defaultModel);
  67255. }
  67256. });
  67257. };
  67258. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67259. // Daydream controller only has 1 GamepadButton (on the trackpad).
  67260. if (buttonIdx === 0) {
  67261. var observable = this.onTriggerStateChangedObservable;
  67262. if (observable) {
  67263. observable.notifyObservers(state);
  67264. }
  67265. }
  67266. else {
  67267. // If the app or home buttons are ever made available
  67268. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  67269. }
  67270. };
  67271. /**
  67272. * Base Url for the controller model.
  67273. */
  67274. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67275. /**
  67276. * File name for the controller model.
  67277. */
  67278. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  67279. /**
  67280. * Gamepad Id prefix used to identify Daydream Controller.
  67281. */
  67282. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  67283. return DaydreamController;
  67284. }(BABYLON.WebVRController));
  67285. BABYLON.DaydreamController = DaydreamController;
  67286. })(BABYLON || (BABYLON = {}));
  67287. //# sourceMappingURL=babylon.daydreamController.js.map
  67288. "use strict";
  67289. var BABYLON;
  67290. (function (BABYLON) {
  67291. var FollowCamera = /** @class */ (function (_super) {
  67292. __extends(FollowCamera, _super);
  67293. function FollowCamera(name, position, scene, lockedTarget) {
  67294. if (lockedTarget === void 0) { lockedTarget = null; }
  67295. var _this = _super.call(this, name, position, scene) || this;
  67296. _this.radius = 12;
  67297. _this.rotationOffset = 0;
  67298. _this.heightOffset = 4;
  67299. _this.cameraAcceleration = 0.05;
  67300. _this.maxCameraSpeed = 20;
  67301. _this.lockedTarget = lockedTarget;
  67302. return _this;
  67303. }
  67304. FollowCamera.prototype.getRadians = function (degrees) {
  67305. return degrees * Math.PI / 180;
  67306. };
  67307. FollowCamera.prototype.follow = function (cameraTarget) {
  67308. if (!cameraTarget)
  67309. return;
  67310. var yRotation;
  67311. if (cameraTarget.rotationQuaternion) {
  67312. var rotMatrix = new BABYLON.Matrix();
  67313. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  67314. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  67315. }
  67316. else {
  67317. yRotation = cameraTarget.rotation.y;
  67318. }
  67319. var radians = this.getRadians(this.rotationOffset) + yRotation;
  67320. var targetPosition = cameraTarget.getAbsolutePosition();
  67321. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  67322. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  67323. var dx = targetX - this.position.x;
  67324. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  67325. var dz = (targetZ) - this.position.z;
  67326. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  67327. var vy = dy * this.cameraAcceleration;
  67328. var vz = dz * this.cameraAcceleration * 2;
  67329. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  67330. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67331. }
  67332. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  67333. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67334. }
  67335. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  67336. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67337. }
  67338. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  67339. this.setTarget(targetPosition);
  67340. };
  67341. FollowCamera.prototype._checkInputs = function () {
  67342. _super.prototype._checkInputs.call(this);
  67343. if (this.lockedTarget) {
  67344. this.follow(this.lockedTarget);
  67345. }
  67346. };
  67347. FollowCamera.prototype.getClassName = function () {
  67348. return "FollowCamera";
  67349. };
  67350. __decorate([
  67351. BABYLON.serialize()
  67352. ], FollowCamera.prototype, "radius", void 0);
  67353. __decorate([
  67354. BABYLON.serialize()
  67355. ], FollowCamera.prototype, "rotationOffset", void 0);
  67356. __decorate([
  67357. BABYLON.serialize()
  67358. ], FollowCamera.prototype, "heightOffset", void 0);
  67359. __decorate([
  67360. BABYLON.serialize()
  67361. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  67362. __decorate([
  67363. BABYLON.serialize()
  67364. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  67365. __decorate([
  67366. BABYLON.serializeAsMeshReference("lockedTargetId")
  67367. ], FollowCamera.prototype, "lockedTarget", void 0);
  67368. return FollowCamera;
  67369. }(BABYLON.TargetCamera));
  67370. BABYLON.FollowCamera = FollowCamera;
  67371. var ArcFollowCamera = /** @class */ (function (_super) {
  67372. __extends(ArcFollowCamera, _super);
  67373. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  67374. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  67375. _this.alpha = alpha;
  67376. _this.beta = beta;
  67377. _this.radius = radius;
  67378. _this.target = target;
  67379. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  67380. _this.follow();
  67381. return _this;
  67382. }
  67383. ArcFollowCamera.prototype.follow = function () {
  67384. if (!this.target) {
  67385. return;
  67386. }
  67387. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  67388. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  67389. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  67390. var targetPosition = this.target.getAbsolutePosition();
  67391. this.position = targetPosition.add(this._cartesianCoordinates);
  67392. this.setTarget(targetPosition);
  67393. };
  67394. ArcFollowCamera.prototype._checkInputs = function () {
  67395. _super.prototype._checkInputs.call(this);
  67396. this.follow();
  67397. };
  67398. ArcFollowCamera.prototype.getClassName = function () {
  67399. return "ArcFollowCamera";
  67400. };
  67401. return ArcFollowCamera;
  67402. }(BABYLON.TargetCamera));
  67403. BABYLON.ArcFollowCamera = ArcFollowCamera;
  67404. })(BABYLON || (BABYLON = {}));
  67405. //# sourceMappingURL=babylon.followCamera.js.map
  67406. "use strict";
  67407. var BABYLON;
  67408. (function (BABYLON) {
  67409. // We're mainly based on the logic defined into the FreeCamera code
  67410. var UniversalCamera = /** @class */ (function (_super) {
  67411. __extends(UniversalCamera, _super);
  67412. //-- end properties for backward compatibility for inputs
  67413. function UniversalCamera(name, position, scene) {
  67414. var _this = _super.call(this, name, position, scene) || this;
  67415. _this.inputs.addGamepad();
  67416. return _this;
  67417. }
  67418. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  67419. //-- Begin properties for backward compatibility for inputs
  67420. get: function () {
  67421. var gamepad = this.inputs.attached["gamepad"];
  67422. if (gamepad)
  67423. return gamepad.gamepadAngularSensibility;
  67424. return 0;
  67425. },
  67426. set: function (value) {
  67427. var gamepad = this.inputs.attached["gamepad"];
  67428. if (gamepad)
  67429. gamepad.gamepadAngularSensibility = value;
  67430. },
  67431. enumerable: true,
  67432. configurable: true
  67433. });
  67434. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  67435. get: function () {
  67436. var gamepad = this.inputs.attached["gamepad"];
  67437. if (gamepad)
  67438. return gamepad.gamepadMoveSensibility;
  67439. return 0;
  67440. },
  67441. set: function (value) {
  67442. var gamepad = this.inputs.attached["gamepad"];
  67443. if (gamepad)
  67444. gamepad.gamepadMoveSensibility = value;
  67445. },
  67446. enumerable: true,
  67447. configurable: true
  67448. });
  67449. UniversalCamera.prototype.getClassName = function () {
  67450. return "UniversalCamera";
  67451. };
  67452. return UniversalCamera;
  67453. }(BABYLON.TouchCamera));
  67454. BABYLON.UniversalCamera = UniversalCamera;
  67455. })(BABYLON || (BABYLON = {}));
  67456. //# sourceMappingURL=babylon.universalCamera.js.map
  67457. "use strict";
  67458. var BABYLON;
  67459. (function (BABYLON) {
  67460. // We're mainly based on the logic defined into the FreeCamera code
  67461. var GamepadCamera = /** @class */ (function (_super) {
  67462. __extends(GamepadCamera, _super);
  67463. //-- end properties for backward compatibility for inputs
  67464. function GamepadCamera(name, position, scene) {
  67465. return _super.call(this, name, position, scene) || this;
  67466. }
  67467. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  67468. //-- Begin properties for backward compatibility for inputs
  67469. get: function () {
  67470. var gamepad = this.inputs.attached["gamepad"];
  67471. if (gamepad)
  67472. return gamepad.gamepadAngularSensibility;
  67473. return 0;
  67474. },
  67475. set: function (value) {
  67476. var gamepad = this.inputs.attached["gamepad"];
  67477. if (gamepad)
  67478. gamepad.gamepadAngularSensibility = value;
  67479. },
  67480. enumerable: true,
  67481. configurable: true
  67482. });
  67483. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  67484. get: function () {
  67485. var gamepad = this.inputs.attached["gamepad"];
  67486. if (gamepad)
  67487. return gamepad.gamepadMoveSensibility;
  67488. return 0;
  67489. },
  67490. set: function (value) {
  67491. var gamepad = this.inputs.attached["gamepad"];
  67492. if (gamepad)
  67493. gamepad.gamepadMoveSensibility = value;
  67494. },
  67495. enumerable: true,
  67496. configurable: true
  67497. });
  67498. GamepadCamera.prototype.getClassName = function () {
  67499. return "GamepadCamera";
  67500. };
  67501. return GamepadCamera;
  67502. }(BABYLON.UniversalCamera));
  67503. BABYLON.GamepadCamera = GamepadCamera;
  67504. })(BABYLON || (BABYLON = {}));
  67505. //# sourceMappingURL=babylon.gamepadCamera.js.map
  67506. "use strict";
  67507. var BABYLON;
  67508. (function (BABYLON) {
  67509. var PostProcessRenderPipelineManager = /** @class */ (function () {
  67510. function PostProcessRenderPipelineManager() {
  67511. this._renderPipelines = {};
  67512. }
  67513. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  67514. this._renderPipelines[renderPipeline._name] = renderPipeline;
  67515. };
  67516. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  67517. if (unique === void 0) { unique = false; }
  67518. var renderPipeline = this._renderPipelines[renderPipelineName];
  67519. if (!renderPipeline) {
  67520. return;
  67521. }
  67522. renderPipeline._attachCameras(cameras, unique);
  67523. };
  67524. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  67525. var renderPipeline = this._renderPipelines[renderPipelineName];
  67526. if (!renderPipeline) {
  67527. return;
  67528. }
  67529. renderPipeline._detachCameras(cameras);
  67530. };
  67531. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  67532. var renderPipeline = this._renderPipelines[renderPipelineName];
  67533. if (!renderPipeline) {
  67534. return;
  67535. }
  67536. renderPipeline._enableEffect(renderEffectName, cameras);
  67537. };
  67538. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  67539. var renderPipeline = this._renderPipelines[renderPipelineName];
  67540. if (!renderPipeline) {
  67541. return;
  67542. }
  67543. renderPipeline._disableEffect(renderEffectName, cameras);
  67544. };
  67545. PostProcessRenderPipelineManager.prototype.update = function () {
  67546. for (var renderPipelineName in this._renderPipelines) {
  67547. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67548. var pipeline = this._renderPipelines[renderPipelineName];
  67549. if (!pipeline.isSupported) {
  67550. pipeline.dispose();
  67551. delete this._renderPipelines[renderPipelineName];
  67552. }
  67553. else {
  67554. pipeline._update();
  67555. }
  67556. }
  67557. }
  67558. };
  67559. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  67560. for (var renderPipelineName in this._renderPipelines) {
  67561. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67562. var pipeline = this._renderPipelines[renderPipelineName];
  67563. pipeline._rebuild();
  67564. }
  67565. }
  67566. };
  67567. PostProcessRenderPipelineManager.prototype.dispose = function () {
  67568. for (var renderPipelineName in this._renderPipelines) {
  67569. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67570. var pipeline = this._renderPipelines[renderPipelineName];
  67571. pipeline.dispose();
  67572. }
  67573. }
  67574. };
  67575. return PostProcessRenderPipelineManager;
  67576. }());
  67577. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  67578. })(BABYLON || (BABYLON = {}));
  67579. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  67580. "use strict";
  67581. var BABYLON;
  67582. (function (BABYLON) {
  67583. /**
  67584. * This represents a set of one or more post processes in Babylon.
  67585. * A post process can be used to apply a shader to a texture after it is rendered.
  67586. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  67587. */
  67588. var PostProcessRenderEffect = /** @class */ (function () {
  67589. /**
  67590. * Instantiates a post process render effect.
  67591. * A post process can be used to apply a shader to a texture after it is rendered.
  67592. * @param engine The engine the effect is tied to
  67593. * @param name The name of the effect
  67594. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  67595. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  67596. */
  67597. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  67598. this._name = name;
  67599. this._singleInstance = singleInstance || true;
  67600. this._getPostProcesses = getPostProcesses;
  67601. this._cameras = {};
  67602. this._indicesForCamera = {};
  67603. this._postProcesses = {};
  67604. }
  67605. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  67606. /**
  67607. * Checks if all the post processes in the effect are supported.
  67608. */
  67609. get: function () {
  67610. for (var index in this._postProcesses) {
  67611. for (var ppIndex in this._postProcesses[index]) {
  67612. if (!this._postProcesses[index][ppIndex].isSupported) {
  67613. return false;
  67614. }
  67615. }
  67616. }
  67617. return true;
  67618. },
  67619. enumerable: true,
  67620. configurable: true
  67621. });
  67622. /**
  67623. * Updates the current state of the effect
  67624. */
  67625. PostProcessRenderEffect.prototype._update = function () {
  67626. };
  67627. /**
  67628. * Attaches the effect on cameras
  67629. * @param cameras The camera to attach to.
  67630. */
  67631. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  67632. var _this = this;
  67633. var cameraKey;
  67634. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67635. if (!cams) {
  67636. return;
  67637. }
  67638. for (var i = 0; i < cams.length; i++) {
  67639. var camera = cams[i];
  67640. var cameraName = camera.name;
  67641. if (this._singleInstance) {
  67642. cameraKey = 0;
  67643. }
  67644. else {
  67645. cameraKey = cameraName;
  67646. }
  67647. if (!this._postProcesses[cameraKey]) {
  67648. var postProcess = this._getPostProcesses();
  67649. if (postProcess) {
  67650. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  67651. }
  67652. }
  67653. if (!this._indicesForCamera[cameraName]) {
  67654. this._indicesForCamera[cameraName] = [];
  67655. }
  67656. this._postProcesses[cameraKey].forEach(function (postProcess) {
  67657. var index = camera.attachPostProcess(postProcess);
  67658. _this._indicesForCamera[cameraName].push(index);
  67659. });
  67660. if (!this._cameras[cameraName]) {
  67661. this._cameras[cameraName] = camera;
  67662. }
  67663. }
  67664. };
  67665. /**
  67666. * Detatches the effect on cameras
  67667. * @param cameras The camera to detatch from.
  67668. */
  67669. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  67670. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67671. if (!cams) {
  67672. return;
  67673. }
  67674. for (var i = 0; i < cams.length; i++) {
  67675. var camera = cams[i];
  67676. var cameraName = camera.name;
  67677. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67678. camera.detachPostProcess(postProcess);
  67679. });
  67680. if (this._cameras[cameraName]) {
  67681. //this._indicesForCamera.splice(index, 1);
  67682. this._cameras[cameraName] = null;
  67683. }
  67684. }
  67685. };
  67686. /**
  67687. * Enables the effect on given cameras
  67688. * @param cameras The camera to enable.
  67689. */
  67690. PostProcessRenderEffect.prototype._enable = function (cameras) {
  67691. var _this = this;
  67692. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67693. if (!cams) {
  67694. return;
  67695. }
  67696. for (var i = 0; i < cams.length; i++) {
  67697. var camera = cams[i];
  67698. var cameraName = camera.name;
  67699. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  67700. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  67701. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67702. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  67703. });
  67704. }
  67705. }
  67706. }
  67707. };
  67708. /**
  67709. * Disables the effect on the given cameras
  67710. * @param cameras The camera to disable.
  67711. */
  67712. PostProcessRenderEffect.prototype._disable = function (cameras) {
  67713. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67714. if (!cams) {
  67715. return;
  67716. }
  67717. for (var i = 0; i < cams.length; i++) {
  67718. var camera = cams[i];
  67719. var cameraName = camera.name;
  67720. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67721. camera.detachPostProcess(postProcess);
  67722. });
  67723. }
  67724. };
  67725. /**
  67726. * Gets a list of the post processes contained in the effect.
  67727. * @param camera The camera to get the post processes on.
  67728. * @returns The list of the post processes in the effect.
  67729. */
  67730. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  67731. if (this._singleInstance) {
  67732. return this._postProcesses[0];
  67733. }
  67734. else {
  67735. if (!camera) {
  67736. return null;
  67737. }
  67738. return this._postProcesses[camera.name];
  67739. }
  67740. };
  67741. return PostProcessRenderEffect;
  67742. }());
  67743. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  67744. })(BABYLON || (BABYLON = {}));
  67745. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  67746. "use strict";
  67747. var BABYLON;
  67748. (function (BABYLON) {
  67749. var PostProcessRenderPipeline = /** @class */ (function () {
  67750. function PostProcessRenderPipeline(engine, name) {
  67751. this.engine = engine;
  67752. this._name = name;
  67753. this._renderEffects = {};
  67754. this._renderEffectsForIsolatedPass = new Array();
  67755. this._cameras = [];
  67756. }
  67757. PostProcessRenderPipeline.prototype.getClassName = function () {
  67758. return "PostProcessRenderPipeline";
  67759. };
  67760. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  67761. get: function () {
  67762. for (var renderEffectName in this._renderEffects) {
  67763. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67764. if (!this._renderEffects[renderEffectName].isSupported) {
  67765. return false;
  67766. }
  67767. }
  67768. }
  67769. return true;
  67770. },
  67771. enumerable: true,
  67772. configurable: true
  67773. });
  67774. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  67775. this._renderEffects[renderEffect._name] = renderEffect;
  67776. };
  67777. // private
  67778. PostProcessRenderPipeline.prototype._rebuild = function () {
  67779. };
  67780. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  67781. var renderEffects = this._renderEffects[renderEffectName];
  67782. if (!renderEffects) {
  67783. return;
  67784. }
  67785. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  67786. };
  67787. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  67788. var renderEffects = this._renderEffects[renderEffectName];
  67789. if (!renderEffects) {
  67790. return;
  67791. }
  67792. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  67793. };
  67794. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  67795. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67796. if (!cams) {
  67797. return;
  67798. }
  67799. var indicesToDelete = [];
  67800. var i;
  67801. for (i = 0; i < cams.length; i++) {
  67802. var camera = cams[i];
  67803. var cameraName = camera.name;
  67804. if (this._cameras.indexOf(camera) === -1) {
  67805. this._cameras[cameraName] = camera;
  67806. }
  67807. else if (unique) {
  67808. indicesToDelete.push(i);
  67809. }
  67810. }
  67811. for (i = 0; i < indicesToDelete.length; i++) {
  67812. cameras.splice(indicesToDelete[i], 1);
  67813. }
  67814. for (var renderEffectName in this._renderEffects) {
  67815. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67816. this._renderEffects[renderEffectName]._attachCameras(cams);
  67817. }
  67818. }
  67819. };
  67820. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  67821. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67822. if (!cams) {
  67823. return;
  67824. }
  67825. for (var renderEffectName in this._renderEffects) {
  67826. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67827. this._renderEffects[renderEffectName]._detachCameras(cams);
  67828. }
  67829. }
  67830. for (var i = 0; i < cams.length; i++) {
  67831. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  67832. }
  67833. };
  67834. PostProcessRenderPipeline.prototype._update = function () {
  67835. for (var renderEffectName in this._renderEffects) {
  67836. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67837. this._renderEffects[renderEffectName]._update();
  67838. }
  67839. }
  67840. for (var i = 0; i < this._cameras.length; i++) {
  67841. var cameraName = this._cameras[i].name;
  67842. if (this._renderEffectsForIsolatedPass[cameraName]) {
  67843. this._renderEffectsForIsolatedPass[cameraName]._update();
  67844. }
  67845. }
  67846. };
  67847. PostProcessRenderPipeline.prototype._reset = function () {
  67848. this._renderEffects = {};
  67849. this._renderEffectsForIsolatedPass = new Array();
  67850. };
  67851. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  67852. // 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)
  67853. var effectKeys = Object.keys(this._renderEffects);
  67854. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  67855. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  67856. if (postProcesses) {
  67857. postProcesses[0].samples = 4;
  67858. return true;
  67859. }
  67860. }
  67861. return false;
  67862. };
  67863. PostProcessRenderPipeline.prototype.dispose = function () {
  67864. // Must be implemented by children
  67865. };
  67866. __decorate([
  67867. BABYLON.serialize()
  67868. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  67869. return PostProcessRenderPipeline;
  67870. }());
  67871. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  67872. })(BABYLON || (BABYLON = {}));
  67873. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  67874. "use strict";
  67875. var BABYLON;
  67876. (function (BABYLON) {
  67877. /**
  67878. * This represents a depth renderer in Babylon.
  67879. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  67880. */
  67881. var DepthRenderer = /** @class */ (function () {
  67882. /**
  67883. * Instantiates a depth renderer
  67884. * @param scene The scene the renderer belongs to
  67885. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  67886. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  67887. */
  67888. function DepthRenderer(scene, type, camera) {
  67889. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  67890. if (camera === void 0) { camera = null; }
  67891. var _this = this;
  67892. this._scene = scene;
  67893. this._camera = camera;
  67894. var engine = scene.getEngine();
  67895. // Render target
  67896. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  67897. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67898. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67899. this._depthMap.refreshRate = 1;
  67900. this._depthMap.renderParticles = false;
  67901. this._depthMap.renderList = null;
  67902. // Camera to get depth map from to support multiple concurrent cameras
  67903. this._depthMap.activeCamera = this._camera;
  67904. this._depthMap.ignoreCameraViewport = true;
  67905. this._depthMap.useCameraPostProcesses = false;
  67906. // set default depth value to 1.0 (far away)
  67907. this._depthMap.onClearObservable.add(function (engine) {
  67908. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  67909. });
  67910. // Custom render function
  67911. var renderSubMesh = function (subMesh) {
  67912. var mesh = subMesh.getRenderingMesh();
  67913. var scene = _this._scene;
  67914. var engine = scene.getEngine();
  67915. var material = subMesh.getMaterial();
  67916. if (!material) {
  67917. return;
  67918. }
  67919. // Culling and reverse (right handed system)
  67920. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  67921. // Managing instances
  67922. var batch = mesh._getInstancesRenderList(subMesh._id);
  67923. if (batch.mustReturn) {
  67924. return;
  67925. }
  67926. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67927. var camera = _this._camera || scene.activeCamera;
  67928. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  67929. engine.enableEffect(_this._effect);
  67930. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  67931. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  67932. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  67933. // Alpha test
  67934. if (material && material.needAlphaTesting()) {
  67935. var alphaTexture = material.getAlphaTestTexture();
  67936. if (alphaTexture) {
  67937. _this._effect.setTexture("diffuseSampler", alphaTexture);
  67938. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67939. }
  67940. }
  67941. // Bones
  67942. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67943. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67944. }
  67945. // Draw
  67946. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  67947. }
  67948. };
  67949. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67950. var index;
  67951. if (depthOnlySubMeshes.length) {
  67952. engine.setColorWrite(false);
  67953. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67954. renderSubMesh(depthOnlySubMeshes.data[index]);
  67955. }
  67956. engine.setColorWrite(true);
  67957. }
  67958. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67959. renderSubMesh(opaqueSubMeshes.data[index]);
  67960. }
  67961. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67962. renderSubMesh(alphaTestSubMeshes.data[index]);
  67963. }
  67964. };
  67965. }
  67966. /**
  67967. * Creates the depth rendering effect and checks if the effect is ready.
  67968. * @param subMesh The submesh to be used to render the depth map of
  67969. * @param useInstances If multiple world instances should be used
  67970. * @returns if the depth renderer is ready to render the depth map
  67971. */
  67972. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  67973. var material = subMesh.getMaterial();
  67974. if (material.disableDepthWrite) {
  67975. return false;
  67976. }
  67977. var defines = [];
  67978. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67979. var mesh = subMesh.getMesh();
  67980. // Alpha test
  67981. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  67982. defines.push("#define ALPHATEST");
  67983. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67984. attribs.push(BABYLON.VertexBuffer.UVKind);
  67985. defines.push("#define UV1");
  67986. }
  67987. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67988. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67989. defines.push("#define UV2");
  67990. }
  67991. }
  67992. // Bones
  67993. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67994. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67995. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67996. if (mesh.numBoneInfluencers > 4) {
  67997. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67998. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67999. }
  68000. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68001. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  68002. }
  68003. else {
  68004. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68005. }
  68006. // Instances
  68007. if (useInstances) {
  68008. defines.push("#define INSTANCES");
  68009. attribs.push("world0");
  68010. attribs.push("world1");
  68011. attribs.push("world2");
  68012. attribs.push("world3");
  68013. }
  68014. // Get correct effect
  68015. var join = defines.join("\n");
  68016. if (this._cachedDefines !== join) {
  68017. this._cachedDefines = join;
  68018. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  68019. }
  68020. return this._effect.isReady();
  68021. };
  68022. /**
  68023. * Gets the texture which the depth map will be written to.
  68024. * @returns The depth map texture
  68025. */
  68026. DepthRenderer.prototype.getDepthMap = function () {
  68027. return this._depthMap;
  68028. };
  68029. /**
  68030. * Disposes of the depth renderer.
  68031. */
  68032. DepthRenderer.prototype.dispose = function () {
  68033. this._depthMap.dispose();
  68034. };
  68035. return DepthRenderer;
  68036. }());
  68037. BABYLON.DepthRenderer = DepthRenderer;
  68038. })(BABYLON || (BABYLON = {}));
  68039. //# sourceMappingURL=babylon.depthRenderer.js.map
  68040. "use strict";
  68041. var BABYLON;
  68042. (function (BABYLON) {
  68043. var SSAORenderingPipeline = /** @class */ (function (_super) {
  68044. __extends(SSAORenderingPipeline, _super);
  68045. /**
  68046. * @constructor
  68047. * @param {string} name - The rendering pipeline name
  68048. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68049. * @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 }
  68050. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68051. */
  68052. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  68053. var _this = _super.call(this, scene.getEngine(), name) || this;
  68054. // Members
  68055. /**
  68056. * The PassPostProcess id in the pipeline that contains the original scene color
  68057. * @type {string}
  68058. */
  68059. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  68060. /**
  68061. * The SSAO PostProcess id in the pipeline
  68062. * @type {string}
  68063. */
  68064. _this.SSAORenderEffect = "SSAORenderEffect";
  68065. /**
  68066. * The horizontal blur PostProcess id in the pipeline
  68067. * @type {string}
  68068. */
  68069. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  68070. /**
  68071. * The vertical blur PostProcess id in the pipeline
  68072. * @type {string}
  68073. */
  68074. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  68075. /**
  68076. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  68077. * @type {string}
  68078. */
  68079. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  68080. /**
  68081. * The output strength of the SSAO post-process. Default value is 1.0.
  68082. * @type {number}
  68083. */
  68084. _this.totalStrength = 1.0;
  68085. /**
  68086. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  68087. * @type {number}
  68088. */
  68089. _this.radius = 0.0001;
  68090. /**
  68091. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  68092. * Must not be equal to fallOff and superior to fallOff.
  68093. * Default value is 0.975
  68094. * @type {number}
  68095. */
  68096. _this.area = 0.0075;
  68097. /**
  68098. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  68099. * Must not be equal to area and inferior to area.
  68100. * Default value is 0.0
  68101. * @type {number}
  68102. */
  68103. _this.fallOff = 0.000001;
  68104. /**
  68105. * The base color of the SSAO post-process
  68106. * The final result is "base + ssao" between [0, 1]
  68107. * @type {number}
  68108. */
  68109. _this.base = 0.5;
  68110. _this._firstUpdate = true;
  68111. _this._scene = scene;
  68112. // Set up assets
  68113. _this._createRandomTexture();
  68114. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  68115. var ssaoRatio = ratio.ssaoRatio || ratio;
  68116. var combineRatio = ratio.combineRatio || ratio;
  68117. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  68118. _this._createSSAOPostProcess(ssaoRatio);
  68119. _this._createBlurPostProcess(ssaoRatio);
  68120. _this._createSSAOCombinePostProcess(combineRatio);
  68121. // Set up pipeline
  68122. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  68123. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  68124. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  68125. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  68126. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  68127. // Finish
  68128. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68129. if (cameras)
  68130. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68131. return _this;
  68132. }
  68133. // Public Methods
  68134. /**
  68135. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  68136. */
  68137. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  68138. if (disableDepthRender === void 0) { disableDepthRender = false; }
  68139. for (var i = 0; i < this._scene.cameras.length; i++) {
  68140. var camera = this._scene.cameras[i];
  68141. this._originalColorPostProcess.dispose(camera);
  68142. this._ssaoPostProcess.dispose(camera);
  68143. this._blurHPostProcess.dispose(camera);
  68144. this._blurVPostProcess.dispose(camera);
  68145. this._ssaoCombinePostProcess.dispose(camera);
  68146. }
  68147. this._randomTexture.dispose();
  68148. if (disableDepthRender)
  68149. this._scene.disableDepthRenderer();
  68150. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68151. _super.prototype.dispose.call(this);
  68152. };
  68153. // Private Methods
  68154. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  68155. var _this = this;
  68156. var size = 16;
  68157. 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);
  68158. 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);
  68159. this._blurHPostProcess.onActivateObservable.add(function () {
  68160. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  68161. _this._blurHPostProcess.kernel = size * dw;
  68162. });
  68163. this._blurVPostProcess.onActivateObservable.add(function () {
  68164. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  68165. _this._blurVPostProcess.kernel = size * dw;
  68166. });
  68167. };
  68168. SSAORenderingPipeline.prototype._rebuild = function () {
  68169. this._firstUpdate = true;
  68170. _super.prototype._rebuild.call(this);
  68171. };
  68172. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  68173. var _this = this;
  68174. var numSamples = 16;
  68175. var sampleSphere = [
  68176. 0.5381, 0.1856, -0.4319,
  68177. 0.1379, 0.2486, 0.4430,
  68178. 0.3371, 0.5679, -0.0057,
  68179. -0.6999, -0.0451, -0.0019,
  68180. 0.0689, -0.1598, -0.8547,
  68181. 0.0560, 0.0069, -0.1843,
  68182. -0.0146, 0.1402, 0.0762,
  68183. 0.0100, -0.1924, -0.0344,
  68184. -0.3577, -0.5301, -0.4358,
  68185. -0.3169, 0.1063, 0.0158,
  68186. 0.0103, -0.5869, 0.0046,
  68187. -0.0897, -0.4940, 0.3287,
  68188. 0.7119, -0.0154, -0.0918,
  68189. -0.0533, 0.0596, -0.5411,
  68190. 0.0352, -0.0631, 0.5460,
  68191. -0.4776, 0.2847, -0.0271
  68192. ];
  68193. var samplesFactor = 1.0 / numSamples;
  68194. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  68195. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  68196. "area", "fallOff", "base", "range", "viewport"
  68197. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  68198. this._ssaoPostProcess.onApply = function (effect) {
  68199. if (_this._firstUpdate) {
  68200. effect.setArray3("sampleSphere", sampleSphere);
  68201. effect.setFloat("samplesFactor", samplesFactor);
  68202. effect.setFloat("randTextureTiles", 4.0);
  68203. }
  68204. effect.setFloat("totalStrength", _this.totalStrength);
  68205. effect.setFloat("radius", _this.radius);
  68206. effect.setFloat("area", _this.area);
  68207. effect.setFloat("fallOff", _this.fallOff);
  68208. effect.setFloat("base", _this.base);
  68209. effect.setTexture("textureSampler", _this._depthTexture);
  68210. effect.setTexture("randomSampler", _this._randomTexture);
  68211. };
  68212. };
  68213. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  68214. var _this = this;
  68215. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68216. this._ssaoCombinePostProcess.onApply = function (effect) {
  68217. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  68218. };
  68219. };
  68220. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  68221. var size = 512;
  68222. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68223. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68224. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68225. var context = this._randomTexture.getContext();
  68226. var rand = function (min, max) {
  68227. return Math.random() * (max - min) + min;
  68228. };
  68229. var randVector = BABYLON.Vector3.Zero();
  68230. for (var x = 0; x < size; x++) {
  68231. for (var y = 0; y < size; y++) {
  68232. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  68233. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  68234. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  68235. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  68236. context.fillRect(x, y, 1, 1);
  68237. }
  68238. }
  68239. this._randomTexture.update(false);
  68240. };
  68241. __decorate([
  68242. BABYLON.serialize()
  68243. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  68244. __decorate([
  68245. BABYLON.serialize()
  68246. ], SSAORenderingPipeline.prototype, "radius", void 0);
  68247. __decorate([
  68248. BABYLON.serialize()
  68249. ], SSAORenderingPipeline.prototype, "area", void 0);
  68250. __decorate([
  68251. BABYLON.serialize()
  68252. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  68253. __decorate([
  68254. BABYLON.serialize()
  68255. ], SSAORenderingPipeline.prototype, "base", void 0);
  68256. return SSAORenderingPipeline;
  68257. }(BABYLON.PostProcessRenderPipeline));
  68258. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  68259. })(BABYLON || (BABYLON = {}));
  68260. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  68261. "use strict";
  68262. var BABYLON;
  68263. (function (BABYLON) {
  68264. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  68265. __extends(SSAO2RenderingPipeline, _super);
  68266. /**
  68267. * @constructor
  68268. * @param {string} name - The rendering pipeline name
  68269. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68270. * @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 }
  68271. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68272. */
  68273. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  68274. var _this = _super.call(this, scene.getEngine(), name) || this;
  68275. // Members
  68276. /**
  68277. * The PassPostProcess id in the pipeline that contains the original scene color
  68278. * @type {string}
  68279. */
  68280. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  68281. /**
  68282. * The SSAO PostProcess id in the pipeline
  68283. * @type {string}
  68284. */
  68285. _this.SSAORenderEffect = "SSAORenderEffect";
  68286. /**
  68287. * The horizontal blur PostProcess id in the pipeline
  68288. * @type {string}
  68289. */
  68290. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  68291. /**
  68292. * The vertical blur PostProcess id in the pipeline
  68293. * @type {string}
  68294. */
  68295. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  68296. /**
  68297. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  68298. * @type {string}
  68299. */
  68300. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  68301. /**
  68302. * The output strength of the SSAO post-process. Default value is 1.0.
  68303. * @type {number}
  68304. */
  68305. _this.totalStrength = 1.0;
  68306. /**
  68307. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  68308. * @type {number}
  68309. */
  68310. _this.maxZ = 100.0;
  68311. /**
  68312. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  68313. * @type {number}
  68314. */
  68315. _this.minZAspect = 0.2;
  68316. /**
  68317. * Number of samples used for the SSAO calculations. Default value is 8
  68318. * @type {number}
  68319. */
  68320. _this._samples = 8;
  68321. /**
  68322. * Are we using bilateral blur ?
  68323. * @type {boolean}
  68324. */
  68325. _this._expensiveBlur = true;
  68326. /**
  68327. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  68328. * @type {number}
  68329. */
  68330. _this.radius = 2.0;
  68331. /**
  68332. * The base color of the SSAO post-process
  68333. * The final result is "base + ssao" between [0, 1]
  68334. * @type {number}
  68335. */
  68336. _this.base = 0.1;
  68337. _this._firstUpdate = true;
  68338. _this._scene = scene;
  68339. if (!_this.isSupported) {
  68340. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  68341. return _this;
  68342. }
  68343. var ssaoRatio = ratio.ssaoRatio || ratio;
  68344. var blurRatio = ratio.blurRatio || ratio;
  68345. // Set up assets
  68346. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  68347. _this._createRandomTexture();
  68348. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  68349. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  68350. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  68351. _this._createSSAOPostProcess(1.0);
  68352. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  68353. _this._createSSAOCombinePostProcess(blurRatio);
  68354. // Set up pipeline
  68355. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  68356. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  68357. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  68358. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  68359. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  68360. // Finish
  68361. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68362. if (cameras)
  68363. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68364. return _this;
  68365. }
  68366. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  68367. get: function () {
  68368. return this._samples;
  68369. },
  68370. set: function (n) {
  68371. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  68372. this._samples = n;
  68373. this._sampleSphere = this._generateHemisphere();
  68374. this._firstUpdate = true;
  68375. },
  68376. enumerable: true,
  68377. configurable: true
  68378. });
  68379. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  68380. get: function () {
  68381. return this._expensiveBlur;
  68382. },
  68383. set: function (b) {
  68384. 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"]);
  68385. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  68386. this._expensiveBlur = b;
  68387. this._firstUpdate = true;
  68388. },
  68389. enumerable: true,
  68390. configurable: true
  68391. });
  68392. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  68393. /**
  68394. * Support test.
  68395. * @type {boolean}
  68396. */
  68397. get: function () {
  68398. var engine = BABYLON.Engine.LastCreatedEngine;
  68399. if (!engine) {
  68400. return false;
  68401. }
  68402. return engine.getCaps().drawBuffersExtension;
  68403. },
  68404. enumerable: true,
  68405. configurable: true
  68406. });
  68407. // Public Methods
  68408. /**
  68409. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  68410. */
  68411. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  68412. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  68413. for (var i = 0; i < this._scene.cameras.length; i++) {
  68414. var camera = this._scene.cameras[i];
  68415. this._originalColorPostProcess.dispose(camera);
  68416. this._ssaoPostProcess.dispose(camera);
  68417. this._blurHPostProcess.dispose(camera);
  68418. this._blurVPostProcess.dispose(camera);
  68419. this._ssaoCombinePostProcess.dispose(camera);
  68420. }
  68421. this._randomTexture.dispose();
  68422. if (disableGeometryBufferRenderer)
  68423. this._scene.disableGeometryBufferRenderer();
  68424. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68425. _super.prototype.dispose.call(this);
  68426. };
  68427. // Private Methods
  68428. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  68429. var _this = this;
  68430. this._samplerOffsets = [];
  68431. var expensive = this.expensiveBlur;
  68432. for (var i = -8; i < 8; i++) {
  68433. this._samplerOffsets.push(i * 2 + 0.5);
  68434. }
  68435. 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");
  68436. this._blurHPostProcess.onApply = function (effect) {
  68437. if (!_this._scene.activeCamera) {
  68438. return;
  68439. }
  68440. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  68441. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68442. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68443. effect.setFloat("radius", _this.radius);
  68444. effect.setTexture("depthSampler", _this._depthTexture);
  68445. if (_this._firstUpdate) {
  68446. effect.setArray("samplerOffsets", _this._samplerOffsets);
  68447. }
  68448. };
  68449. 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");
  68450. this._blurVPostProcess.onApply = function (effect) {
  68451. if (!_this._scene.activeCamera) {
  68452. return;
  68453. }
  68454. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  68455. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68456. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68457. effect.setFloat("radius", _this.radius);
  68458. effect.setTexture("depthSampler", _this._depthTexture);
  68459. if (_this._firstUpdate) {
  68460. effect.setArray("samplerOffsets", _this._samplerOffsets);
  68461. _this._firstUpdate = false;
  68462. }
  68463. };
  68464. };
  68465. SSAO2RenderingPipeline.prototype._rebuild = function () {
  68466. this._firstUpdate = true;
  68467. _super.prototype._rebuild.call(this);
  68468. };
  68469. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  68470. var numSamples = this.samples;
  68471. var result = [];
  68472. var vector, scale;
  68473. var rand = function (min, max) {
  68474. return Math.random() * (max - min) + min;
  68475. };
  68476. var i = 0;
  68477. while (i < numSamples) {
  68478. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  68479. vector.normalize();
  68480. scale = i / numSamples;
  68481. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  68482. vector.scaleInPlace(scale);
  68483. result.push(vector.x, vector.y, vector.z);
  68484. i++;
  68485. }
  68486. return result;
  68487. };
  68488. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  68489. var _this = this;
  68490. var numSamples = this.samples;
  68491. this._sampleSphere = this._generateHemisphere();
  68492. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  68493. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  68494. "base", "range", "projection", "near", "far", "texelSize",
  68495. "xViewport", "yViewport", "maxZ", "minZAspect"
  68496. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  68497. this._ssaoPostProcess.onApply = function (effect) {
  68498. if (_this._firstUpdate) {
  68499. effect.setArray3("sampleSphere", _this._sampleSphere);
  68500. effect.setFloat("randTextureTiles", 4.0);
  68501. }
  68502. if (!_this._scene.activeCamera) {
  68503. return;
  68504. }
  68505. effect.setFloat("samplesFactor", 1 / _this.samples);
  68506. effect.setFloat("totalStrength", _this.totalStrength);
  68507. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  68508. effect.setFloat("radius", _this.radius);
  68509. effect.setFloat("maxZ", _this.maxZ);
  68510. effect.setFloat("minZAspect", _this.minZAspect);
  68511. effect.setFloat("base", _this.base);
  68512. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68513. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68514. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  68515. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  68516. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  68517. effect.setTexture("textureSampler", _this._depthTexture);
  68518. effect.setTexture("normalSampler", _this._normalTexture);
  68519. effect.setTexture("randomSampler", _this._randomTexture);
  68520. };
  68521. };
  68522. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  68523. var _this = this;
  68524. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68525. this._ssaoCombinePostProcess.onApply = function (effect) {
  68526. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  68527. };
  68528. };
  68529. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  68530. var size = 512;
  68531. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68532. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68533. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68534. var context = this._randomTexture.getContext();
  68535. var rand = function (min, max) {
  68536. return Math.random() * (max - min) + min;
  68537. };
  68538. var randVector = BABYLON.Vector3.Zero();
  68539. for (var x = 0; x < size; x++) {
  68540. for (var y = 0; y < size; y++) {
  68541. randVector.x = rand(0.0, 1.0);
  68542. randVector.y = rand(0.0, 1.0);
  68543. randVector.z = 0.0;
  68544. randVector.normalize();
  68545. randVector.scaleInPlace(255);
  68546. randVector.x = Math.floor(randVector.x);
  68547. randVector.y = Math.floor(randVector.y);
  68548. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  68549. context.fillRect(x, y, 1, 1);
  68550. }
  68551. }
  68552. this._randomTexture.update(false);
  68553. };
  68554. __decorate([
  68555. BABYLON.serialize()
  68556. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  68557. __decorate([
  68558. BABYLON.serialize()
  68559. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  68560. __decorate([
  68561. BABYLON.serialize()
  68562. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  68563. __decorate([
  68564. BABYLON.serialize("samples")
  68565. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  68566. __decorate([
  68567. BABYLON.serialize("expensiveBlur")
  68568. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  68569. __decorate([
  68570. BABYLON.serialize()
  68571. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  68572. __decorate([
  68573. BABYLON.serialize()
  68574. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  68575. return SSAO2RenderingPipeline;
  68576. }(BABYLON.PostProcessRenderPipeline));
  68577. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  68578. })(BABYLON || (BABYLON = {}));
  68579. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  68580. "use strict";
  68581. // BABYLON.JS Chromatic Aberration GLSL Shader
  68582. // Author: Olivier Guyot
  68583. // Separates very slightly R, G and B colors on the edges of the screen
  68584. // Inspired by Francois Tarlier & Martins Upitis
  68585. var BABYLON;
  68586. (function (BABYLON) {
  68587. var LensRenderingPipeline = /** @class */ (function (_super) {
  68588. __extends(LensRenderingPipeline, _super);
  68589. /**
  68590. * @constructor
  68591. *
  68592. * Effect parameters are as follow:
  68593. * {
  68594. * chromatic_aberration: number; // from 0 to x (1 for realism)
  68595. * edge_blur: number; // from 0 to x (1 for realism)
  68596. * distortion: number; // from 0 to x (1 for realism)
  68597. * grain_amount: number; // from 0 to 1
  68598. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  68599. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  68600. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  68601. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  68602. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  68603. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  68604. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  68605. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  68606. * }
  68607. * Note: if an effect parameter is unset, effect is disabled
  68608. *
  68609. * @param {string} name - The rendering pipeline name
  68610. * @param {object} parameters - An object containing all parameters (see above)
  68611. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68612. * @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)
  68613. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68614. */
  68615. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  68616. if (ratio === void 0) { ratio = 1.0; }
  68617. var _this = _super.call(this, scene.getEngine(), name) || this;
  68618. // Lens effects can be of the following:
  68619. // - chromatic aberration (slight shift of RGB colors)
  68620. // - blur on the edge of the lens
  68621. // - lens distortion
  68622. // - depth-of-field blur & highlights enhancing
  68623. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  68624. // - grain effect (noise or custom texture)
  68625. // Two additional texture samplers are needed:
  68626. // - depth map (for depth-of-field)
  68627. // - grain texture
  68628. /**
  68629. * The chromatic aberration PostProcess id in the pipeline
  68630. * @type {string}
  68631. */
  68632. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  68633. /**
  68634. * The highlights enhancing PostProcess id in the pipeline
  68635. * @type {string}
  68636. */
  68637. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  68638. /**
  68639. * The depth-of-field PostProcess id in the pipeline
  68640. * @type {string}
  68641. */
  68642. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  68643. _this._scene = scene;
  68644. // Fetch texture samplers
  68645. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  68646. if (parameters.grain_texture) {
  68647. _this._grainTexture = parameters.grain_texture;
  68648. }
  68649. else {
  68650. _this._createGrainTexture();
  68651. }
  68652. // save parameters
  68653. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  68654. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  68655. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  68656. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  68657. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  68658. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  68659. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  68660. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  68661. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  68662. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  68663. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  68664. // Create effects
  68665. _this._createChromaticAberrationPostProcess(ratio);
  68666. _this._createHighlightsPostProcess(ratio);
  68667. _this._createDepthOfFieldPostProcess(ratio / 4);
  68668. // Set up pipeline
  68669. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  68670. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  68671. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  68672. if (_this._highlightsGain === -1) {
  68673. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  68674. }
  68675. // Finish
  68676. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68677. if (cameras) {
  68678. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68679. }
  68680. return _this;
  68681. }
  68682. // public methods (self explanatory)
  68683. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  68684. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  68685. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  68686. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  68687. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  68688. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  68689. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  68690. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  68691. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  68692. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  68693. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  68694. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  68695. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  68696. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  68697. };
  68698. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  68699. this._highlightsPostProcess.updateEffect();
  68700. };
  68701. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  68702. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  68703. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  68704. this._highlightsGain = amount;
  68705. };
  68706. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  68707. if (this._highlightsGain === -1) {
  68708. this._highlightsGain = 1.0;
  68709. }
  68710. this._highlightsThreshold = amount;
  68711. };
  68712. LensRenderingPipeline.prototype.disableHighlights = function () {
  68713. this._highlightsGain = -1;
  68714. };
  68715. /**
  68716. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  68717. */
  68718. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  68719. if (disableDepthRender === void 0) { disableDepthRender = false; }
  68720. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68721. this._chromaticAberrationPostProcess = null;
  68722. this._highlightsPostProcess = null;
  68723. this._depthOfFieldPostProcess = null;
  68724. this._grainTexture.dispose();
  68725. if (disableDepthRender)
  68726. this._scene.disableDepthRenderer();
  68727. };
  68728. // colors shifting and distortion
  68729. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  68730. var _this = this;
  68731. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  68732. [], // samplers
  68733. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68734. this._chromaticAberrationPostProcess.onApply = function (effect) {
  68735. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  68736. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68737. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68738. effect.setFloat('radialIntensity', 1);
  68739. effect.setFloat2('direction', 17, 17);
  68740. effect.setFloat2('centerPosition', 0.5, 0.5);
  68741. };
  68742. };
  68743. // highlights enhancing
  68744. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  68745. var _this = this;
  68746. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  68747. [], // samplers
  68748. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  68749. this._highlightsPostProcess.onApply = function (effect) {
  68750. effect.setFloat('gain', _this._highlightsGain);
  68751. effect.setFloat('threshold', _this._highlightsThreshold);
  68752. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  68753. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68754. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68755. };
  68756. };
  68757. // colors shifting and distortion
  68758. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  68759. var _this = this;
  68760. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  68761. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  68762. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  68763. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68764. this._depthOfFieldPostProcess.onApply = function (effect) {
  68765. effect.setTexture("depthSampler", _this._depthTexture);
  68766. effect.setTexture("grainSampler", _this._grainTexture);
  68767. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  68768. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  68769. effect.setFloat('grain_amount', _this._grainAmount);
  68770. effect.setBool('blur_noise', _this._blurNoise);
  68771. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68772. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68773. effect.setFloat('distortion', _this._distortion);
  68774. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  68775. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  68776. effect.setFloat('aperture', _this._dofAperture);
  68777. effect.setFloat('darken', _this._dofDarken);
  68778. effect.setFloat('edge_blur', _this._edgeBlur);
  68779. effect.setBool('highlights', (_this._highlightsGain !== -1));
  68780. if (_this._scene.activeCamera) {
  68781. effect.setFloat('near', _this._scene.activeCamera.minZ);
  68782. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  68783. }
  68784. };
  68785. };
  68786. // creates a black and white random noise texture, 512x512
  68787. LensRenderingPipeline.prototype._createGrainTexture = function () {
  68788. var size = 512;
  68789. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68790. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68791. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68792. var context = this._grainTexture.getContext();
  68793. var rand = function (min, max) {
  68794. return Math.random() * (max - min) + min;
  68795. };
  68796. var value;
  68797. for (var x = 0; x < size; x++) {
  68798. for (var y = 0; y < size; y++) {
  68799. value = Math.floor(rand(0.42, 0.58) * 255);
  68800. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  68801. context.fillRect(x, y, 1, 1);
  68802. }
  68803. }
  68804. this._grainTexture.update(false);
  68805. };
  68806. return LensRenderingPipeline;
  68807. }(BABYLON.PostProcessRenderPipeline));
  68808. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  68809. })(BABYLON || (BABYLON = {}));
  68810. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  68811. "use strict";
  68812. var BABYLON;
  68813. (function (BABYLON) {
  68814. var StandardRenderingPipeline = /** @class */ (function (_super) {
  68815. __extends(StandardRenderingPipeline, _super);
  68816. /**
  68817. * @constructor
  68818. * @param {string} name - The rendering pipeline name
  68819. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68820. * @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)
  68821. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  68822. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68823. */
  68824. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  68825. if (originalPostProcess === void 0) { originalPostProcess = null; }
  68826. var _this = _super.call(this, scene.getEngine(), name) || this;
  68827. _this.downSampleX4PostProcess = null;
  68828. _this.brightPassPostProcess = null;
  68829. _this.blurHPostProcesses = [];
  68830. _this.blurVPostProcesses = [];
  68831. _this.textureAdderPostProcess = null;
  68832. _this.volumetricLightPostProcess = null;
  68833. _this.volumetricLightSmoothXPostProcess = null;
  68834. _this.volumetricLightSmoothYPostProcess = null;
  68835. _this.volumetricLightMergePostProces = null;
  68836. _this.volumetricLightFinalPostProcess = null;
  68837. _this.luminancePostProcess = null;
  68838. _this.luminanceDownSamplePostProcesses = [];
  68839. _this.hdrPostProcess = null;
  68840. _this.textureAdderFinalPostProcess = null;
  68841. _this.lensFlareFinalPostProcess = null;
  68842. _this.hdrFinalPostProcess = null;
  68843. _this.lensFlarePostProcess = null;
  68844. _this.lensFlareComposePostProcess = null;
  68845. _this.motionBlurPostProcess = null;
  68846. _this.depthOfFieldPostProcess = null;
  68847. // Values
  68848. _this.brightThreshold = 1.0;
  68849. _this.blurWidth = 512.0;
  68850. _this.horizontalBlur = false;
  68851. _this.exposure = 1.0;
  68852. _this.lensTexture = null;
  68853. _this.volumetricLightCoefficient = 0.2;
  68854. _this.volumetricLightPower = 4.0;
  68855. _this.volumetricLightBlurScale = 64.0;
  68856. _this.sourceLight = null;
  68857. _this.hdrMinimumLuminance = 1.0;
  68858. _this.hdrDecreaseRate = 0.5;
  68859. _this.hdrIncreaseRate = 0.5;
  68860. _this.lensColorTexture = null;
  68861. _this.lensFlareStrength = 20.0;
  68862. _this.lensFlareGhostDispersal = 1.4;
  68863. _this.lensFlareHaloWidth = 0.7;
  68864. _this.lensFlareDistortionStrength = 16.0;
  68865. _this.lensStarTexture = null;
  68866. _this.lensFlareDirtTexture = null;
  68867. _this.depthOfFieldDistance = 10.0;
  68868. _this.depthOfFieldBlurWidth = 64.0;
  68869. _this.motionStrength = 1.0;
  68870. // IAnimatable
  68871. _this.animations = [];
  68872. _this._currentDepthOfFieldSource = null;
  68873. _this._hdrCurrentLuminance = 1.0;
  68874. // Getters and setters
  68875. _this._bloomEnabled = true;
  68876. _this._depthOfFieldEnabled = false;
  68877. _this._vlsEnabled = false;
  68878. _this._lensFlareEnabled = false;
  68879. _this._hdrEnabled = false;
  68880. _this._motionBlurEnabled = false;
  68881. _this._motionBlurSamples = 64.0;
  68882. _this._volumetricLightStepsCount = 50.0;
  68883. _this._cameras = cameras || [];
  68884. // Initialize
  68885. _this._scene = scene;
  68886. _this._basePostProcess = originalPostProcess;
  68887. _this._ratio = ratio;
  68888. // Misc
  68889. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68890. // Finish
  68891. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68892. _this._buildPipeline();
  68893. return _this;
  68894. }
  68895. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  68896. get: function () {
  68897. return this._bloomEnabled;
  68898. },
  68899. set: function (enabled) {
  68900. if (this._bloomEnabled === enabled) {
  68901. return;
  68902. }
  68903. this._bloomEnabled = enabled;
  68904. this._buildPipeline();
  68905. },
  68906. enumerable: true,
  68907. configurable: true
  68908. });
  68909. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  68910. get: function () {
  68911. return this._depthOfFieldEnabled;
  68912. },
  68913. set: function (enabled) {
  68914. if (this._depthOfFieldEnabled === enabled) {
  68915. return;
  68916. }
  68917. this._depthOfFieldEnabled = enabled;
  68918. this._buildPipeline();
  68919. },
  68920. enumerable: true,
  68921. configurable: true
  68922. });
  68923. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  68924. get: function () {
  68925. return this._lensFlareEnabled;
  68926. },
  68927. set: function (enabled) {
  68928. if (this._lensFlareEnabled === enabled) {
  68929. return;
  68930. }
  68931. this._lensFlareEnabled = enabled;
  68932. this._buildPipeline();
  68933. },
  68934. enumerable: true,
  68935. configurable: true
  68936. });
  68937. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  68938. get: function () {
  68939. return this._hdrEnabled;
  68940. },
  68941. set: function (enabled) {
  68942. if (this._hdrEnabled === enabled) {
  68943. return;
  68944. }
  68945. this._hdrEnabled = enabled;
  68946. this._buildPipeline();
  68947. },
  68948. enumerable: true,
  68949. configurable: true
  68950. });
  68951. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  68952. get: function () {
  68953. return this._vlsEnabled;
  68954. },
  68955. set: function (enabled) {
  68956. if (this._vlsEnabled === enabled) {
  68957. return;
  68958. }
  68959. if (enabled) {
  68960. var geometry = this._scene.enableGeometryBufferRenderer();
  68961. if (!geometry) {
  68962. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  68963. return;
  68964. }
  68965. }
  68966. this._vlsEnabled = enabled;
  68967. this._buildPipeline();
  68968. },
  68969. enumerable: true,
  68970. configurable: true
  68971. });
  68972. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  68973. get: function () {
  68974. return this._motionBlurEnabled;
  68975. },
  68976. set: function (enabled) {
  68977. if (this._motionBlurEnabled === enabled) {
  68978. return;
  68979. }
  68980. this._motionBlurEnabled = enabled;
  68981. this._buildPipeline();
  68982. },
  68983. enumerable: true,
  68984. configurable: true
  68985. });
  68986. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  68987. get: function () {
  68988. return this._volumetricLightStepsCount;
  68989. },
  68990. set: function (count) {
  68991. if (this.volumetricLightPostProcess) {
  68992. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  68993. }
  68994. this._volumetricLightStepsCount = count;
  68995. },
  68996. enumerable: true,
  68997. configurable: true
  68998. });
  68999. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  69000. get: function () {
  69001. return this._motionBlurSamples;
  69002. },
  69003. set: function (samples) {
  69004. if (this.motionBlurPostProcess) {
  69005. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  69006. }
  69007. this._motionBlurSamples = samples;
  69008. },
  69009. enumerable: true,
  69010. configurable: true
  69011. });
  69012. StandardRenderingPipeline.prototype._buildPipeline = function () {
  69013. var _this = this;
  69014. var ratio = this._ratio;
  69015. var scene = this._scene;
  69016. this._disposePostProcesses();
  69017. this._reset();
  69018. // Create pass post-process
  69019. if (!this._basePostProcess) {
  69020. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  69021. this.originalPostProcess.onApply = function (effect) {
  69022. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  69023. };
  69024. }
  69025. else {
  69026. this.originalPostProcess = this._basePostProcess;
  69027. }
  69028. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  69029. this._currentDepthOfFieldSource = this.originalPostProcess;
  69030. if (this._vlsEnabled) {
  69031. // Create volumetric light
  69032. this._createVolumetricLightPostProcess(scene, ratio);
  69033. // Create volumetric light final post-process
  69034. 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);
  69035. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  69036. }
  69037. if (this._bloomEnabled) {
  69038. // Create down sample X4 post-process
  69039. this._createDownSampleX4PostProcess(scene, ratio / 2);
  69040. // Create bright pass post-process
  69041. this._createBrightPassPostProcess(scene, ratio / 2);
  69042. // Create gaussian blur post-processes (down sampling blurs)
  69043. this._createBlurPostProcesses(scene, ratio / 4, 1);
  69044. // Create texture adder post-process
  69045. this._createTextureAdderPostProcess(scene, ratio);
  69046. // Create depth-of-field source post-process
  69047. 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);
  69048. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  69049. }
  69050. if (this._lensFlareEnabled) {
  69051. // Create lens flare post-process
  69052. this._createLensFlarePostProcess(scene, ratio);
  69053. // Create depth-of-field source post-process post lens-flare and disable it now
  69054. 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);
  69055. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  69056. }
  69057. if (this._hdrEnabled) {
  69058. // Create luminance
  69059. this._createLuminancePostProcesses(scene, this._floatTextureType);
  69060. // Create HDR
  69061. this._createHdrPostProcess(scene, ratio);
  69062. // Create depth-of-field source post-process post hdr and disable it now
  69063. 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);
  69064. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  69065. }
  69066. if (this._depthOfFieldEnabled) {
  69067. // Create gaussian blur used by depth-of-field
  69068. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  69069. // Create depth-of-field post-process
  69070. this._createDepthOfFieldPostProcess(scene, ratio);
  69071. }
  69072. if (this._motionBlurEnabled) {
  69073. // Create motion blur post-process
  69074. this._createMotionBlurPostProcess(scene, ratio);
  69075. }
  69076. if (this._cameras !== null) {
  69077. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  69078. }
  69079. };
  69080. // Down Sample X4 Post-Processs
  69081. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  69082. var _this = this;
  69083. var downSampleX4Offsets = new Array(32);
  69084. 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);
  69085. this.downSampleX4PostProcess.onApply = function (effect) {
  69086. var id = 0;
  69087. var width = _this.downSampleX4PostProcess.width;
  69088. var height = _this.downSampleX4PostProcess.height;
  69089. for (var i = -2; i < 2; i++) {
  69090. for (var j = -2; j < 2; j++) {
  69091. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  69092. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  69093. id += 2;
  69094. }
  69095. }
  69096. effect.setArray2("dsOffsets", downSampleX4Offsets);
  69097. };
  69098. // Add to pipeline
  69099. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  69100. };
  69101. // Brightpass Post-Process
  69102. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  69103. var _this = this;
  69104. var brightOffsets = new Array(8);
  69105. 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);
  69106. this.brightPassPostProcess.onApply = function (effect) {
  69107. var sU = (1.0 / _this.brightPassPostProcess.width);
  69108. var sV = (1.0 / _this.brightPassPostProcess.height);
  69109. brightOffsets[0] = -0.5 * sU;
  69110. brightOffsets[1] = 0.5 * sV;
  69111. brightOffsets[2] = 0.5 * sU;
  69112. brightOffsets[3] = 0.5 * sV;
  69113. brightOffsets[4] = -0.5 * sU;
  69114. brightOffsets[5] = -0.5 * sV;
  69115. brightOffsets[6] = 0.5 * sU;
  69116. brightOffsets[7] = -0.5 * sV;
  69117. effect.setArray2("dsOffsets", brightOffsets);
  69118. effect.setFloat("brightThreshold", _this.brightThreshold);
  69119. };
  69120. // Add to pipeline
  69121. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  69122. };
  69123. // Create blur H&V post-processes
  69124. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  69125. var _this = this;
  69126. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  69127. var engine = scene.getEngine();
  69128. 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);
  69129. 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);
  69130. blurX.onActivateObservable.add(function () {
  69131. var dw = blurX.width / engine.getRenderWidth();
  69132. blurX.kernel = _this[blurWidthKey] * dw;
  69133. });
  69134. blurY.onActivateObservable.add(function () {
  69135. var dw = blurY.height / engine.getRenderHeight();
  69136. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  69137. });
  69138. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  69139. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  69140. this.blurHPostProcesses.push(blurX);
  69141. this.blurVPostProcesses.push(blurY);
  69142. };
  69143. // Create texture adder post-process
  69144. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  69145. var _this = this;
  69146. 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);
  69147. this.textureAdderPostProcess.onApply = function (effect) {
  69148. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  69149. effect.setTexture("lensSampler", _this.lensTexture);
  69150. effect.setFloat("exposure", _this.exposure);
  69151. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  69152. };
  69153. // Add to pipeline
  69154. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  69155. };
  69156. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  69157. var _this = this;
  69158. var geometryRenderer = scene.enableGeometryBufferRenderer();
  69159. geometryRenderer.enablePosition = true;
  69160. var geometry = geometryRenderer.getGBuffer();
  69161. // Base post-process
  69162. 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));
  69163. var depthValues = BABYLON.Vector2.Zero();
  69164. this.volumetricLightPostProcess.onApply = function (effect) {
  69165. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  69166. var generator = _this.sourceLight.getShadowGenerator();
  69167. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  69168. effect.setTexture("positionSampler", geometry.textures[2]);
  69169. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  69170. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  69171. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  69172. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  69173. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  69174. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  69175. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  69176. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  69177. effect.setVector2("depthValues", depthValues);
  69178. }
  69179. };
  69180. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  69181. // Smooth
  69182. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  69183. // Merge
  69184. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  69185. this.volumetricLightMergePostProces.onApply = function (effect) {
  69186. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  69187. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  69188. };
  69189. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  69190. };
  69191. // Create luminance
  69192. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  69193. var _this = this;
  69194. // Create luminance
  69195. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  69196. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  69197. var offsets = [];
  69198. this.luminancePostProcess.onApply = function (effect) {
  69199. var sU = (1.0 / _this.luminancePostProcess.width);
  69200. var sV = (1.0 / _this.luminancePostProcess.height);
  69201. offsets[0] = -0.5 * sU;
  69202. offsets[1] = 0.5 * sV;
  69203. offsets[2] = 0.5 * sU;
  69204. offsets[3] = 0.5 * sV;
  69205. offsets[4] = -0.5 * sU;
  69206. offsets[5] = -0.5 * sV;
  69207. offsets[6] = 0.5 * sU;
  69208. offsets[7] = -0.5 * sV;
  69209. effect.setArray2("lumOffsets", offsets);
  69210. };
  69211. // Add to pipeline
  69212. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  69213. // Create down sample luminance
  69214. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  69215. var size = Math.pow(3, i);
  69216. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  69217. if (i === 0) {
  69218. defines += "#define FINAL_DOWN_SAMPLER";
  69219. }
  69220. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  69221. this.luminanceDownSamplePostProcesses.push(postProcess);
  69222. }
  69223. // Create callbacks and add effects
  69224. var lastLuminance = this.luminancePostProcess;
  69225. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  69226. var downSampleOffsets = new Array(18);
  69227. pp.onApply = function (effect) {
  69228. if (!lastLuminance) {
  69229. return;
  69230. }
  69231. var id = 0;
  69232. for (var x = -1; x < 2; x++) {
  69233. for (var y = -1; y < 2; y++) {
  69234. downSampleOffsets[id] = x / lastLuminance.width;
  69235. downSampleOffsets[id + 1] = y / lastLuminance.height;
  69236. id += 2;
  69237. }
  69238. }
  69239. effect.setArray2("dsOffsets", downSampleOffsets);
  69240. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  69241. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  69242. lastLuminance = _this.luminancePostProcess;
  69243. }
  69244. else {
  69245. lastLuminance = pp;
  69246. }
  69247. };
  69248. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  69249. pp.onAfterRender = function (effect) {
  69250. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  69251. 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);
  69252. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  69253. };
  69254. }
  69255. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  69256. });
  69257. };
  69258. // Create HDR post-process
  69259. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  69260. var _this = this;
  69261. 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);
  69262. var outputLiminance = 1;
  69263. var time = 0;
  69264. var lastTime = 0;
  69265. this.hdrPostProcess.onApply = function (effect) {
  69266. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  69267. time += scene.getEngine().getDeltaTime();
  69268. if (outputLiminance < 0) {
  69269. outputLiminance = _this._hdrCurrentLuminance;
  69270. }
  69271. else {
  69272. var dt = (lastTime - time) / 1000.0;
  69273. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  69274. outputLiminance += _this.hdrDecreaseRate * dt;
  69275. }
  69276. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  69277. outputLiminance -= _this.hdrIncreaseRate * dt;
  69278. }
  69279. else {
  69280. outputLiminance = _this._hdrCurrentLuminance;
  69281. }
  69282. }
  69283. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  69284. effect.setFloat("averageLuminance", outputLiminance);
  69285. lastTime = time;
  69286. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  69287. };
  69288. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  69289. };
  69290. // Create lens flare post-process
  69291. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  69292. var _this = this;
  69293. 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);
  69294. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  69295. this._createBlurPostProcesses(scene, ratio / 4, 2);
  69296. 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);
  69297. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  69298. var resolution = new BABYLON.Vector2(0, 0);
  69299. // Lens flare
  69300. this.lensFlarePostProcess.onApply = function (effect) {
  69301. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  69302. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  69303. effect.setFloat("strength", _this.lensFlareStrength);
  69304. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  69305. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  69306. // Shift
  69307. resolution.x = _this.lensFlarePostProcess.width;
  69308. resolution.y = _this.lensFlarePostProcess.height;
  69309. effect.setVector2("resolution", resolution);
  69310. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  69311. };
  69312. // Compose
  69313. 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);
  69314. 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);
  69315. this.lensFlareComposePostProcess.onApply = function (effect) {
  69316. if (!_this._scene.activeCamera) {
  69317. return;
  69318. }
  69319. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  69320. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  69321. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  69322. // Lens start rotation matrix
  69323. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  69324. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  69325. 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));
  69326. camRot *= 4.0;
  69327. 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);
  69328. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  69329. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  69330. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  69331. };
  69332. };
  69333. // Create depth-of-field post-process
  69334. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  69335. var _this = this;
  69336. 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);
  69337. this.depthOfFieldPostProcess.onApply = function (effect) {
  69338. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  69339. effect.setTexture("depthSampler", _this._getDepthTexture());
  69340. effect.setFloat("distance", _this.depthOfFieldDistance);
  69341. };
  69342. // Add to pipeline
  69343. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  69344. };
  69345. // Create motion blur post-process
  69346. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  69347. var _this = this;
  69348. 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);
  69349. var motionScale = 0;
  69350. var prevViewProjection = BABYLON.Matrix.Identity();
  69351. var invViewProjection = BABYLON.Matrix.Identity();
  69352. var viewProjection = BABYLON.Matrix.Identity();
  69353. var screenSize = BABYLON.Vector2.Zero();
  69354. this.motionBlurPostProcess.onApply = function (effect) {
  69355. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  69356. viewProjection.invertToRef(invViewProjection);
  69357. effect.setMatrix("inverseViewProjection", invViewProjection);
  69358. effect.setMatrix("prevViewProjection", prevViewProjection);
  69359. prevViewProjection = viewProjection;
  69360. screenSize.x = _this.motionBlurPostProcess.width;
  69361. screenSize.y = _this.motionBlurPostProcess.height;
  69362. effect.setVector2("screenSize", screenSize);
  69363. motionScale = scene.getEngine().getFps() / 60.0;
  69364. effect.setFloat("motionScale", motionScale);
  69365. effect.setFloat("motionStrength", _this.motionStrength);
  69366. effect.setTexture("depthSampler", _this._getDepthTexture());
  69367. };
  69368. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  69369. };
  69370. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  69371. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  69372. var renderer = this._scene.enableGeometryBufferRenderer();
  69373. return renderer.getGBuffer().textures[0];
  69374. }
  69375. return this._scene.enableDepthRenderer().getDepthMap();
  69376. };
  69377. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  69378. for (var i = 0; i < this._cameras.length; i++) {
  69379. var camera = this._cameras[i];
  69380. if (this.originalPostProcess) {
  69381. this.originalPostProcess.dispose(camera);
  69382. }
  69383. if (this.downSampleX4PostProcess) {
  69384. this.downSampleX4PostProcess.dispose(camera);
  69385. }
  69386. if (this.brightPassPostProcess) {
  69387. this.brightPassPostProcess.dispose(camera);
  69388. }
  69389. if (this.textureAdderPostProcess) {
  69390. this.textureAdderPostProcess.dispose(camera);
  69391. }
  69392. if (this.textureAdderFinalPostProcess) {
  69393. this.textureAdderFinalPostProcess.dispose(camera);
  69394. }
  69395. if (this.volumetricLightPostProcess) {
  69396. this.volumetricLightPostProcess.dispose(camera);
  69397. }
  69398. if (this.volumetricLightSmoothXPostProcess) {
  69399. this.volumetricLightSmoothXPostProcess.dispose(camera);
  69400. }
  69401. if (this.volumetricLightSmoothYPostProcess) {
  69402. this.volumetricLightSmoothYPostProcess.dispose(camera);
  69403. }
  69404. if (this.volumetricLightMergePostProces) {
  69405. this.volumetricLightMergePostProces.dispose(camera);
  69406. }
  69407. if (this.volumetricLightFinalPostProcess) {
  69408. this.volumetricLightFinalPostProcess.dispose(camera);
  69409. }
  69410. if (this.lensFlarePostProcess) {
  69411. this.lensFlarePostProcess.dispose(camera);
  69412. }
  69413. if (this.lensFlareComposePostProcess) {
  69414. this.lensFlareComposePostProcess.dispose(camera);
  69415. }
  69416. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  69417. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  69418. }
  69419. if (this.luminancePostProcess) {
  69420. this.luminancePostProcess.dispose(camera);
  69421. }
  69422. if (this.hdrPostProcess) {
  69423. this.hdrPostProcess.dispose(camera);
  69424. }
  69425. if (this.hdrFinalPostProcess) {
  69426. this.hdrFinalPostProcess.dispose(camera);
  69427. }
  69428. if (this.depthOfFieldPostProcess) {
  69429. this.depthOfFieldPostProcess.dispose(camera);
  69430. }
  69431. if (this.motionBlurPostProcess) {
  69432. this.motionBlurPostProcess.dispose(camera);
  69433. }
  69434. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  69435. this.blurHPostProcesses[j].dispose(camera);
  69436. }
  69437. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  69438. this.blurVPostProcesses[j].dispose(camera);
  69439. }
  69440. }
  69441. this.originalPostProcess = null;
  69442. this.downSampleX4PostProcess = null;
  69443. this.brightPassPostProcess = null;
  69444. this.textureAdderPostProcess = null;
  69445. this.textureAdderFinalPostProcess = null;
  69446. this.volumetricLightPostProcess = null;
  69447. this.volumetricLightSmoothXPostProcess = null;
  69448. this.volumetricLightSmoothYPostProcess = null;
  69449. this.volumetricLightMergePostProces = null;
  69450. this.volumetricLightFinalPostProcess = null;
  69451. this.lensFlarePostProcess = null;
  69452. this.lensFlareComposePostProcess = null;
  69453. this.luminancePostProcess = null;
  69454. this.hdrPostProcess = null;
  69455. this.hdrFinalPostProcess = null;
  69456. this.depthOfFieldPostProcess = null;
  69457. this.motionBlurPostProcess = null;
  69458. this.luminanceDownSamplePostProcesses = [];
  69459. this.blurHPostProcesses = [];
  69460. this.blurVPostProcesses = [];
  69461. };
  69462. // Dispose
  69463. StandardRenderingPipeline.prototype.dispose = function () {
  69464. this._disposePostProcesses();
  69465. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69466. _super.prototype.dispose.call(this);
  69467. };
  69468. // Serialize rendering pipeline
  69469. StandardRenderingPipeline.prototype.serialize = function () {
  69470. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  69471. serializationObject.customType = "StandardRenderingPipeline";
  69472. return serializationObject;
  69473. };
  69474. /**
  69475. * Static members
  69476. */
  69477. // Parse serialized pipeline
  69478. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  69479. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  69480. };
  69481. // Luminance steps
  69482. StandardRenderingPipeline.LuminanceSteps = 6;
  69483. __decorate([
  69484. BABYLON.serialize()
  69485. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  69486. __decorate([
  69487. BABYLON.serialize()
  69488. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  69489. __decorate([
  69490. BABYLON.serialize()
  69491. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  69492. __decorate([
  69493. BABYLON.serialize()
  69494. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  69495. __decorate([
  69496. BABYLON.serializeAsTexture("lensTexture")
  69497. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  69498. __decorate([
  69499. BABYLON.serialize()
  69500. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  69501. __decorate([
  69502. BABYLON.serialize()
  69503. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  69504. __decorate([
  69505. BABYLON.serialize()
  69506. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  69507. __decorate([
  69508. BABYLON.serialize()
  69509. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  69510. __decorate([
  69511. BABYLON.serialize()
  69512. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  69513. __decorate([
  69514. BABYLON.serialize()
  69515. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  69516. __decorate([
  69517. BABYLON.serializeAsTexture("lensColorTexture")
  69518. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  69519. __decorate([
  69520. BABYLON.serialize()
  69521. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  69522. __decorate([
  69523. BABYLON.serialize()
  69524. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  69525. __decorate([
  69526. BABYLON.serialize()
  69527. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  69528. __decorate([
  69529. BABYLON.serialize()
  69530. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  69531. __decorate([
  69532. BABYLON.serializeAsTexture("lensStarTexture")
  69533. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  69534. __decorate([
  69535. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  69536. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  69537. __decorate([
  69538. BABYLON.serialize()
  69539. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  69540. __decorate([
  69541. BABYLON.serialize()
  69542. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  69543. __decorate([
  69544. BABYLON.serialize()
  69545. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  69546. __decorate([
  69547. BABYLON.serialize()
  69548. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  69549. __decorate([
  69550. BABYLON.serialize()
  69551. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  69552. __decorate([
  69553. BABYLON.serialize()
  69554. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  69555. __decorate([
  69556. BABYLON.serialize()
  69557. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  69558. __decorate([
  69559. BABYLON.serialize()
  69560. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  69561. __decorate([
  69562. BABYLON.serialize()
  69563. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  69564. __decorate([
  69565. BABYLON.serialize()
  69566. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  69567. __decorate([
  69568. BABYLON.serialize()
  69569. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  69570. __decorate([
  69571. BABYLON.serialize()
  69572. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  69573. return StandardRenderingPipeline;
  69574. }(BABYLON.PostProcessRenderPipeline));
  69575. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  69576. })(BABYLON || (BABYLON = {}));
  69577. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  69578. "use strict";
  69579. var BABYLON;
  69580. (function (BABYLON) {
  69581. var FxaaPostProcess = /** @class */ (function (_super) {
  69582. __extends(FxaaPostProcess, _super);
  69583. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  69584. if (camera === void 0) { camera = null; }
  69585. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69586. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  69587. _this.onApplyObservable.add(function (effect) {
  69588. var texelSize = _this.texelSize;
  69589. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  69590. });
  69591. return _this;
  69592. }
  69593. return FxaaPostProcess;
  69594. }(BABYLON.PostProcess));
  69595. BABYLON.FxaaPostProcess = FxaaPostProcess;
  69596. })(BABYLON || (BABYLON = {}));
  69597. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  69598. "use strict";
  69599. var BABYLON;
  69600. (function (BABYLON) {
  69601. /**
  69602. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  69603. */
  69604. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  69605. __extends(ChromaticAberrationPostProcess, _super);
  69606. /**
  69607. * Creates a new instance of @see ChromaticAberrationPostProcess
  69608. * @param name The name of the effect.
  69609. * @param screenWidth The width of the screen to apply the effect on.
  69610. * @param screenHeight The height of the screen to apply the effect on.
  69611. * @param options The required width/height ratio to downsize to before computing the render pass.
  69612. * @param camera The camera to apply the render pass to.
  69613. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69614. * @param engine The engine which the post process will be applied. (default: current engine)
  69615. * @param reusable If the post process can be reused on the same frame. (default: false)
  69616. * @param textureType Type of textures used when performing the post process. (default: 0)
  69617. * @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)
  69618. */
  69619. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69620. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69621. if (blockCompilation === void 0) { blockCompilation = false; }
  69622. 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;
  69623. /**
  69624. * The amount of seperation of rgb channels (default: 30)
  69625. */
  69626. _this.aberrationAmount = 30;
  69627. /**
  69628. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  69629. */
  69630. _this.radialIntensity = 0;
  69631. /**
  69632. * 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))
  69633. */
  69634. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  69635. /**
  69636. * 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))
  69637. */
  69638. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  69639. _this.onApplyObservable.add(function (effect) {
  69640. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  69641. effect.setFloat('screen_width', screenWidth);
  69642. effect.setFloat('screen_height', screenHeight);
  69643. effect.setFloat('radialIntensity', _this.radialIntensity);
  69644. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  69645. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  69646. });
  69647. return _this;
  69648. }
  69649. return ChromaticAberrationPostProcess;
  69650. }(BABYLON.PostProcess));
  69651. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  69652. })(BABYLON || (BABYLON = {}));
  69653. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  69654. "use strict";
  69655. var BABYLON;
  69656. (function (BABYLON) {
  69657. /**
  69658. * The SharpenPostProcess applies a sharpen kernel to every pixel
  69659. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  69660. */
  69661. var SharpenPostProcess = /** @class */ (function (_super) {
  69662. __extends(SharpenPostProcess, _super);
  69663. /**
  69664. * Creates a new instance of @see ConvolutionPostProcess
  69665. * @param name The name of the effect.
  69666. * @param options The required width/height ratio to downsize to before computing the render pass.
  69667. * @param camera The camera to apply the render pass to.
  69668. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69669. * @param engine The engine which the post process will be applied. (default: current engine)
  69670. * @param reusable If the post process can be reused on the same frame. (default: false)
  69671. * @param textureType Type of textures used when performing the post process. (default: 0)
  69672. * @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)
  69673. */
  69674. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69675. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69676. if (blockCompilation === void 0) { blockCompilation = false; }
  69677. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69678. /**
  69679. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  69680. */
  69681. _this.colorAmount = 1.0;
  69682. /**
  69683. * How much sharpness should be applied (default: 0.3)
  69684. */
  69685. _this.edgeAmount = 0.3;
  69686. _this.onApply = function (effect) {
  69687. effect.setFloat2("screenSize", _this.width, _this.height);
  69688. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  69689. };
  69690. return _this;
  69691. }
  69692. return SharpenPostProcess;
  69693. }(BABYLON.PostProcess));
  69694. BABYLON.SharpenPostProcess = SharpenPostProcess;
  69695. })(BABYLON || (BABYLON = {}));
  69696. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  69697. "use strict";
  69698. var BABYLON;
  69699. (function (BABYLON) {
  69700. /**
  69701. * The Blur Post Process which blurs an image based on a kernel and direction.
  69702. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  69703. */
  69704. var BlurPostProcess = /** @class */ (function (_super) {
  69705. __extends(BlurPostProcess, _super);
  69706. /**
  69707. * Creates a new instance of @see BlurPostProcess
  69708. * @param name The name of the effect.
  69709. * @param direction The direction in which to blur the image.
  69710. * @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.
  69711. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  69712. * @param camera The camera to apply the render pass to.
  69713. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69714. * @param engine The engine which the post process will be applied. (default: current engine)
  69715. * @param reusable If the post process can be reused on the same frame. (default: false)
  69716. * @param textureType Type of textures used when performing the post process. (default: 0)
  69717. * @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)
  69718. */
  69719. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  69720. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69721. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69722. if (defines === void 0) { defines = ""; }
  69723. if (blockCompilation === void 0) { blockCompilation = false; }
  69724. 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;
  69725. _this.direction = direction;
  69726. _this.blockCompilation = blockCompilation;
  69727. _this._packedFloat = false;
  69728. _this._staticDefines = "";
  69729. _this._staticDefines = defines;
  69730. _this.onApplyObservable.add(function (effect) {
  69731. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  69732. });
  69733. _this.kernel = kernel;
  69734. return _this;
  69735. }
  69736. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  69737. /**
  69738. * Gets the length in pixels of the blur sample region
  69739. */
  69740. get: function () {
  69741. return this._idealKernel;
  69742. },
  69743. /**
  69744. * Sets the length in pixels of the blur sample region
  69745. */
  69746. set: function (v) {
  69747. if (this._idealKernel === v) {
  69748. return;
  69749. }
  69750. v = Math.max(v, 1);
  69751. this._idealKernel = v;
  69752. this._kernel = this._nearestBestKernel(v);
  69753. if (!this.blockCompilation) {
  69754. this._updateParameters();
  69755. }
  69756. },
  69757. enumerable: true,
  69758. configurable: true
  69759. });
  69760. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  69761. /**
  69762. * Gets wether or not the blur is unpacking/repacking floats
  69763. */
  69764. get: function () {
  69765. return this._packedFloat;
  69766. },
  69767. /**
  69768. * Sets wether or not the blur needs to unpack/repack floats
  69769. */
  69770. set: function (v) {
  69771. if (this._packedFloat === v) {
  69772. return;
  69773. }
  69774. this._packedFloat = v;
  69775. if (!this.blockCompilation) {
  69776. this._updateParameters();
  69777. }
  69778. },
  69779. enumerable: true,
  69780. configurable: true
  69781. });
  69782. /**
  69783. * Updates the effect with the current post process compile time values and recompiles the shader.
  69784. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  69785. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  69786. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  69787. * @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
  69788. * @param onCompiled Called when the shader has been compiled.
  69789. * @param onError Called if there is an error when compiling a shader.
  69790. */
  69791. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  69792. if (defines === void 0) { defines = null; }
  69793. if (uniforms === void 0) { uniforms = null; }
  69794. if (samplers === void 0) { samplers = null; }
  69795. this._updateParameters(onCompiled, onError);
  69796. };
  69797. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  69798. // Generate sampling offsets and weights
  69799. var N = this._kernel;
  69800. var centerIndex = (N - 1) / 2;
  69801. // Generate Gaussian sampling weights over kernel
  69802. var offsets = [];
  69803. var weights = [];
  69804. var totalWeight = 0;
  69805. for (var i = 0; i < N; i++) {
  69806. var u = i / (N - 1);
  69807. var w = this._gaussianWeight(u * 2.0 - 1);
  69808. offsets[i] = (i - centerIndex);
  69809. weights[i] = w;
  69810. totalWeight += w;
  69811. }
  69812. // Normalize weights
  69813. for (var i = 0; i < weights.length; i++) {
  69814. weights[i] /= totalWeight;
  69815. }
  69816. // Optimize: combine samples to take advantage of hardware linear sampling
  69817. // Walk from left to center, combining pairs (symmetrically)
  69818. var linearSamplingWeights = [];
  69819. var linearSamplingOffsets = [];
  69820. var linearSamplingMap = [];
  69821. for (var i = 0; i <= centerIndex; i += 2) {
  69822. var j = Math.min(i + 1, Math.floor(centerIndex));
  69823. var singleCenterSample = i === j;
  69824. if (singleCenterSample) {
  69825. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69826. }
  69827. else {
  69828. var sharedCell = j === centerIndex;
  69829. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  69830. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  69831. if (offsetLinear === 0) {
  69832. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69833. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  69834. }
  69835. else {
  69836. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  69837. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  69838. }
  69839. }
  69840. }
  69841. for (var i = 0; i < linearSamplingMap.length; i++) {
  69842. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  69843. linearSamplingWeights[i] = linearSamplingMap[i].w;
  69844. }
  69845. // Replace with optimized
  69846. offsets = linearSamplingOffsets;
  69847. weights = linearSamplingWeights;
  69848. // Generate shaders
  69849. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  69850. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  69851. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  69852. var defines = "";
  69853. defines += this._staticDefines;
  69854. for (var i = 0; i < varyingCount; i++) {
  69855. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  69856. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  69857. }
  69858. var depCount = 0;
  69859. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  69860. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  69861. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  69862. depCount++;
  69863. }
  69864. if (this.packedFloat) {
  69865. defines += "#define PACKEDFLOAT 1";
  69866. }
  69867. _super.prototype.updateEffect.call(this, defines, null, null, {
  69868. varyingCount: varyingCount,
  69869. depCount: depCount
  69870. }, onCompiled, onError);
  69871. };
  69872. /**
  69873. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  69874. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  69875. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  69876. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  69877. * The gaps between physical kernels are compensated for in the weighting of the samples
  69878. * @param idealKernel Ideal blur kernel.
  69879. * @return Nearest best kernel.
  69880. */
  69881. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  69882. var v = Math.round(idealKernel);
  69883. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  69884. var k = _a[_i];
  69885. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  69886. return Math.max(k, 3);
  69887. }
  69888. }
  69889. return Math.max(v, 3);
  69890. };
  69891. /**
  69892. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  69893. * @param x The point on the Gaussian distribution to sample.
  69894. * @return the value of the Gaussian function at x.
  69895. */
  69896. BlurPostProcess.prototype._gaussianWeight = function (x) {
  69897. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  69898. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  69899. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  69900. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  69901. // truncated at around 1.3% of peak strength.
  69902. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  69903. var sigma = (1 / 3);
  69904. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  69905. var exponent = -((x * x) / (2.0 * sigma * sigma));
  69906. var weight = (1.0 / denominator) * Math.exp(exponent);
  69907. return weight;
  69908. };
  69909. /**
  69910. * Generates a string that can be used as a floating point number in GLSL.
  69911. * @param x Value to print.
  69912. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  69913. * @return GLSL float string.
  69914. */
  69915. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  69916. if (decimalFigures === void 0) { decimalFigures = 8; }
  69917. return x.toFixed(decimalFigures).replace(/0+$/, '');
  69918. };
  69919. return BlurPostProcess;
  69920. }(BABYLON.PostProcess));
  69921. BABYLON.BlurPostProcess = BlurPostProcess;
  69922. })(BABYLON || (BABYLON = {}));
  69923. //# sourceMappingURL=babylon.blurPostProcess.js.map
  69924. "use strict";
  69925. var BABYLON;
  69926. (function (BABYLON) {
  69927. /**
  69928. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  69929. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  69930. * based on samples that have a large difference in distance than the center pixel.
  69931. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  69932. */
  69933. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  69934. __extends(DepthOfFieldBlurPostProcess, _super);
  69935. /**
  69936. * Creates a new instance of @see CircleOfConfusionPostProcess
  69937. * @param name The name of the effect.
  69938. * @param scene The scene the effect belongs to.
  69939. * @param direction The direction the blur should be applied.
  69940. * @param kernel The size of the kernel used to blur.
  69941. * @param options The required width/height ratio to downsize to before computing the render pass.
  69942. * @param camera The camera to apply the render pass to.
  69943. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  69944. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  69945. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69946. * @param engine The engine which the post process will be applied. (default: current engine)
  69947. * @param reusable If the post process can be reused on the same frame. (default: false)
  69948. * @param textureType Type of textures used when performing the post process. (default: 0)
  69949. * @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)
  69950. */
  69951. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  69952. if (imageToBlur === void 0) { imageToBlur = null; }
  69953. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69954. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69955. if (blockCompilation === void 0) { blockCompilation = false; }
  69956. 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;
  69957. _this.direction = direction;
  69958. _this.onApplyObservable.add(function (effect) {
  69959. if (imageToBlur != null) {
  69960. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  69961. }
  69962. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  69963. if (scene.activeCamera) {
  69964. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  69965. }
  69966. });
  69967. return _this;
  69968. }
  69969. return DepthOfFieldBlurPostProcess;
  69970. }(BABYLON.BlurPostProcess));
  69971. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  69972. })(BABYLON || (BABYLON = {}));
  69973. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  69974. "use strict";
  69975. var BABYLON;
  69976. (function (BABYLON) {
  69977. /**
  69978. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  69979. */
  69980. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  69981. __extends(DepthOfFieldMergePostProcess, _super);
  69982. /**
  69983. * Creates a new instance of @see CircleOfConfusionPostProcess
  69984. * @param name The name of the effect.
  69985. * @param original The non-blurred image to be modified
  69986. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  69987. * @param blurSteps Incrimental bluring post processes.
  69988. * @param options The required width/height ratio to downsize to before computing the render pass.
  69989. * @param camera The camera to apply the render pass to.
  69990. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69991. * @param engine The engine which the post process will be applied. (default: current engine)
  69992. * @param reusable If the post process can be reused on the same frame. (default: false)
  69993. * @param textureType Type of textures used when performing the post process. (default: 0)
  69994. * @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)
  69995. */
  69996. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69997. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69998. if (blockCompilation === void 0) { blockCompilation = false; }
  69999. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  70000. _this.blurSteps = blurSteps;
  70001. _this.onApplyObservable.add(function (effect) {
  70002. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  70003. effect.setTextureFromPostProcess("textureSampler", original);
  70004. blurSteps.forEach(function (step, index) {
  70005. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  70006. });
  70007. });
  70008. if (!blockCompilation) {
  70009. _this.updateEffect();
  70010. }
  70011. return _this;
  70012. }
  70013. /**
  70014. * Updates the effect with the current post process compile time values and recompiles the shader.
  70015. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  70016. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  70017. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  70018. * @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
  70019. * @param onCompiled Called when the shader has been compiled.
  70020. * @param onError Called if there is an error when compiling a shader.
  70021. */
  70022. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  70023. if (defines === void 0) { defines = null; }
  70024. if (uniforms === void 0) { uniforms = null; }
  70025. if (samplers === void 0) { samplers = null; }
  70026. _super.prototype.updateEffect.call(this, defines ? defines : "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n", uniforms, samplers, indexParameters, onCompiled, onError);
  70027. };
  70028. return DepthOfFieldMergePostProcess;
  70029. }(BABYLON.PostProcess));
  70030. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  70031. })(BABYLON || (BABYLON = {}));
  70032. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  70033. "use strict";
  70034. var BABYLON;
  70035. (function (BABYLON) {
  70036. /**
  70037. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  70038. */
  70039. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  70040. __extends(CircleOfConfusionPostProcess, _super);
  70041. /**
  70042. * Creates a new instance of @see CircleOfConfusionPostProcess
  70043. * @param name The name of the effect.
  70044. * @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.
  70045. * @param options The required width/height ratio to downsize to before computing the render pass.
  70046. * @param camera The camera to apply the render pass to.
  70047. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70048. * @param engine The engine which the post process will be applied. (default: current engine)
  70049. * @param reusable If the post process can be reused on the same frame. (default: false)
  70050. * @param textureType Type of textures used when performing the post process. (default: 0)
  70051. * @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)
  70052. */
  70053. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70054. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70055. if (blockCompilation === void 0) { blockCompilation = false; }
  70056. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  70057. /**
  70058. * 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.
  70059. */
  70060. _this.lensSize = 50;
  70061. /**
  70062. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  70063. */
  70064. _this.fStop = 1.4;
  70065. /**
  70066. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  70067. */
  70068. _this.focusDistance = 2000;
  70069. /**
  70070. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  70071. */
  70072. _this.focalLength = 50;
  70073. _this._depthTexture = null;
  70074. _this._depthTexture = depthTexture;
  70075. _this.onApplyObservable.add(function (effect) {
  70076. if (!_this._depthTexture) {
  70077. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  70078. return;
  70079. }
  70080. effect.setTexture("depthSampler", _this._depthTexture);
  70081. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  70082. var aperture = _this.lensSize / _this.fStop;
  70083. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  70084. effect.setFloat('focusDistance', _this.focusDistance);
  70085. effect.setFloat('cocPrecalculation', cocPrecalculation);
  70086. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  70087. });
  70088. return _this;
  70089. }
  70090. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  70091. /**
  70092. * 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.
  70093. */
  70094. set: function (value) {
  70095. this._depthTexture = value;
  70096. },
  70097. enumerable: true,
  70098. configurable: true
  70099. });
  70100. return CircleOfConfusionPostProcess;
  70101. }(BABYLON.PostProcess));
  70102. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  70103. })(BABYLON || (BABYLON = {}));
  70104. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  70105. "use strict";
  70106. var BABYLON;
  70107. (function (BABYLON) {
  70108. /**
  70109. * Specifies the level of max blur that should be applied when using the depth of field effect
  70110. */
  70111. var DepthOfFieldEffectBlurLevel;
  70112. (function (DepthOfFieldEffectBlurLevel) {
  70113. /**
  70114. * Subtle blur
  70115. */
  70116. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  70117. /**
  70118. * Medium blur
  70119. */
  70120. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  70121. /**
  70122. * Large blur
  70123. */
  70124. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  70125. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  70126. ;
  70127. /**
  70128. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  70129. */
  70130. var DepthOfFieldEffect = /** @class */ (function (_super) {
  70131. __extends(DepthOfFieldEffect, _super);
  70132. /**
  70133. * Creates a new instance of @see DepthOfFieldEffect
  70134. * @param scene The scene the effect belongs to.
  70135. * @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.
  70136. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  70137. * @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)
  70138. */
  70139. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  70140. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  70141. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  70142. if (blockCompilation === void 0) { blockCompilation = false; }
  70143. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  70144. return _this._effects;
  70145. }, true) || this;
  70146. _this._effects = [];
  70147. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  70148. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70149. // 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)
  70150. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  70151. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  70152. _this._depthOfFieldBlurY = [];
  70153. _this._depthOfFieldBlurX = [];
  70154. var blurCount = 1;
  70155. var kernelSize = 15;
  70156. switch (blurLevel) {
  70157. case DepthOfFieldEffectBlurLevel.High: {
  70158. blurCount = 3;
  70159. kernelSize = 51;
  70160. break;
  70161. }
  70162. case DepthOfFieldEffectBlurLevel.Medium: {
  70163. blurCount = 2;
  70164. kernelSize = 31;
  70165. break;
  70166. }
  70167. default: {
  70168. kernelSize = 15;
  70169. blurCount = 1;
  70170. break;
  70171. }
  70172. }
  70173. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  70174. for (var i = 0; i < blurCount; i++) {
  70175. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70176. blurY.autoClear = false;
  70177. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70178. blurX.autoClear = false;
  70179. _this._depthOfFieldBlurY.push(blurY);
  70180. _this._depthOfFieldBlurX.push(blurX);
  70181. }
  70182. // Merge blurred images with original image based on circleOfConfusion
  70183. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70184. _this._depthOfFieldMerge.autoClear = false;
  70185. // Set all post processes on the effect.
  70186. _this._effects = [_this._circleOfConfusion];
  70187. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  70188. _this._effects.push(_this._depthOfFieldBlurY[i]);
  70189. _this._effects.push(_this._depthOfFieldBlurX[i]);
  70190. }
  70191. _this._effects.push(_this._depthOfFieldMerge);
  70192. return _this;
  70193. }
  70194. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  70195. get: function () {
  70196. return this._circleOfConfusion.focalLength;
  70197. },
  70198. /**
  70199. * The focal the length of the camera used in the effect
  70200. */
  70201. set: function (value) {
  70202. this._circleOfConfusion.focalLength = value;
  70203. },
  70204. enumerable: true,
  70205. configurable: true
  70206. });
  70207. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  70208. get: function () {
  70209. return this._circleOfConfusion.fStop;
  70210. },
  70211. /**
  70212. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  70213. */
  70214. set: function (value) {
  70215. this._circleOfConfusion.fStop = value;
  70216. },
  70217. enumerable: true,
  70218. configurable: true
  70219. });
  70220. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  70221. get: function () {
  70222. return this._circleOfConfusion.focusDistance;
  70223. },
  70224. /**
  70225. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  70226. */
  70227. set: function (value) {
  70228. this._circleOfConfusion.focusDistance = value;
  70229. },
  70230. enumerable: true,
  70231. configurable: true
  70232. });
  70233. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  70234. get: function () {
  70235. return this._circleOfConfusion.lensSize;
  70236. },
  70237. /**
  70238. * 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.
  70239. */
  70240. set: function (value) {
  70241. this._circleOfConfusion.lensSize = value;
  70242. },
  70243. enumerable: true,
  70244. configurable: true
  70245. });
  70246. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  70247. /**
  70248. * 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.
  70249. */
  70250. set: function (value) {
  70251. this._circleOfConfusion.depthTexture = value;
  70252. },
  70253. enumerable: true,
  70254. configurable: true
  70255. });
  70256. /**
  70257. * Disposes each of the internal effects for a given camera.
  70258. * @param camera The camera to dispose the effect on.
  70259. */
  70260. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  70261. this._circleOfConfusion.dispose(camera);
  70262. this._depthOfFieldBlurX.forEach(function (element) {
  70263. element.dispose(camera);
  70264. });
  70265. this._depthOfFieldBlurY.forEach(function (element) {
  70266. element.dispose(camera);
  70267. });
  70268. this._depthOfFieldMerge.dispose(camera);
  70269. };
  70270. /**
  70271. * Internal
  70272. */
  70273. DepthOfFieldEffect.prototype._updateEffects = function () {
  70274. for (var effect in this._effects) {
  70275. this._effects[effect].updateEffect();
  70276. }
  70277. };
  70278. /**
  70279. * Internal
  70280. * @returns if all the contained post processes are ready.
  70281. */
  70282. DepthOfFieldEffect.prototype._isReady = function () {
  70283. for (var effect in this._effects) {
  70284. if (!this._effects[effect].isReady()) {
  70285. return false;
  70286. }
  70287. }
  70288. return true;
  70289. };
  70290. return DepthOfFieldEffect;
  70291. }(BABYLON.PostProcessRenderEffect));
  70292. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  70293. })(BABYLON || (BABYLON = {}));
  70294. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  70295. "use strict";
  70296. var BABYLON;
  70297. (function (BABYLON) {
  70298. /**
  70299. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  70300. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  70301. */
  70302. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  70303. __extends(DefaultRenderingPipeline, _super);
  70304. /**
  70305. * @constructor
  70306. * @param {string} name - The rendering pipeline name
  70307. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  70308. * @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)
  70309. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  70310. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  70311. */
  70312. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  70313. if (automaticBuild === void 0) { automaticBuild = true; }
  70314. var _this = _super.call(this, scene.getEngine(), name) || this;
  70315. _this._originalCameras = [];
  70316. /**
  70317. * ID of the sharpen post process,
  70318. */
  70319. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  70320. /**
  70321. * ID of the pass post process used for bloom,
  70322. */
  70323. _this.PassPostProcessId = "PassPostProcessEffect";
  70324. /**
  70325. * ID of the highlight post process used for bloom,
  70326. */
  70327. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  70328. /**
  70329. * ID of the blurX post process used for bloom,
  70330. */
  70331. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  70332. /**
  70333. * ID of the blurY post process used for bloom,
  70334. */
  70335. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  70336. /**
  70337. * ID of the copy back post process used for bloom,
  70338. */
  70339. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  70340. /**
  70341. * ID of the image processing post process;
  70342. */
  70343. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  70344. /**
  70345. * ID of the Fast Approximate Anti-Aliasing post process;
  70346. */
  70347. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  70348. /**
  70349. * ID of the final merge post process;
  70350. */
  70351. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  70352. /**
  70353. * ID of the chromatic aberration post process,
  70354. */
  70355. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  70356. /**
  70357. * Animations which can be used to tweak settings over a period of time
  70358. */
  70359. _this.animations = [];
  70360. // Values
  70361. _this._sharpenEnabled = false;
  70362. _this._bloomEnabled = false;
  70363. _this._depthOfFieldEnabled = false;
  70364. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  70365. _this._fxaaEnabled = false;
  70366. _this._msaaEnabled = false;
  70367. _this._imageProcessingEnabled = true;
  70368. _this._bloomScale = 0.6;
  70369. _this._chromaticAberrationEnabled = false;
  70370. _this._buildAllowed = true;
  70371. /**
  70372. * Specifies the size of the bloom blur kernel, relative to the final output size
  70373. */
  70374. _this.bloomKernel = 64;
  70375. /**
  70376. * Specifies the weight of the bloom in the final rendering
  70377. */
  70378. _this._bloomWeight = 0.15;
  70379. _this._prevPostProcess = null;
  70380. _this._prevPrevPostProcess = null;
  70381. _this._cameras = cameras || [];
  70382. _this._originalCameras = _this._cameras.slice();
  70383. _this._buildAllowed = automaticBuild;
  70384. // Initialize
  70385. _this._scene = scene;
  70386. var caps = _this._scene.getEngine().getCaps();
  70387. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  70388. // Misc
  70389. if (_this._hdr) {
  70390. if (caps.textureHalfFloatRender) {
  70391. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70392. }
  70393. else if (caps.textureFloatRender) {
  70394. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70395. }
  70396. }
  70397. else {
  70398. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70399. }
  70400. // Attach
  70401. scene.postProcessRenderPipelineManager.addPipeline(_this);
  70402. var engine = _this._scene.getEngine();
  70403. // Create post processes before hand so they can be modified before enabled.
  70404. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  70405. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70406. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  70407. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  70408. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70409. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  70410. _this._buildPipeline();
  70411. return _this;
  70412. }
  70413. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  70414. get: function () {
  70415. return this._sharpenEnabled;
  70416. },
  70417. /**
  70418. * Enable or disable the sharpen process from the pipeline
  70419. */
  70420. set: function (enabled) {
  70421. if (this._sharpenEnabled === enabled) {
  70422. return;
  70423. }
  70424. this._sharpenEnabled = enabled;
  70425. this._buildPipeline();
  70426. },
  70427. enumerable: true,
  70428. configurable: true
  70429. });
  70430. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  70431. get: function () {
  70432. return this._bloomWeight;
  70433. },
  70434. /**
  70435. * The strength of the bloom.
  70436. */
  70437. set: function (value) {
  70438. if (this._bloomWeight === value) {
  70439. return;
  70440. }
  70441. this._bloomWeight = value;
  70442. if (this._hdr && this.copyBack) {
  70443. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  70444. }
  70445. },
  70446. enumerable: true,
  70447. configurable: true
  70448. });
  70449. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  70450. get: function () {
  70451. return this._bloomScale;
  70452. },
  70453. /**
  70454. * The scale of the bloom, lower value will provide better performance.
  70455. */
  70456. set: function (value) {
  70457. if (this._bloomScale === value) {
  70458. return;
  70459. }
  70460. this._bloomScale = value;
  70461. this._buildPipeline();
  70462. },
  70463. enumerable: true,
  70464. configurable: true
  70465. });
  70466. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  70467. get: function () {
  70468. return this._bloomEnabled;
  70469. },
  70470. /**
  70471. * Enable or disable the bloom from the pipeline
  70472. */
  70473. set: function (enabled) {
  70474. if (this._bloomEnabled === enabled) {
  70475. return;
  70476. }
  70477. this._bloomEnabled = enabled;
  70478. this._buildPipeline();
  70479. },
  70480. enumerable: true,
  70481. configurable: true
  70482. });
  70483. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  70484. /**
  70485. * If the depth of field is enabled.
  70486. */
  70487. get: function () {
  70488. return this._depthOfFieldEnabled;
  70489. },
  70490. set: function (enabled) {
  70491. if (this._depthOfFieldEnabled === enabled) {
  70492. return;
  70493. }
  70494. this._depthOfFieldEnabled = enabled;
  70495. this._buildPipeline();
  70496. },
  70497. enumerable: true,
  70498. configurable: true
  70499. });
  70500. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  70501. /**
  70502. * Blur level of the depth of field effect. (Higher blur will effect performance)
  70503. */
  70504. get: function () {
  70505. return this._depthOfFieldBlurLevel;
  70506. },
  70507. set: function (value) {
  70508. if (this._depthOfFieldBlurLevel === value) {
  70509. return;
  70510. }
  70511. this._depthOfFieldBlurLevel = value;
  70512. // recreate dof and dispose old as this setting is not dynamic
  70513. var oldDof = this.depthOfField;
  70514. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  70515. this.depthOfField.focalLength = oldDof.focalLength;
  70516. this.depthOfField.focusDistance = oldDof.focusDistance;
  70517. this.depthOfField.fStop = oldDof.fStop;
  70518. this.depthOfField.lensSize = oldDof.lensSize;
  70519. for (var i = 0; i < this._cameras.length; i++) {
  70520. oldDof.disposeEffects(this._cameras[i]);
  70521. }
  70522. this._buildPipeline();
  70523. },
  70524. enumerable: true,
  70525. configurable: true
  70526. });
  70527. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  70528. get: function () {
  70529. return this._fxaaEnabled;
  70530. },
  70531. /**
  70532. * If the anti aliasing is enabled.
  70533. */
  70534. set: function (enabled) {
  70535. if (this._fxaaEnabled === enabled) {
  70536. return;
  70537. }
  70538. this._fxaaEnabled = enabled;
  70539. this._buildPipeline();
  70540. },
  70541. enumerable: true,
  70542. configurable: true
  70543. });
  70544. Object.defineProperty(DefaultRenderingPipeline.prototype, "msaaEnabled", {
  70545. get: function () {
  70546. return this._msaaEnabled;
  70547. },
  70548. /**
  70549. * If the multisample anti-aliasing is enabled.
  70550. */
  70551. set: function (enabled) {
  70552. if (this._msaaEnabled === enabled) {
  70553. return;
  70554. }
  70555. this._msaaEnabled = enabled;
  70556. this._buildPipeline();
  70557. },
  70558. enumerable: true,
  70559. configurable: true
  70560. });
  70561. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  70562. get: function () {
  70563. return this._imageProcessingEnabled;
  70564. },
  70565. /**
  70566. * If image processing is enabled.
  70567. */
  70568. set: function (enabled) {
  70569. if (this._imageProcessingEnabled === enabled) {
  70570. return;
  70571. }
  70572. this._imageProcessingEnabled = enabled;
  70573. this._buildPipeline();
  70574. },
  70575. enumerable: true,
  70576. configurable: true
  70577. });
  70578. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  70579. get: function () {
  70580. return this._chromaticAberrationEnabled;
  70581. },
  70582. /**
  70583. * Enable or disable the chromaticAberration process from the pipeline
  70584. */
  70585. set: function (enabled) {
  70586. if (this._chromaticAberrationEnabled === enabled) {
  70587. return;
  70588. }
  70589. this._chromaticAberrationEnabled = enabled;
  70590. this._buildPipeline();
  70591. },
  70592. enumerable: true,
  70593. configurable: true
  70594. });
  70595. /**
  70596. * Force the compilation of the entire pipeline.
  70597. */
  70598. DefaultRenderingPipeline.prototype.prepare = function () {
  70599. var previousState = this._buildAllowed;
  70600. this._buildAllowed = true;
  70601. this._buildPipeline();
  70602. this._buildAllowed = previousState;
  70603. };
  70604. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  70605. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  70606. if (this._prevPostProcess && this._prevPostProcess.autoClear) {
  70607. postProcess.autoClear = false;
  70608. }
  70609. else {
  70610. postProcess.autoClear = true;
  70611. }
  70612. if (!skipTextureSharing) {
  70613. if (this._prevPrevPostProcess) {
  70614. postProcess.shareOutputWith(this._prevPrevPostProcess);
  70615. }
  70616. else {
  70617. postProcess.useOwnOutput();
  70618. }
  70619. if (this._prevPostProcess) {
  70620. this._prevPrevPostProcess = this._prevPostProcess;
  70621. }
  70622. this._prevPostProcess = postProcess;
  70623. }
  70624. };
  70625. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  70626. var _this = this;
  70627. if (!this._buildAllowed) {
  70628. return;
  70629. }
  70630. var engine = this._scene.getEngine();
  70631. this._disposePostProcesses();
  70632. if (this._cameras !== null) {
  70633. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  70634. // get back cameras to be used to reattach pipeline
  70635. this._cameras = this._originalCameras.slice();
  70636. }
  70637. this._reset();
  70638. this._prevPostProcess = null;
  70639. this._prevPrevPostProcess = null;
  70640. if (this.sharpenEnabled) {
  70641. if (!this.sharpen.isReady()) {
  70642. this.sharpen.updateEffect();
  70643. }
  70644. this.addEffect(this._sharpenEffect);
  70645. this._setAutoClearAndTextureSharing(this.sharpen);
  70646. }
  70647. if (this.depthOfFieldEnabled) {
  70648. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  70649. this.depthOfField.depthTexture = depthTexture;
  70650. if (!this.depthOfField._isReady()) {
  70651. this.depthOfField._updateEffects();
  70652. }
  70653. this.addEffect(this.depthOfField);
  70654. this._setAutoClearAndTextureSharing(this.depthOfField._depthOfFieldMerge);
  70655. }
  70656. if (this.bloomEnabled) {
  70657. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70658. this._setAutoClearAndTextureSharing(this.pass, true);
  70659. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  70660. if (!this._hdr) {
  70661. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70662. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  70663. this.highlights.autoClear = false;
  70664. this.highlights.alwaysForcePOT = true;
  70665. }
  70666. 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);
  70667. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  70668. this.blurX.alwaysForcePOT = true;
  70669. this.blurX.autoClear = false;
  70670. this.blurX.onActivateObservable.add(function () {
  70671. var dw = _this.blurX.width / engine.getRenderWidth(true);
  70672. _this.blurX.kernel = _this.bloomKernel * dw;
  70673. });
  70674. 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);
  70675. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  70676. this.blurY.alwaysForcePOT = true;
  70677. this.blurY.autoClear = false;
  70678. this.blurY.onActivateObservable.add(function () {
  70679. var dh = _this.blurY.height / engine.getRenderHeight(true);
  70680. _this.blurY.kernel = _this.bloomKernel * dh;
  70681. });
  70682. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70683. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  70684. this.copyBack.alwaysForcePOT = true;
  70685. if (this._hdr) {
  70686. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  70687. var w = this.bloomWeight;
  70688. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  70689. }
  70690. else {
  70691. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  70692. }
  70693. this.copyBack.autoClear = false;
  70694. }
  70695. if (this._imageProcessingEnabled) {
  70696. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70697. if (this._hdr) {
  70698. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  70699. }
  70700. else {
  70701. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  70702. }
  70703. }
  70704. if (this._hdr && this.imageProcessing) {
  70705. this.finalMerge = this.imageProcessing;
  70706. }
  70707. else {
  70708. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70709. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  70710. this._setAutoClearAndTextureSharing(this.finalMerge, true);
  70711. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  70712. }
  70713. if (this.bloomEnabled) {
  70714. if (this._hdr) {
  70715. this.copyBack.shareOutputWith(this.blurX);
  70716. if (this.imageProcessing) {
  70717. this.imageProcessing.shareOutputWith(this.pass);
  70718. this.imageProcessing.autoClear = false;
  70719. }
  70720. else {
  70721. this.finalMerge.shareOutputWith(this.pass);
  70722. }
  70723. }
  70724. else {
  70725. this.finalMerge.shareOutputWith(this.pass);
  70726. }
  70727. }
  70728. if (this.fxaaEnabled) {
  70729. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70730. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  70731. this._setAutoClearAndTextureSharing(this.fxaa);
  70732. }
  70733. if (this.chromaticAberrationEnabled) {
  70734. if (!this.chromaticAberration.isReady()) {
  70735. this.chromaticAberration.updateEffect();
  70736. }
  70737. this.addEffect(this._chromaticAberrationEffect);
  70738. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  70739. }
  70740. if (this._cameras !== null) {
  70741. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  70742. }
  70743. if (this.msaaEnabled) {
  70744. if (!this._enableMSAAOnFirstPostProcess()) {
  70745. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  70746. }
  70747. }
  70748. };
  70749. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  70750. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  70751. for (var i = 0; i < this._cameras.length; i++) {
  70752. var camera = this._cameras[i];
  70753. if (this.pass) {
  70754. this.pass.dispose(camera);
  70755. }
  70756. if (this.highlights) {
  70757. this.highlights.dispose(camera);
  70758. }
  70759. if (this.blurX) {
  70760. this.blurX.dispose(camera);
  70761. }
  70762. if (this.blurY) {
  70763. this.blurY.dispose(camera);
  70764. }
  70765. if (this.copyBack) {
  70766. this.copyBack.dispose(camera);
  70767. }
  70768. if (this.imageProcessing) {
  70769. this.imageProcessing.dispose(camera);
  70770. }
  70771. if (this.fxaa) {
  70772. this.fxaa.dispose(camera);
  70773. }
  70774. if (this.finalMerge) {
  70775. this.finalMerge.dispose(camera);
  70776. }
  70777. // These are created in the constructor and should not be disposed on every pipeline change
  70778. if (disposeNonRecreated) {
  70779. if (this.sharpen) {
  70780. this.sharpen.dispose(camera);
  70781. }
  70782. if (this.depthOfField) {
  70783. this.depthOfField.disposeEffects(camera);
  70784. }
  70785. if (this.chromaticAberration) {
  70786. this.chromaticAberration.dispose(camera);
  70787. }
  70788. }
  70789. }
  70790. this.pass = null;
  70791. this.highlights = null;
  70792. this.blurX = null;
  70793. this.blurY = null;
  70794. this.copyBack = null;
  70795. this.imageProcessing = null;
  70796. this.fxaa = null;
  70797. this.finalMerge = null;
  70798. if (disposeNonRecreated) {
  70799. this.sharpen = null;
  70800. this.depthOfField = null;
  70801. this.chromaticAberration = null;
  70802. }
  70803. };
  70804. /**
  70805. * Dispose of the pipeline and stop all post processes
  70806. */
  70807. DefaultRenderingPipeline.prototype.dispose = function () {
  70808. this._disposePostProcesses(true);
  70809. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  70810. _super.prototype.dispose.call(this);
  70811. };
  70812. /**
  70813. * Serialize the rendering pipeline (Used when exporting)
  70814. * @returns the serialized object
  70815. */
  70816. DefaultRenderingPipeline.prototype.serialize = function () {
  70817. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  70818. serializationObject.customType = "DefaultRenderingPipeline";
  70819. return serializationObject;
  70820. };
  70821. /**
  70822. * Parse the serialized pipeline
  70823. * @param source Source pipeline.
  70824. * @param scene The scene to load the pipeline to.
  70825. * @param rootUrl The URL of the serialized pipeline.
  70826. * @returns An instantiated pipeline from the serialized object.
  70827. */
  70828. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  70829. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  70830. };
  70831. __decorate([
  70832. BABYLON.serialize()
  70833. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  70834. __decorate([
  70835. BABYLON.serialize()
  70836. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  70837. __decorate([
  70838. BABYLON.serialize()
  70839. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  70840. __decorate([
  70841. BABYLON.serialize()
  70842. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  70843. __decorate([
  70844. BABYLON.serialize()
  70845. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  70846. __decorate([
  70847. BABYLON.serialize()
  70848. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  70849. __decorate([
  70850. BABYLON.serialize()
  70851. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  70852. __decorate([
  70853. BABYLON.serialize()
  70854. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  70855. __decorate([
  70856. BABYLON.serialize()
  70857. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  70858. __decorate([
  70859. BABYLON.serialize()
  70860. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  70861. __decorate([
  70862. BABYLON.serialize()
  70863. ], DefaultRenderingPipeline.prototype, "msaaEnabled", null);
  70864. __decorate([
  70865. BABYLON.serialize()
  70866. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  70867. __decorate([
  70868. BABYLON.serialize()
  70869. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  70870. return DefaultRenderingPipeline;
  70871. }(BABYLON.PostProcessRenderPipeline));
  70872. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  70873. })(BABYLON || (BABYLON = {}));
  70874. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  70875. "use strict";
  70876. var BABYLON;
  70877. (function (BABYLON) {
  70878. /**
  70879. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  70880. */
  70881. var GeometryBufferRenderer = /** @class */ (function () {
  70882. /**
  70883. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  70884. * @param scene The scene the buffer belongs to
  70885. * @param ratio How big is the buffer related to the main canvas.
  70886. */
  70887. function GeometryBufferRenderer(scene, ratio) {
  70888. if (ratio === void 0) { ratio = 1; }
  70889. this._enablePosition = false;
  70890. this._scene = scene;
  70891. this._ratio = ratio;
  70892. // Render target
  70893. this._createRenderTargets();
  70894. }
  70895. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  70896. /**
  70897. * Set the render list (meshes to be rendered) used in the G buffer.
  70898. */
  70899. set: function (meshes) {
  70900. this._multiRenderTarget.renderList = meshes;
  70901. },
  70902. enumerable: true,
  70903. configurable: true
  70904. });
  70905. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  70906. /**
  70907. * Gets wether or not G buffer are supported by the running hardware.
  70908. * This requires draw buffer supports
  70909. */
  70910. get: function () {
  70911. return this._multiRenderTarget.isSupported;
  70912. },
  70913. enumerable: true,
  70914. configurable: true
  70915. });
  70916. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  70917. /**
  70918. * Gets wether or not position are enabled for the G buffer.
  70919. */
  70920. get: function () {
  70921. return this._enablePosition;
  70922. },
  70923. /**
  70924. * Sets wether or not position are enabled for the G buffer.
  70925. */
  70926. set: function (enable) {
  70927. this._enablePosition = enable;
  70928. this.dispose();
  70929. this._createRenderTargets();
  70930. },
  70931. enumerable: true,
  70932. configurable: true
  70933. });
  70934. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  70935. /**
  70936. * Gets the scene associated with the buffer.
  70937. */
  70938. get: function () {
  70939. return this._scene;
  70940. },
  70941. enumerable: true,
  70942. configurable: true
  70943. });
  70944. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  70945. /**
  70946. * Gets the ratio used by the buffer during its creation.
  70947. * How big is the buffer related to the main canvas.
  70948. */
  70949. get: function () {
  70950. return this._ratio;
  70951. },
  70952. enumerable: true,
  70953. configurable: true
  70954. });
  70955. /**
  70956. * Checks wether everything is ready to render a submesh to the G buffer.
  70957. * @param subMesh the submesh to check readiness for
  70958. * @param useInstances is the mesh drawn using instance or not
  70959. * @returns true if ready otherwise false
  70960. */
  70961. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  70962. var material = subMesh.getMaterial();
  70963. if (material && material.disableDepthWrite) {
  70964. return false;
  70965. }
  70966. var defines = [];
  70967. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  70968. var mesh = subMesh.getMesh();
  70969. // Alpha test
  70970. if (material && material.needAlphaTesting()) {
  70971. defines.push("#define ALPHATEST");
  70972. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70973. attribs.push(BABYLON.VertexBuffer.UVKind);
  70974. defines.push("#define UV1");
  70975. }
  70976. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70977. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70978. defines.push("#define UV2");
  70979. }
  70980. }
  70981. // Buffers
  70982. if (this._enablePosition) {
  70983. defines.push("#define POSITION");
  70984. }
  70985. // Bones
  70986. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70987. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70988. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70989. if (mesh.numBoneInfluencers > 4) {
  70990. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  70991. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  70992. }
  70993. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70994. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  70995. }
  70996. else {
  70997. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70998. }
  70999. // Instances
  71000. if (useInstances) {
  71001. defines.push("#define INSTANCES");
  71002. attribs.push("world0");
  71003. attribs.push("world1");
  71004. attribs.push("world2");
  71005. attribs.push("world3");
  71006. }
  71007. // Get correct effect
  71008. var join = defines.join("\n");
  71009. if (this._cachedDefines !== join) {
  71010. this._cachedDefines = join;
  71011. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  71012. }
  71013. return this._effect.isReady();
  71014. };
  71015. /**
  71016. * Gets the current underlying G Buffer.
  71017. * @returns the buffer
  71018. */
  71019. GeometryBufferRenderer.prototype.getGBuffer = function () {
  71020. return this._multiRenderTarget;
  71021. };
  71022. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  71023. /**
  71024. * Gets the number of samples used to render the buffer (anti aliasing).
  71025. */
  71026. get: function () {
  71027. return this._multiRenderTarget.samples;
  71028. },
  71029. /**
  71030. * Sets the number of samples used to render the buffer (anti aliasing).
  71031. */
  71032. set: function (value) {
  71033. this._multiRenderTarget.samples = value;
  71034. },
  71035. enumerable: true,
  71036. configurable: true
  71037. });
  71038. /**
  71039. * Disposes the renderer and frees up associated resources.
  71040. */
  71041. GeometryBufferRenderer.prototype.dispose = function () {
  71042. this.getGBuffer().dispose();
  71043. };
  71044. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  71045. var _this = this;
  71046. var engine = this._scene.getEngine();
  71047. var count = this._enablePosition ? 3 : 2;
  71048. 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 });
  71049. if (!this.isSupported) {
  71050. return;
  71051. }
  71052. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71053. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71054. this._multiRenderTarget.refreshRate = 1;
  71055. this._multiRenderTarget.renderParticles = false;
  71056. this._multiRenderTarget.renderList = null;
  71057. // set default depth value to 1.0 (far away)
  71058. this._multiRenderTarget.onClearObservable.add(function (engine) {
  71059. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  71060. });
  71061. // Custom render function
  71062. var renderSubMesh = function (subMesh) {
  71063. var mesh = subMesh.getRenderingMesh();
  71064. var scene = _this._scene;
  71065. var engine = scene.getEngine();
  71066. var material = subMesh.getMaterial();
  71067. if (!material) {
  71068. return;
  71069. }
  71070. // Culling
  71071. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  71072. // Managing instances
  71073. var batch = mesh._getInstancesRenderList(subMesh._id);
  71074. if (batch.mustReturn) {
  71075. return;
  71076. }
  71077. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  71078. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  71079. engine.enableEffect(_this._effect);
  71080. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  71081. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  71082. _this._effect.setMatrix("view", scene.getViewMatrix());
  71083. // Alpha test
  71084. if (material && material.needAlphaTesting()) {
  71085. var alphaTexture = material.getAlphaTestTexture();
  71086. if (alphaTexture) {
  71087. _this._effect.setTexture("diffuseSampler", alphaTexture);
  71088. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71089. }
  71090. }
  71091. // Bones
  71092. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71093. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71094. }
  71095. // Draw
  71096. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  71097. }
  71098. };
  71099. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71100. var index;
  71101. if (depthOnlySubMeshes.length) {
  71102. engine.setColorWrite(false);
  71103. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71104. renderSubMesh(depthOnlySubMeshes.data[index]);
  71105. }
  71106. engine.setColorWrite(true);
  71107. }
  71108. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71109. renderSubMesh(opaqueSubMeshes.data[index]);
  71110. }
  71111. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71112. renderSubMesh(alphaTestSubMeshes.data[index]);
  71113. }
  71114. };
  71115. };
  71116. return GeometryBufferRenderer;
  71117. }());
  71118. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  71119. })(BABYLON || (BABYLON = {}));
  71120. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  71121. "use strict";
  71122. var BABYLON;
  71123. (function (BABYLON) {
  71124. var RefractionPostProcess = /** @class */ (function (_super) {
  71125. __extends(RefractionPostProcess, _super);
  71126. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  71127. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  71128. _this.color = color;
  71129. _this.depth = depth;
  71130. _this.colorLevel = colorLevel;
  71131. _this._ownRefractionTexture = true;
  71132. _this.onActivateObservable.add(function (cam) {
  71133. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  71134. });
  71135. _this.onApplyObservable.add(function (effect) {
  71136. effect.setColor3("baseColor", _this.color);
  71137. effect.setFloat("depth", _this.depth);
  71138. effect.setFloat("colorLevel", _this.colorLevel);
  71139. effect.setTexture("refractionSampler", _this._refTexture);
  71140. });
  71141. return _this;
  71142. }
  71143. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  71144. /**
  71145. * Gets or sets the refraction texture
  71146. * Please note that you are responsible for disposing the texture if you set it manually
  71147. */
  71148. get: function () {
  71149. return this._refTexture;
  71150. },
  71151. set: function (value) {
  71152. if (this._refTexture && this._ownRefractionTexture) {
  71153. this._refTexture.dispose();
  71154. }
  71155. this._refTexture = value;
  71156. this._ownRefractionTexture = false;
  71157. },
  71158. enumerable: true,
  71159. configurable: true
  71160. });
  71161. // Methods
  71162. RefractionPostProcess.prototype.dispose = function (camera) {
  71163. if (this._refTexture && this._ownRefractionTexture) {
  71164. this._refTexture.dispose();
  71165. this._refTexture = null;
  71166. }
  71167. _super.prototype.dispose.call(this, camera);
  71168. };
  71169. return RefractionPostProcess;
  71170. }(BABYLON.PostProcess));
  71171. BABYLON.RefractionPostProcess = RefractionPostProcess;
  71172. })(BABYLON || (BABYLON = {}));
  71173. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  71174. "use strict";
  71175. var BABYLON;
  71176. (function (BABYLON) {
  71177. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  71178. __extends(BlackAndWhitePostProcess, _super);
  71179. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  71180. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  71181. _this.degree = 1;
  71182. _this.onApplyObservable.add(function (effect) {
  71183. effect.setFloat("degree", _this.degree);
  71184. });
  71185. return _this;
  71186. }
  71187. return BlackAndWhitePostProcess;
  71188. }(BABYLON.PostProcess));
  71189. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  71190. })(BABYLON || (BABYLON = {}));
  71191. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  71192. "use strict";
  71193. var BABYLON;
  71194. (function (BABYLON) {
  71195. /**
  71196. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  71197. * input texture to perform effects such as edge detection or sharpening
  71198. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  71199. */
  71200. var ConvolutionPostProcess = /** @class */ (function (_super) {
  71201. __extends(ConvolutionPostProcess, _super);
  71202. /**
  71203. * Creates a new instance of @see ConvolutionPostProcess
  71204. * @param name The name of the effect.
  71205. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  71206. * @param options The required width/height ratio to downsize to before computing the render pass.
  71207. * @param camera The camera to apply the render pass to.
  71208. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  71209. * @param engine The engine which the post process will be applied. (default: current engine)
  71210. * @param reusable If the post process can be reused on the same frame. (default: false)
  71211. * @param textureType Type of textures used when performing the post process. (default: 0)
  71212. */
  71213. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  71214. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71215. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  71216. _this.kernel = kernel;
  71217. _this.onApply = function (effect) {
  71218. effect.setFloat2("screenSize", _this.width, _this.height);
  71219. effect.setArray("kernel", _this.kernel);
  71220. };
  71221. return _this;
  71222. }
  71223. // Statics
  71224. /**
  71225. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71226. */
  71227. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  71228. /**
  71229. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71230. */
  71231. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  71232. /**
  71233. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71234. */
  71235. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  71236. /**
  71237. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71238. */
  71239. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  71240. /**
  71241. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71242. */
  71243. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  71244. /**
  71245. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71246. */
  71247. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  71248. return ConvolutionPostProcess;
  71249. }(BABYLON.PostProcess));
  71250. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  71251. })(BABYLON || (BABYLON = {}));
  71252. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  71253. "use strict";
  71254. var BABYLON;
  71255. (function (BABYLON) {
  71256. var FilterPostProcess = /** @class */ (function (_super) {
  71257. __extends(FilterPostProcess, _super);
  71258. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  71259. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  71260. _this.kernelMatrix = kernelMatrix;
  71261. _this.onApply = function (effect) {
  71262. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  71263. };
  71264. return _this;
  71265. }
  71266. return FilterPostProcess;
  71267. }(BABYLON.PostProcess));
  71268. BABYLON.FilterPostProcess = FilterPostProcess;
  71269. })(BABYLON || (BABYLON = {}));
  71270. //# sourceMappingURL=babylon.filterPostProcess.js.map
  71271. "use strict";
  71272. var BABYLON;
  71273. (function (BABYLON) {
  71274. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  71275. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  71276. __extends(VolumetricLightScatteringPostProcess, _super);
  71277. /**
  71278. * @constructor
  71279. * @param {string} name - The post-process name
  71280. * @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)
  71281. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  71282. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  71283. * @param {number} samples - The post-process quality, default 100
  71284. * @param {number} samplingMode - The post-process filtering mode
  71285. * @param {BABYLON.Engine} engine - The babylon engine
  71286. * @param {boolean} reusable - If the post-process is reusable
  71287. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  71288. */
  71289. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  71290. if (samples === void 0) { samples = 100; }
  71291. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71292. 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;
  71293. _this._screenCoordinates = BABYLON.Vector2.Zero();
  71294. /**
  71295. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  71296. * @type {Vector3}
  71297. */
  71298. _this.customMeshPosition = BABYLON.Vector3.Zero();
  71299. /**
  71300. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  71301. * @type {boolean}
  71302. */
  71303. _this.useCustomMeshPosition = false;
  71304. /**
  71305. * If the post-process should inverse the light scattering direction
  71306. * @type {boolean}
  71307. */
  71308. _this.invert = true;
  71309. /**
  71310. * Array containing the excluded meshes not rendered in the internal pass
  71311. */
  71312. _this.excludedMeshes = new Array();
  71313. /**
  71314. * Controls the overall intensity of the post-process
  71315. * @type {number}
  71316. */
  71317. _this.exposure = 0.3;
  71318. /**
  71319. * Dissipates each sample's contribution in range [0, 1]
  71320. * @type {number}
  71321. */
  71322. _this.decay = 0.96815;
  71323. /**
  71324. * Controls the overall intensity of each sample
  71325. * @type {number}
  71326. */
  71327. _this.weight = 0.58767;
  71328. /**
  71329. * Controls the density of each sample
  71330. * @type {number}
  71331. */
  71332. _this.density = 0.926;
  71333. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  71334. engine = scene.getEngine();
  71335. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  71336. // Configure mesh
  71337. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  71338. // Configure
  71339. _this._createPass(scene, ratio.passRatio || ratio);
  71340. _this.onActivate = function (camera) {
  71341. if (!_this.isSupported) {
  71342. _this.dispose(camera);
  71343. }
  71344. _this.onActivate = null;
  71345. };
  71346. _this.onApplyObservable.add(function (effect) {
  71347. _this._updateMeshScreenCoordinates(scene);
  71348. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  71349. effect.setFloat("exposure", _this.exposure);
  71350. effect.setFloat("decay", _this.decay);
  71351. effect.setFloat("weight", _this.weight);
  71352. effect.setFloat("density", _this.density);
  71353. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  71354. });
  71355. return _this;
  71356. }
  71357. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  71358. get: function () {
  71359. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  71360. return false;
  71361. },
  71362. set: function (useDiffuseColor) {
  71363. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  71364. },
  71365. enumerable: true,
  71366. configurable: true
  71367. });
  71368. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  71369. return "VolumetricLightScatteringPostProcess";
  71370. };
  71371. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  71372. var mesh = subMesh.getMesh();
  71373. // Render this.mesh as default
  71374. if (mesh === this.mesh && mesh.material) {
  71375. return mesh.material.isReady(mesh);
  71376. }
  71377. var defines = [];
  71378. var attribs = [BABYLON.VertexBuffer.PositionKind];
  71379. var material = subMesh.getMaterial();
  71380. // Alpha test
  71381. if (material) {
  71382. if (material.needAlphaTesting()) {
  71383. defines.push("#define ALPHATEST");
  71384. }
  71385. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71386. attribs.push(BABYLON.VertexBuffer.UVKind);
  71387. defines.push("#define UV1");
  71388. }
  71389. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71390. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71391. defines.push("#define UV2");
  71392. }
  71393. }
  71394. // Bones
  71395. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71396. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71397. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71398. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71399. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  71400. }
  71401. else {
  71402. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71403. }
  71404. // Instances
  71405. if (useInstances) {
  71406. defines.push("#define INSTANCES");
  71407. attribs.push("world0");
  71408. attribs.push("world1");
  71409. attribs.push("world2");
  71410. attribs.push("world3");
  71411. }
  71412. // Get correct effect
  71413. var join = defines.join("\n");
  71414. if (this._cachedDefines !== join) {
  71415. this._cachedDefines = join;
  71416. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  71417. }
  71418. return this._volumetricLightScatteringPass.isReady();
  71419. };
  71420. /**
  71421. * Sets the new light position for light scattering effect
  71422. * @param {BABYLON.Vector3} The new custom light position
  71423. */
  71424. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  71425. this.customMeshPosition = position;
  71426. };
  71427. /**
  71428. * Returns the light position for light scattering effect
  71429. * @return {BABYLON.Vector3} The custom light position
  71430. */
  71431. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  71432. return this.customMeshPosition;
  71433. };
  71434. /**
  71435. * Disposes the internal assets and detaches the post-process from the camera
  71436. */
  71437. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  71438. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  71439. if (rttIndex !== -1) {
  71440. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  71441. }
  71442. this._volumetricLightScatteringRTT.dispose();
  71443. _super.prototype.dispose.call(this, camera);
  71444. };
  71445. /**
  71446. * Returns the render target texture used by the post-process
  71447. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  71448. */
  71449. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  71450. return this._volumetricLightScatteringRTT;
  71451. };
  71452. // Private methods
  71453. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  71454. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  71455. return true;
  71456. }
  71457. return false;
  71458. };
  71459. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  71460. var _this = this;
  71461. var engine = scene.getEngine();
  71462. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71463. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71464. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71465. this._volumetricLightScatteringRTT.renderList = null;
  71466. this._volumetricLightScatteringRTT.renderParticles = false;
  71467. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  71468. var camera = this.getCamera();
  71469. if (camera) {
  71470. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  71471. }
  71472. else {
  71473. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  71474. }
  71475. // Custom render function for submeshes
  71476. var renderSubMesh = function (subMesh) {
  71477. var mesh = subMesh.getRenderingMesh();
  71478. if (_this._meshExcluded(mesh)) {
  71479. return;
  71480. }
  71481. var material = subMesh.getMaterial();
  71482. if (!material) {
  71483. return;
  71484. }
  71485. var scene = mesh.getScene();
  71486. var engine = scene.getEngine();
  71487. // Culling
  71488. engine.setState(material.backFaceCulling);
  71489. // Managing instances
  71490. var batch = mesh._getInstancesRenderList(subMesh._id);
  71491. if (batch.mustReturn) {
  71492. return;
  71493. }
  71494. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  71495. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  71496. var effect = _this._volumetricLightScatteringPass;
  71497. if (mesh === _this.mesh) {
  71498. if (subMesh.effect) {
  71499. effect = subMesh.effect;
  71500. }
  71501. else {
  71502. effect = material.getEffect();
  71503. }
  71504. }
  71505. engine.enableEffect(effect);
  71506. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  71507. if (mesh === _this.mesh) {
  71508. material.bind(mesh.getWorldMatrix(), mesh);
  71509. }
  71510. else {
  71511. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  71512. // Alpha test
  71513. if (material && material.needAlphaTesting()) {
  71514. var alphaTexture = material.getAlphaTestTexture();
  71515. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  71516. if (alphaTexture) {
  71517. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71518. }
  71519. }
  71520. // Bones
  71521. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71522. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71523. }
  71524. }
  71525. // Draw
  71526. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  71527. }
  71528. };
  71529. // Render target texture callbacks
  71530. var savedSceneClearColor;
  71531. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  71532. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  71533. savedSceneClearColor = scene.clearColor;
  71534. scene.clearColor = sceneClearColor;
  71535. });
  71536. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  71537. scene.clearColor = savedSceneClearColor;
  71538. });
  71539. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71540. var engine = scene.getEngine();
  71541. var index;
  71542. if (depthOnlySubMeshes.length) {
  71543. engine.setColorWrite(false);
  71544. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71545. renderSubMesh(depthOnlySubMeshes.data[index]);
  71546. }
  71547. engine.setColorWrite(true);
  71548. }
  71549. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71550. renderSubMesh(opaqueSubMeshes.data[index]);
  71551. }
  71552. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71553. renderSubMesh(alphaTestSubMeshes.data[index]);
  71554. }
  71555. if (transparentSubMeshes.length) {
  71556. // Sort sub meshes
  71557. for (index = 0; index < transparentSubMeshes.length; index++) {
  71558. var submesh = transparentSubMeshes.data[index];
  71559. var boundingInfo = submesh.getBoundingInfo();
  71560. if (boundingInfo && scene.activeCamera) {
  71561. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  71562. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  71563. }
  71564. }
  71565. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  71566. sortedArray.sort(function (a, b) {
  71567. // Alpha index first
  71568. if (a._alphaIndex > b._alphaIndex) {
  71569. return 1;
  71570. }
  71571. if (a._alphaIndex < b._alphaIndex) {
  71572. return -1;
  71573. }
  71574. // Then distance to camera
  71575. if (a._distanceToCamera < b._distanceToCamera) {
  71576. return 1;
  71577. }
  71578. if (a._distanceToCamera > b._distanceToCamera) {
  71579. return -1;
  71580. }
  71581. return 0;
  71582. });
  71583. // Render sub meshes
  71584. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  71585. for (index = 0; index < sortedArray.length; index++) {
  71586. renderSubMesh(sortedArray[index]);
  71587. }
  71588. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  71589. }
  71590. };
  71591. };
  71592. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  71593. var transform = scene.getTransformMatrix();
  71594. var meshPosition;
  71595. if (this.useCustomMeshPosition) {
  71596. meshPosition = this.customMeshPosition;
  71597. }
  71598. else if (this.attachedNode) {
  71599. meshPosition = this.attachedNode.position;
  71600. }
  71601. else {
  71602. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  71603. }
  71604. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  71605. this._screenCoordinates.x = pos.x / this._viewPort.width;
  71606. this._screenCoordinates.y = pos.y / this._viewPort.height;
  71607. if (this.invert)
  71608. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  71609. };
  71610. // Static methods
  71611. /**
  71612. * Creates a default mesh for the Volumeric Light Scattering post-process
  71613. * @param {string} The mesh name
  71614. * @param {BABYLON.Scene} The scene where to create the mesh
  71615. * @return {BABYLON.Mesh} the default mesh
  71616. */
  71617. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  71618. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  71619. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  71620. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  71621. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  71622. mesh.material = material;
  71623. return mesh;
  71624. };
  71625. __decorate([
  71626. BABYLON.serializeAsVector3()
  71627. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  71628. __decorate([
  71629. BABYLON.serialize()
  71630. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  71631. __decorate([
  71632. BABYLON.serialize()
  71633. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  71634. __decorate([
  71635. BABYLON.serializeAsMeshReference()
  71636. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  71637. __decorate([
  71638. BABYLON.serialize()
  71639. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  71640. __decorate([
  71641. BABYLON.serialize()
  71642. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  71643. __decorate([
  71644. BABYLON.serialize()
  71645. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  71646. __decorate([
  71647. BABYLON.serialize()
  71648. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  71649. __decorate([
  71650. BABYLON.serialize()
  71651. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  71652. return VolumetricLightScatteringPostProcess;
  71653. }(BABYLON.PostProcess));
  71654. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  71655. })(BABYLON || (BABYLON = {}));
  71656. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  71657. "use strict";
  71658. //
  71659. // This post-process allows the modification of rendered colors by using
  71660. // a 'look-up table' (LUT). This effect is also called Color Grading.
  71661. //
  71662. // The object needs to be provided an url to a texture containing the color
  71663. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  71664. // Use an image editing software to tweak the LUT to match your needs.
  71665. //
  71666. // For an example of a color LUT, see here:
  71667. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  71668. // For explanations on color grading, see here:
  71669. // http://udn.epicgames.com/Three/ColorGrading.html
  71670. //
  71671. var BABYLON;
  71672. (function (BABYLON) {
  71673. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  71674. __extends(ColorCorrectionPostProcess, _super);
  71675. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  71676. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  71677. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  71678. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  71679. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71680. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71681. _this.onApply = function (effect) {
  71682. effect.setTexture("colorTable", _this._colorTableTexture);
  71683. };
  71684. return _this;
  71685. }
  71686. return ColorCorrectionPostProcess;
  71687. }(BABYLON.PostProcess));
  71688. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  71689. })(BABYLON || (BABYLON = {}));
  71690. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  71691. "use strict";
  71692. var BABYLON;
  71693. (function (BABYLON) {
  71694. var TonemappingOperator;
  71695. (function (TonemappingOperator) {
  71696. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  71697. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  71698. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  71699. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  71700. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  71701. ;
  71702. var TonemapPostProcess = /** @class */ (function (_super) {
  71703. __extends(TonemapPostProcess, _super);
  71704. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  71705. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71706. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71707. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  71708. _this._operator = _operator;
  71709. _this.exposureAdjustment = exposureAdjustment;
  71710. var defines = "#define ";
  71711. if (_this._operator === TonemappingOperator.Hable)
  71712. defines += "HABLE_TONEMAPPING";
  71713. else if (_this._operator === TonemappingOperator.Reinhard)
  71714. defines += "REINHARD_TONEMAPPING";
  71715. else if (_this._operator === TonemappingOperator.HejiDawson)
  71716. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  71717. else if (_this._operator === TonemappingOperator.Photographic)
  71718. defines += "PHOTOGRAPHIC_TONEMAPPING";
  71719. //sadly a second call to create the effect.
  71720. _this.updateEffect(defines);
  71721. _this.onApply = function (effect) {
  71722. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  71723. };
  71724. return _this;
  71725. }
  71726. return TonemapPostProcess;
  71727. }(BABYLON.PostProcess));
  71728. BABYLON.TonemapPostProcess = TonemapPostProcess;
  71729. })(BABYLON || (BABYLON = {}));
  71730. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  71731. "use strict";
  71732. var BABYLON;
  71733. (function (BABYLON) {
  71734. var DisplayPassPostProcess = /** @class */ (function (_super) {
  71735. __extends(DisplayPassPostProcess, _super);
  71736. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  71737. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  71738. }
  71739. return DisplayPassPostProcess;
  71740. }(BABYLON.PostProcess));
  71741. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  71742. })(BABYLON || (BABYLON = {}));
  71743. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  71744. "use strict";
  71745. var BABYLON;
  71746. (function (BABYLON) {
  71747. var HighlightsPostProcess = /** @class */ (function (_super) {
  71748. __extends(HighlightsPostProcess, _super);
  71749. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  71750. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71751. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  71752. }
  71753. return HighlightsPostProcess;
  71754. }(BABYLON.PostProcess));
  71755. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  71756. })(BABYLON || (BABYLON = {}));
  71757. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  71758. "use strict";
  71759. var BABYLON;
  71760. (function (BABYLON) {
  71761. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  71762. __extends(ImageProcessingPostProcess, _super);
  71763. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  71764. if (camera === void 0) { camera = null; }
  71765. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71766. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  71767. _this._fromLinearSpace = true;
  71768. /**
  71769. * Defines cache preventing GC.
  71770. */
  71771. _this._defines = {
  71772. IMAGEPROCESSING: false,
  71773. VIGNETTE: false,
  71774. VIGNETTEBLENDMODEMULTIPLY: false,
  71775. VIGNETTEBLENDMODEOPAQUE: false,
  71776. TONEMAPPING: false,
  71777. CONTRAST: false,
  71778. COLORCURVES: false,
  71779. COLORGRADING: false,
  71780. COLORGRADING3D: false,
  71781. FROMLINEARSPACE: false,
  71782. SAMPLER3DGREENDEPTH: false,
  71783. SAMPLER3DBGRMAP: false,
  71784. IMAGEPROCESSINGPOSTPROCESS: false,
  71785. EXPOSURE: false,
  71786. GRAIN: false,
  71787. };
  71788. // Setup the configuration as forced by the constructor. This would then not force the
  71789. // scene materials output in linear space and let untouched the default forward pass.
  71790. if (imageProcessingConfiguration) {
  71791. imageProcessingConfiguration.applyByPostProcess = true;
  71792. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  71793. // This will cause the shader to be compiled
  71794. _this.fromLinearSpace = false;
  71795. }
  71796. else {
  71797. _this._attachImageProcessingConfiguration(null, true);
  71798. _this.imageProcessingConfiguration.applyByPostProcess = true;
  71799. }
  71800. _this.onApply = function (effect) {
  71801. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  71802. };
  71803. return _this;
  71804. }
  71805. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  71806. /**
  71807. * Gets the image processing configuration used either in this material.
  71808. */
  71809. get: function () {
  71810. return this._imageProcessingConfiguration;
  71811. },
  71812. /**
  71813. * Sets the Default image processing configuration used either in the this material.
  71814. *
  71815. * If sets to null, the scene one is in use.
  71816. */
  71817. set: function (value) {
  71818. this._attachImageProcessingConfiguration(value);
  71819. },
  71820. enumerable: true,
  71821. configurable: true
  71822. });
  71823. /**
  71824. * Attaches a new image processing configuration to the PBR Material.
  71825. * @param configuration
  71826. */
  71827. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  71828. var _this = this;
  71829. if (doNotBuild === void 0) { doNotBuild = false; }
  71830. if (configuration === this._imageProcessingConfiguration) {
  71831. return;
  71832. }
  71833. // Detaches observer.
  71834. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  71835. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  71836. }
  71837. // Pick the scene configuration if needed.
  71838. if (!configuration) {
  71839. var scene = null;
  71840. var engine = this.getEngine();
  71841. var camera = this.getCamera();
  71842. if (camera) {
  71843. scene = camera.getScene();
  71844. }
  71845. else if (engine && engine.scenes) {
  71846. var scenes = engine.scenes;
  71847. scene = scenes[scenes.length - 1];
  71848. }
  71849. else {
  71850. scene = BABYLON.Engine.LastCreatedScene;
  71851. }
  71852. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  71853. }
  71854. else {
  71855. this._imageProcessingConfiguration = configuration;
  71856. }
  71857. // Attaches observer.
  71858. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  71859. _this._updateParameters();
  71860. });
  71861. // Ensure the effect will be rebuilt.
  71862. if (!doNotBuild) {
  71863. this._updateParameters();
  71864. }
  71865. };
  71866. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  71867. /**
  71868. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  71869. */
  71870. get: function () {
  71871. return this.imageProcessingConfiguration.colorCurves;
  71872. },
  71873. /**
  71874. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  71875. */
  71876. set: function (value) {
  71877. this.imageProcessingConfiguration.colorCurves = value;
  71878. },
  71879. enumerable: true,
  71880. configurable: true
  71881. });
  71882. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  71883. /**
  71884. * Gets wether the color curves effect is enabled.
  71885. */
  71886. get: function () {
  71887. return this.imageProcessingConfiguration.colorCurvesEnabled;
  71888. },
  71889. /**
  71890. * Sets wether the color curves effect is enabled.
  71891. */
  71892. set: function (value) {
  71893. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  71894. },
  71895. enumerable: true,
  71896. configurable: true
  71897. });
  71898. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  71899. /**
  71900. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  71901. */
  71902. get: function () {
  71903. return this.imageProcessingConfiguration.colorGradingTexture;
  71904. },
  71905. /**
  71906. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  71907. */
  71908. set: function (value) {
  71909. this.imageProcessingConfiguration.colorGradingTexture = value;
  71910. },
  71911. enumerable: true,
  71912. configurable: true
  71913. });
  71914. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  71915. /**
  71916. * Gets wether the color grading effect is enabled.
  71917. */
  71918. get: function () {
  71919. return this.imageProcessingConfiguration.colorGradingEnabled;
  71920. },
  71921. /**
  71922. * Gets wether the color grading effect is enabled.
  71923. */
  71924. set: function (value) {
  71925. this.imageProcessingConfiguration.colorGradingEnabled = value;
  71926. },
  71927. enumerable: true,
  71928. configurable: true
  71929. });
  71930. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  71931. /**
  71932. * Gets exposure used in the effect.
  71933. */
  71934. get: function () {
  71935. return this.imageProcessingConfiguration.exposure;
  71936. },
  71937. /**
  71938. * Sets exposure used in the effect.
  71939. */
  71940. set: function (value) {
  71941. this.imageProcessingConfiguration.exposure = value;
  71942. },
  71943. enumerable: true,
  71944. configurable: true
  71945. });
  71946. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  71947. /**
  71948. * Gets wether tonemapping is enabled or not.
  71949. */
  71950. get: function () {
  71951. return this._imageProcessingConfiguration.toneMappingEnabled;
  71952. },
  71953. /**
  71954. * Sets wether tonemapping is enabled or not
  71955. */
  71956. set: function (value) {
  71957. this._imageProcessingConfiguration.toneMappingEnabled = value;
  71958. },
  71959. enumerable: true,
  71960. configurable: true
  71961. });
  71962. ;
  71963. ;
  71964. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  71965. /**
  71966. * Gets contrast used in the effect.
  71967. */
  71968. get: function () {
  71969. return this.imageProcessingConfiguration.contrast;
  71970. },
  71971. /**
  71972. * Sets contrast used in the effect.
  71973. */
  71974. set: function (value) {
  71975. this.imageProcessingConfiguration.contrast = value;
  71976. },
  71977. enumerable: true,
  71978. configurable: true
  71979. });
  71980. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  71981. /**
  71982. * Gets Vignette stretch size.
  71983. */
  71984. get: function () {
  71985. return this.imageProcessingConfiguration.vignetteStretch;
  71986. },
  71987. /**
  71988. * Sets Vignette stretch size.
  71989. */
  71990. set: function (value) {
  71991. this.imageProcessingConfiguration.vignetteStretch = value;
  71992. },
  71993. enumerable: true,
  71994. configurable: true
  71995. });
  71996. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  71997. /**
  71998. * Gets Vignette centre X Offset.
  71999. */
  72000. get: function () {
  72001. return this.imageProcessingConfiguration.vignetteCentreX;
  72002. },
  72003. /**
  72004. * Sets Vignette centre X Offset.
  72005. */
  72006. set: function (value) {
  72007. this.imageProcessingConfiguration.vignetteCentreX = value;
  72008. },
  72009. enumerable: true,
  72010. configurable: true
  72011. });
  72012. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  72013. /**
  72014. * Gets Vignette centre Y Offset.
  72015. */
  72016. get: function () {
  72017. return this.imageProcessingConfiguration.vignetteCentreY;
  72018. },
  72019. /**
  72020. * Sets Vignette centre Y Offset.
  72021. */
  72022. set: function (value) {
  72023. this.imageProcessingConfiguration.vignetteCentreY = value;
  72024. },
  72025. enumerable: true,
  72026. configurable: true
  72027. });
  72028. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  72029. /**
  72030. * Gets Vignette weight or intensity of the vignette effect.
  72031. */
  72032. get: function () {
  72033. return this.imageProcessingConfiguration.vignetteWeight;
  72034. },
  72035. /**
  72036. * Sets Vignette weight or intensity of the vignette effect.
  72037. */
  72038. set: function (value) {
  72039. this.imageProcessingConfiguration.vignetteWeight = value;
  72040. },
  72041. enumerable: true,
  72042. configurable: true
  72043. });
  72044. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  72045. /**
  72046. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  72047. * if vignetteEnabled is set to true.
  72048. */
  72049. get: function () {
  72050. return this.imageProcessingConfiguration.vignetteColor;
  72051. },
  72052. /**
  72053. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  72054. * if vignetteEnabled is set to true.
  72055. */
  72056. set: function (value) {
  72057. this.imageProcessingConfiguration.vignetteColor = value;
  72058. },
  72059. enumerable: true,
  72060. configurable: true
  72061. });
  72062. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  72063. /**
  72064. * Gets Camera field of view used by the Vignette effect.
  72065. */
  72066. get: function () {
  72067. return this.imageProcessingConfiguration.vignetteCameraFov;
  72068. },
  72069. /**
  72070. * Sets Camera field of view used by the Vignette effect.
  72071. */
  72072. set: function (value) {
  72073. this.imageProcessingConfiguration.vignetteCameraFov = value;
  72074. },
  72075. enumerable: true,
  72076. configurable: true
  72077. });
  72078. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  72079. /**
  72080. * Gets the vignette blend mode allowing different kind of effect.
  72081. */
  72082. get: function () {
  72083. return this.imageProcessingConfiguration.vignetteBlendMode;
  72084. },
  72085. /**
  72086. * Sets the vignette blend mode allowing different kind of effect.
  72087. */
  72088. set: function (value) {
  72089. this.imageProcessingConfiguration.vignetteBlendMode = value;
  72090. },
  72091. enumerable: true,
  72092. configurable: true
  72093. });
  72094. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  72095. /**
  72096. * Gets wether the vignette effect is enabled.
  72097. */
  72098. get: function () {
  72099. return this.imageProcessingConfiguration.vignetteEnabled;
  72100. },
  72101. /**
  72102. * Sets wether the vignette effect is enabled.
  72103. */
  72104. set: function (value) {
  72105. this.imageProcessingConfiguration.vignetteEnabled = value;
  72106. },
  72107. enumerable: true,
  72108. configurable: true
  72109. });
  72110. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainEnabled", {
  72111. /**
  72112. * Gets wether the grain effect is enabled.
  72113. */
  72114. get: function () {
  72115. return this.imageProcessingConfiguration.grainEnabled;
  72116. },
  72117. /**
  72118. * Sets wether the grain effect is enabled.
  72119. */
  72120. set: function (value) {
  72121. this.imageProcessingConfiguration.grainEnabled = value;
  72122. },
  72123. enumerable: true,
  72124. configurable: true
  72125. });
  72126. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainIntensity", {
  72127. /**
  72128. * Gets the grain effect's intensity.
  72129. */
  72130. get: function () {
  72131. return this.imageProcessingConfiguration.grainIntensity;
  72132. },
  72133. /**
  72134. * Sets the grain effect's intensity.
  72135. */
  72136. set: function (value) {
  72137. this.imageProcessingConfiguration.grainIntensity = value;
  72138. },
  72139. enumerable: true,
  72140. configurable: true
  72141. });
  72142. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainAnimated", {
  72143. /**
  72144. * Gets wether the grain effect is animated.
  72145. */
  72146. get: function () {
  72147. return this.imageProcessingConfiguration.grainAnimated;
  72148. },
  72149. /**
  72150. * Sets wether the grain effect is animated.
  72151. */
  72152. set: function (value) {
  72153. this.imageProcessingConfiguration.grainAnimated = value;
  72154. },
  72155. enumerable: true,
  72156. configurable: true
  72157. });
  72158. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  72159. /**
  72160. * Gets wether the input of the processing is in Gamma or Linear Space.
  72161. */
  72162. get: function () {
  72163. return this._fromLinearSpace;
  72164. },
  72165. /**
  72166. * Sets wether the input of the processing is in Gamma or Linear Space.
  72167. */
  72168. set: function (value) {
  72169. if (this._fromLinearSpace === value) {
  72170. return;
  72171. }
  72172. this._fromLinearSpace = value;
  72173. this._updateParameters();
  72174. },
  72175. enumerable: true,
  72176. configurable: true
  72177. });
  72178. ImageProcessingPostProcess.prototype.getClassName = function () {
  72179. return "ImageProcessingPostProcess";
  72180. };
  72181. ImageProcessingPostProcess.prototype._updateParameters = function () {
  72182. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  72183. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  72184. var defines = "";
  72185. for (var define in this._defines) {
  72186. if (this._defines[define]) {
  72187. defines += "#define " + define + ";\r\n";
  72188. }
  72189. }
  72190. var samplers = ["textureSampler"];
  72191. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  72192. var uniforms = ["scale"];
  72193. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  72194. this.updateEffect(defines, uniforms, samplers);
  72195. };
  72196. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  72197. _super.prototype.dispose.call(this, camera);
  72198. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  72199. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  72200. }
  72201. this.imageProcessingConfiguration.applyByPostProcess = false;
  72202. };
  72203. __decorate([
  72204. BABYLON.serialize()
  72205. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  72206. return ImageProcessingPostProcess;
  72207. }(BABYLON.PostProcess));
  72208. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  72209. })(BABYLON || (BABYLON = {}));
  72210. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  72211. "use strict";
  72212. var BABYLON;
  72213. (function (BABYLON) {
  72214. var Bone = /** @class */ (function (_super) {
  72215. __extends(Bone, _super);
  72216. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  72217. if (parentBone === void 0) { parentBone = null; }
  72218. if (localMatrix === void 0) { localMatrix = null; }
  72219. if (restPose === void 0) { restPose = null; }
  72220. if (baseMatrix === void 0) { baseMatrix = null; }
  72221. if (index === void 0) { index = null; }
  72222. var _this = _super.call(this, name, skeleton.getScene()) || this;
  72223. _this.name = name;
  72224. _this.children = new Array();
  72225. _this.animations = new Array();
  72226. // Set this value to map this bone to a different index in the transform matrices.
  72227. // Set this value to -1 to exclude the bone from the transform matrices.
  72228. _this._index = null;
  72229. _this._worldTransform = new BABYLON.Matrix();
  72230. _this._absoluteTransform = new BABYLON.Matrix();
  72231. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  72232. _this._scaleMatrix = BABYLON.Matrix.Identity();
  72233. _this._scaleVector = BABYLON.Vector3.One();
  72234. _this._negateScaleChildren = BABYLON.Vector3.One();
  72235. _this._scalingDeterminant = 1;
  72236. _this._skeleton = skeleton;
  72237. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  72238. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  72239. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  72240. _this._index = index;
  72241. skeleton.bones.push(_this);
  72242. _this.setParent(parentBone, false);
  72243. _this._updateDifferenceMatrix();
  72244. return _this;
  72245. }
  72246. Object.defineProperty(Bone.prototype, "_matrix", {
  72247. get: function () {
  72248. return this._localMatrix;
  72249. },
  72250. set: function (val) {
  72251. if (this._localMatrix) {
  72252. this._localMatrix.copyFrom(val);
  72253. }
  72254. else {
  72255. this._localMatrix = val;
  72256. }
  72257. },
  72258. enumerable: true,
  72259. configurable: true
  72260. });
  72261. // Members
  72262. Bone.prototype.getSkeleton = function () {
  72263. return this._skeleton;
  72264. };
  72265. Bone.prototype.getParent = function () {
  72266. return this._parent;
  72267. };
  72268. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  72269. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  72270. if (this._parent === parent) {
  72271. return;
  72272. }
  72273. if (this._parent) {
  72274. var index = this._parent.children.indexOf(this);
  72275. if (index !== -1) {
  72276. this._parent.children.splice(index, 1);
  72277. }
  72278. }
  72279. this._parent = parent;
  72280. if (this._parent) {
  72281. this._parent.children.push(this);
  72282. }
  72283. if (updateDifferenceMatrix) {
  72284. this._updateDifferenceMatrix();
  72285. }
  72286. };
  72287. Bone.prototype.getLocalMatrix = function () {
  72288. return this._localMatrix;
  72289. };
  72290. Bone.prototype.getBaseMatrix = function () {
  72291. return this._baseMatrix;
  72292. };
  72293. Bone.prototype.getRestPose = function () {
  72294. return this._restPose;
  72295. };
  72296. Bone.prototype.returnToRest = function () {
  72297. this.updateMatrix(this._restPose.clone());
  72298. };
  72299. Bone.prototype.getWorldMatrix = function () {
  72300. return this._worldTransform;
  72301. };
  72302. Bone.prototype.getInvertedAbsoluteTransform = function () {
  72303. return this._invertedAbsoluteTransform;
  72304. };
  72305. Bone.prototype.getAbsoluteTransform = function () {
  72306. return this._absoluteTransform;
  72307. };
  72308. Object.defineProperty(Bone.prototype, "position", {
  72309. // Properties (matches AbstractMesh properties)
  72310. get: function () {
  72311. return this.getPosition();
  72312. },
  72313. set: function (newPosition) {
  72314. this.setPosition(newPosition);
  72315. },
  72316. enumerable: true,
  72317. configurable: true
  72318. });
  72319. Object.defineProperty(Bone.prototype, "rotation", {
  72320. get: function () {
  72321. return this.getRotation();
  72322. },
  72323. set: function (newRotation) {
  72324. this.setRotation(newRotation);
  72325. },
  72326. enumerable: true,
  72327. configurable: true
  72328. });
  72329. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  72330. get: function () {
  72331. return this.getRotationQuaternion();
  72332. },
  72333. set: function (newRotation) {
  72334. this.setRotationQuaternion(newRotation);
  72335. },
  72336. enumerable: true,
  72337. configurable: true
  72338. });
  72339. Object.defineProperty(Bone.prototype, "scaling", {
  72340. get: function () {
  72341. return this.getScale();
  72342. },
  72343. set: function (newScaling) {
  72344. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  72345. },
  72346. enumerable: true,
  72347. configurable: true
  72348. });
  72349. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  72350. /**
  72351. * Gets the animation properties override
  72352. */
  72353. get: function () {
  72354. return this._skeleton.animationPropertiesOverride;
  72355. },
  72356. enumerable: true,
  72357. configurable: true
  72358. });
  72359. // Methods
  72360. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  72361. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  72362. this._baseMatrix = matrix.clone();
  72363. this._localMatrix = matrix.clone();
  72364. this._skeleton._markAsDirty();
  72365. if (updateDifferenceMatrix) {
  72366. this._updateDifferenceMatrix();
  72367. }
  72368. };
  72369. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  72370. if (!rootMatrix) {
  72371. rootMatrix = this._baseMatrix;
  72372. }
  72373. if (this._parent) {
  72374. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  72375. }
  72376. else {
  72377. this._absoluteTransform.copyFrom(rootMatrix);
  72378. }
  72379. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  72380. for (var index = 0; index < this.children.length; index++) {
  72381. this.children[index]._updateDifferenceMatrix();
  72382. }
  72383. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  72384. };
  72385. Bone.prototype.markAsDirty = function () {
  72386. this._currentRenderId++;
  72387. this._skeleton._markAsDirty();
  72388. };
  72389. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  72390. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  72391. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  72392. // all animation may be coming from a library skeleton, so may need to create animation
  72393. if (this.animations.length === 0) {
  72394. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  72395. this.animations[0].setKeys([]);
  72396. }
  72397. // get animation info / verify there is such a range from the source bone
  72398. var sourceRange = source.animations[0].getRange(rangeName);
  72399. if (!sourceRange) {
  72400. return false;
  72401. }
  72402. var from = sourceRange.from;
  72403. var to = sourceRange.to;
  72404. var sourceKeys = source.animations[0].getKeys();
  72405. // rescaling prep
  72406. var sourceBoneLength = source.length;
  72407. var sourceParent = source.getParent();
  72408. var parent = this.getParent();
  72409. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  72410. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  72411. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  72412. var destKeys = this.animations[0].getKeys();
  72413. // loop vars declaration
  72414. var orig;
  72415. var origTranslation;
  72416. var mat;
  72417. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  72418. orig = sourceKeys[key];
  72419. if (orig.frame >= from && orig.frame <= to) {
  72420. if (rescaleAsRequired) {
  72421. mat = orig.value.clone();
  72422. // scale based on parent ratio, when bone has parent
  72423. if (parentScalingReqd) {
  72424. origTranslation = mat.getTranslation();
  72425. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  72426. // scale based on skeleton dimension ratio when root bone, and value is passed
  72427. }
  72428. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  72429. origTranslation = mat.getTranslation();
  72430. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  72431. // use original when root bone, and no data for skelDimensionsRatio
  72432. }
  72433. else {
  72434. mat = orig.value;
  72435. }
  72436. }
  72437. else {
  72438. mat = orig.value;
  72439. }
  72440. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  72441. }
  72442. }
  72443. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  72444. return true;
  72445. };
  72446. /**
  72447. * Translate the bone in local or world space.
  72448. * @param vec The amount to translate the bone.
  72449. * @param space The space that the translation is in.
  72450. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72451. */
  72452. Bone.prototype.translate = function (vec, space, mesh) {
  72453. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72454. var lm = this.getLocalMatrix();
  72455. if (space == BABYLON.Space.LOCAL) {
  72456. lm.m[12] += vec.x;
  72457. lm.m[13] += vec.y;
  72458. lm.m[14] += vec.z;
  72459. }
  72460. else {
  72461. var wm = null;
  72462. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72463. if (mesh) {
  72464. wm = mesh.getWorldMatrix();
  72465. }
  72466. this._skeleton.computeAbsoluteTransforms();
  72467. var tmat = Bone._tmpMats[0];
  72468. var tvec = Bone._tmpVecs[0];
  72469. if (this._parent) {
  72470. if (mesh && wm) {
  72471. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72472. tmat.multiplyToRef(wm, tmat);
  72473. }
  72474. else {
  72475. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72476. }
  72477. }
  72478. tmat.m[12] = 0;
  72479. tmat.m[13] = 0;
  72480. tmat.m[14] = 0;
  72481. tmat.invert();
  72482. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  72483. lm.m[12] += tvec.x;
  72484. lm.m[13] += tvec.y;
  72485. lm.m[14] += tvec.z;
  72486. }
  72487. this.markAsDirty();
  72488. };
  72489. /**
  72490. * Set the postion of the bone in local or world space.
  72491. * @param position The position to set the bone.
  72492. * @param space The space that the position is in.
  72493. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72494. */
  72495. Bone.prototype.setPosition = function (position, space, mesh) {
  72496. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72497. var lm = this.getLocalMatrix();
  72498. if (space == BABYLON.Space.LOCAL) {
  72499. lm.m[12] = position.x;
  72500. lm.m[13] = position.y;
  72501. lm.m[14] = position.z;
  72502. }
  72503. else {
  72504. var wm = null;
  72505. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72506. if (mesh) {
  72507. wm = mesh.getWorldMatrix();
  72508. }
  72509. this._skeleton.computeAbsoluteTransforms();
  72510. var tmat = Bone._tmpMats[0];
  72511. var vec = Bone._tmpVecs[0];
  72512. if (this._parent) {
  72513. if (mesh && wm) {
  72514. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72515. tmat.multiplyToRef(wm, tmat);
  72516. }
  72517. else {
  72518. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72519. }
  72520. }
  72521. tmat.invert();
  72522. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  72523. lm.m[12] = vec.x;
  72524. lm.m[13] = vec.y;
  72525. lm.m[14] = vec.z;
  72526. }
  72527. this.markAsDirty();
  72528. };
  72529. /**
  72530. * Set the absolute postion of the bone (world space).
  72531. * @param position The position to set the bone.
  72532. * @param mesh The mesh that this bone is attached to.
  72533. */
  72534. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  72535. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  72536. };
  72537. /**
  72538. * Set the scale of the bone on the x, y and z axes.
  72539. * @param x The scale of the bone on the x axis.
  72540. * @param x The scale of the bone on the y axis.
  72541. * @param z The scale of the bone on the z axis.
  72542. * @param scaleChildren Set this to true if children of the bone should be scaled.
  72543. */
  72544. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  72545. if (scaleChildren === void 0) { scaleChildren = false; }
  72546. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  72547. if (!scaleChildren) {
  72548. this._negateScaleChildren.x = 1 / x;
  72549. this._negateScaleChildren.y = 1 / y;
  72550. this._negateScaleChildren.z = 1 / z;
  72551. }
  72552. this._syncScaleVector();
  72553. }
  72554. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  72555. };
  72556. /**
  72557. * Scale the bone on the x, y and z axes.
  72558. * @param x The amount to scale the bone on the x axis.
  72559. * @param x The amount to scale the bone on the y axis.
  72560. * @param z The amount to scale the bone on the z axis.
  72561. * @param scaleChildren Set this to true if children of the bone should be scaled.
  72562. */
  72563. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  72564. if (scaleChildren === void 0) { scaleChildren = false; }
  72565. var locMat = this.getLocalMatrix();
  72566. var origLocMat = Bone._tmpMats[0];
  72567. origLocMat.copyFrom(locMat);
  72568. var origLocMatInv = Bone._tmpMats[1];
  72569. origLocMatInv.copyFrom(origLocMat);
  72570. origLocMatInv.invert();
  72571. var scaleMat = Bone._tmpMats[2];
  72572. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  72573. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  72574. this._scaleVector.x *= x;
  72575. this._scaleVector.y *= y;
  72576. this._scaleVector.z *= z;
  72577. locMat.multiplyToRef(origLocMatInv, locMat);
  72578. locMat.multiplyToRef(scaleMat, locMat);
  72579. locMat.multiplyToRef(origLocMat, locMat);
  72580. var parent = this.getParent();
  72581. if (parent) {
  72582. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  72583. }
  72584. else {
  72585. this.getAbsoluteTransform().copyFrom(locMat);
  72586. }
  72587. var len = this.children.length;
  72588. scaleMat.invert();
  72589. for (var i = 0; i < len; i++) {
  72590. var child = this.children[i];
  72591. var cm = child.getLocalMatrix();
  72592. cm.multiplyToRef(scaleMat, cm);
  72593. var lm = child.getLocalMatrix();
  72594. lm.m[12] *= x;
  72595. lm.m[13] *= y;
  72596. lm.m[14] *= z;
  72597. }
  72598. this.computeAbsoluteTransforms();
  72599. if (scaleChildren) {
  72600. for (var i = 0; i < len; i++) {
  72601. this.children[i].scale(x, y, z, scaleChildren);
  72602. }
  72603. }
  72604. this.markAsDirty();
  72605. };
  72606. /**
  72607. * Set the yaw, pitch, and roll of the bone in local or world space.
  72608. * @param yaw The rotation of the bone on the y axis.
  72609. * @param pitch The rotation of the bone on the x axis.
  72610. * @param roll The rotation of the bone on the z axis.
  72611. * @param space The space that the axes of rotation are in.
  72612. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72613. */
  72614. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  72615. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72616. var rotMat = Bone._tmpMats[0];
  72617. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  72618. var rotMatInv = Bone._tmpMats[1];
  72619. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72620. rotMatInv.multiplyToRef(rotMat, rotMat);
  72621. this._rotateWithMatrix(rotMat, space, mesh);
  72622. };
  72623. /**
  72624. * Rotate the bone on an axis in local or world space.
  72625. * @param axis The axis to rotate the bone on.
  72626. * @param amount The amount to rotate the bone.
  72627. * @param space The space that the axis is in.
  72628. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72629. */
  72630. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  72631. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72632. var rmat = Bone._tmpMats[0];
  72633. rmat.m[12] = 0;
  72634. rmat.m[13] = 0;
  72635. rmat.m[14] = 0;
  72636. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  72637. this._rotateWithMatrix(rmat, space, mesh);
  72638. };
  72639. /**
  72640. * Set the rotation of the bone to a particular axis angle in local or world space.
  72641. * @param axis The axis to rotate the bone on.
  72642. * @param angle The angle that the bone should be rotated to.
  72643. * @param space The space that the axis is in.
  72644. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72645. */
  72646. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  72647. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72648. var rotMat = Bone._tmpMats[0];
  72649. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  72650. var rotMatInv = Bone._tmpMats[1];
  72651. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72652. rotMatInv.multiplyToRef(rotMat, rotMat);
  72653. this._rotateWithMatrix(rotMat, space, mesh);
  72654. };
  72655. /**
  72656. * Set the euler rotation of the bone in local of world space.
  72657. * @param rotation The euler rotation that the bone should be set to.
  72658. * @param space The space that the rotation is in.
  72659. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72660. */
  72661. Bone.prototype.setRotation = function (rotation, space, mesh) {
  72662. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72663. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  72664. };
  72665. /**
  72666. * Set the quaternion rotation of the bone in local of world space.
  72667. * @param quat The quaternion rotation that the bone should be set to.
  72668. * @param space The space that the rotation is in.
  72669. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72670. */
  72671. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  72672. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72673. var rotMatInv = Bone._tmpMats[0];
  72674. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72675. var rotMat = Bone._tmpMats[1];
  72676. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  72677. rotMatInv.multiplyToRef(rotMat, rotMat);
  72678. this._rotateWithMatrix(rotMat, space, mesh);
  72679. };
  72680. /**
  72681. * Set the rotation matrix of the bone in local of world space.
  72682. * @param rotMat The rotation matrix that the bone should be set to.
  72683. * @param space The space that the rotation is in.
  72684. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72685. */
  72686. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  72687. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72688. var rotMatInv = Bone._tmpMats[0];
  72689. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72690. var rotMat2 = Bone._tmpMats[1];
  72691. rotMat2.copyFrom(rotMat);
  72692. rotMatInv.multiplyToRef(rotMat, rotMat2);
  72693. this._rotateWithMatrix(rotMat2, space, mesh);
  72694. };
  72695. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  72696. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72697. var lmat = this.getLocalMatrix();
  72698. var lx = lmat.m[12];
  72699. var ly = lmat.m[13];
  72700. var lz = lmat.m[14];
  72701. var parent = this.getParent();
  72702. var parentScale = Bone._tmpMats[3];
  72703. var parentScaleInv = Bone._tmpMats[4];
  72704. if (parent) {
  72705. if (space == BABYLON.Space.WORLD) {
  72706. if (mesh) {
  72707. parentScale.copyFrom(mesh.getWorldMatrix());
  72708. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  72709. }
  72710. else {
  72711. parentScale.copyFrom(parent.getAbsoluteTransform());
  72712. }
  72713. }
  72714. else {
  72715. parentScale = parent._scaleMatrix;
  72716. }
  72717. parentScaleInv.copyFrom(parentScale);
  72718. parentScaleInv.invert();
  72719. lmat.multiplyToRef(parentScale, lmat);
  72720. lmat.multiplyToRef(rmat, lmat);
  72721. lmat.multiplyToRef(parentScaleInv, lmat);
  72722. }
  72723. else {
  72724. if (space == BABYLON.Space.WORLD && mesh) {
  72725. parentScale.copyFrom(mesh.getWorldMatrix());
  72726. parentScaleInv.copyFrom(parentScale);
  72727. parentScaleInv.invert();
  72728. lmat.multiplyToRef(parentScale, lmat);
  72729. lmat.multiplyToRef(rmat, lmat);
  72730. lmat.multiplyToRef(parentScaleInv, lmat);
  72731. }
  72732. else {
  72733. lmat.multiplyToRef(rmat, lmat);
  72734. }
  72735. }
  72736. lmat.m[12] = lx;
  72737. lmat.m[13] = ly;
  72738. lmat.m[14] = lz;
  72739. this.computeAbsoluteTransforms();
  72740. this.markAsDirty();
  72741. };
  72742. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  72743. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72744. if (space == BABYLON.Space.WORLD) {
  72745. var scaleMatrix = Bone._tmpMats[2];
  72746. scaleMatrix.copyFrom(this._scaleMatrix);
  72747. rotMatInv.copyFrom(this.getAbsoluteTransform());
  72748. if (mesh) {
  72749. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  72750. var meshScale = Bone._tmpMats[3];
  72751. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  72752. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  72753. }
  72754. rotMatInv.invert();
  72755. scaleMatrix.m[0] *= this._scalingDeterminant;
  72756. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  72757. }
  72758. else {
  72759. rotMatInv.copyFrom(this.getLocalMatrix());
  72760. rotMatInv.invert();
  72761. var scaleMatrix = Bone._tmpMats[2];
  72762. scaleMatrix.copyFrom(this._scaleMatrix);
  72763. if (this._parent) {
  72764. var pscaleMatrix = Bone._tmpMats[3];
  72765. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  72766. pscaleMatrix.invert();
  72767. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  72768. }
  72769. else {
  72770. scaleMatrix.m[0] *= this._scalingDeterminant;
  72771. }
  72772. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  72773. }
  72774. };
  72775. /**
  72776. * Get the scale of the bone
  72777. * @returns the scale of the bone
  72778. */
  72779. Bone.prototype.getScale = function () {
  72780. return this._scaleVector.clone();
  72781. };
  72782. /**
  72783. * Copy the scale of the bone to a vector3.
  72784. * @param result The vector3 to copy the scale to
  72785. */
  72786. Bone.prototype.getScaleToRef = function (result) {
  72787. result.copyFrom(this._scaleVector);
  72788. };
  72789. /**
  72790. * Get the position of the bone in local or world space.
  72791. * @param space The space that the returned position is in.
  72792. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72793. * @returns The position of the bone
  72794. */
  72795. Bone.prototype.getPosition = function (space, mesh) {
  72796. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72797. if (mesh === void 0) { mesh = null; }
  72798. var pos = BABYLON.Vector3.Zero();
  72799. this.getPositionToRef(space, mesh, pos);
  72800. return pos;
  72801. };
  72802. /**
  72803. * Copy the position of the bone to a vector3 in local or world space.
  72804. * @param space The space that the returned position is in.
  72805. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72806. * @param result The vector3 to copy the position to.
  72807. */
  72808. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  72809. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72810. if (space == BABYLON.Space.LOCAL) {
  72811. var lm = this.getLocalMatrix();
  72812. result.x = lm.m[12];
  72813. result.y = lm.m[13];
  72814. result.z = lm.m[14];
  72815. }
  72816. else {
  72817. var wm = null;
  72818. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72819. if (mesh) {
  72820. wm = mesh.getWorldMatrix();
  72821. }
  72822. this._skeleton.computeAbsoluteTransforms();
  72823. var tmat = Bone._tmpMats[0];
  72824. if (mesh && wm) {
  72825. tmat.copyFrom(this.getAbsoluteTransform());
  72826. tmat.multiplyToRef(wm, tmat);
  72827. }
  72828. else {
  72829. tmat = this.getAbsoluteTransform();
  72830. }
  72831. result.x = tmat.m[12];
  72832. result.y = tmat.m[13];
  72833. result.z = tmat.m[14];
  72834. }
  72835. };
  72836. /**
  72837. * Get the absolute position of the bone (world space).
  72838. * @param mesh The mesh that this bone is attached to.
  72839. * @returns The absolute position of the bone
  72840. */
  72841. Bone.prototype.getAbsolutePosition = function (mesh) {
  72842. if (mesh === void 0) { mesh = null; }
  72843. var pos = BABYLON.Vector3.Zero();
  72844. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  72845. return pos;
  72846. };
  72847. /**
  72848. * Copy the absolute position of the bone (world space) to the result param.
  72849. * @param mesh The mesh that this bone is attached to.
  72850. * @param result The vector3 to copy the absolute position to.
  72851. */
  72852. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  72853. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  72854. };
  72855. /**
  72856. * Compute the absolute transforms of this bone and its children.
  72857. */
  72858. Bone.prototype.computeAbsoluteTransforms = function () {
  72859. if (this._parent) {
  72860. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  72861. }
  72862. else {
  72863. this._absoluteTransform.copyFrom(this._localMatrix);
  72864. var poseMatrix = this._skeleton.getPoseMatrix();
  72865. if (poseMatrix) {
  72866. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  72867. }
  72868. }
  72869. var children = this.children;
  72870. var len = children.length;
  72871. for (var i = 0; i < len; i++) {
  72872. children[i].computeAbsoluteTransforms();
  72873. }
  72874. };
  72875. Bone.prototype._syncScaleVector = function () {
  72876. var lm = this.getLocalMatrix();
  72877. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  72878. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  72879. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  72880. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  72881. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  72882. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  72883. this._scaleVector.x = xs * Math.sqrt(xsq);
  72884. this._scaleVector.y = ys * Math.sqrt(ysq);
  72885. this._scaleVector.z = zs * Math.sqrt(zsq);
  72886. if (this._parent) {
  72887. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  72888. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  72889. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  72890. }
  72891. 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);
  72892. };
  72893. /**
  72894. * Get the world direction from an axis that is in the local space of the bone.
  72895. * @param localAxis The local direction that is used to compute the world direction.
  72896. * @param mesh The mesh that this bone is attached to.
  72897. * @returns The world direction
  72898. */
  72899. Bone.prototype.getDirection = function (localAxis, mesh) {
  72900. if (mesh === void 0) { mesh = null; }
  72901. var result = BABYLON.Vector3.Zero();
  72902. this.getDirectionToRef(localAxis, mesh, result);
  72903. return result;
  72904. };
  72905. /**
  72906. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  72907. * @param localAxis The local direction that is used to compute the world direction.
  72908. * @param mesh The mesh that this bone is attached to.
  72909. * @param result The vector3 that the world direction will be copied to.
  72910. */
  72911. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  72912. if (mesh === void 0) { mesh = null; }
  72913. var wm = null;
  72914. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72915. if (mesh) {
  72916. wm = mesh.getWorldMatrix();
  72917. }
  72918. this._skeleton.computeAbsoluteTransforms();
  72919. var mat = Bone._tmpMats[0];
  72920. mat.copyFrom(this.getAbsoluteTransform());
  72921. if (mesh && wm) {
  72922. mat.multiplyToRef(wm, mat);
  72923. }
  72924. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  72925. result.normalize();
  72926. };
  72927. /**
  72928. * Get the euler rotation of the bone in local or world space.
  72929. * @param space The space that the rotation should be in.
  72930. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72931. * @returns The euler rotation
  72932. */
  72933. Bone.prototype.getRotation = function (space, mesh) {
  72934. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72935. if (mesh === void 0) { mesh = null; }
  72936. var result = BABYLON.Vector3.Zero();
  72937. this.getRotationToRef(space, mesh, result);
  72938. return result;
  72939. };
  72940. /**
  72941. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  72942. * @param space The space that the rotation should be in.
  72943. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72944. * @param result The vector3 that the rotation should be copied to.
  72945. */
  72946. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  72947. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72948. if (mesh === void 0) { mesh = null; }
  72949. var quat = Bone._tmpQuat;
  72950. this.getRotationQuaternionToRef(space, mesh, quat);
  72951. quat.toEulerAnglesToRef(result);
  72952. };
  72953. /**
  72954. * Get the quaternion rotation of the bone in either local or world space.
  72955. * @param space The space that the rotation should be in.
  72956. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72957. * @returns The quaternion rotation
  72958. */
  72959. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  72960. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72961. if (mesh === void 0) { mesh = null; }
  72962. var result = BABYLON.Quaternion.Identity();
  72963. this.getRotationQuaternionToRef(space, mesh, result);
  72964. return result;
  72965. };
  72966. /**
  72967. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  72968. * @param space The space that the rotation should be in.
  72969. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72970. * @param result The quaternion that the rotation should be copied to.
  72971. */
  72972. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  72973. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72974. if (mesh === void 0) { mesh = null; }
  72975. if (space == BABYLON.Space.LOCAL) {
  72976. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  72977. }
  72978. else {
  72979. var mat = Bone._tmpMats[0];
  72980. var amat = this.getAbsoluteTransform();
  72981. if (mesh) {
  72982. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  72983. }
  72984. else {
  72985. mat.copyFrom(amat);
  72986. }
  72987. mat.m[0] *= this._scalingDeterminant;
  72988. mat.m[1] *= this._scalingDeterminant;
  72989. mat.m[2] *= this._scalingDeterminant;
  72990. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  72991. }
  72992. };
  72993. /**
  72994. * Get the rotation matrix of the bone in local or world space.
  72995. * @param space The space that the rotation should be in.
  72996. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72997. * @returns The rotation matrix
  72998. */
  72999. Bone.prototype.getRotationMatrix = function (space, mesh) {
  73000. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73001. var result = BABYLON.Matrix.Identity();
  73002. this.getRotationMatrixToRef(space, mesh, result);
  73003. return result;
  73004. };
  73005. /**
  73006. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  73007. * @param space The space that the rotation should be in.
  73008. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73009. * @param result The quaternion that the rotation should be copied to.
  73010. */
  73011. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  73012. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73013. if (space == BABYLON.Space.LOCAL) {
  73014. this.getLocalMatrix().getRotationMatrixToRef(result);
  73015. }
  73016. else {
  73017. var mat = Bone._tmpMats[0];
  73018. var amat = this.getAbsoluteTransform();
  73019. if (mesh) {
  73020. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  73021. }
  73022. else {
  73023. mat.copyFrom(amat);
  73024. }
  73025. mat.m[0] *= this._scalingDeterminant;
  73026. mat.m[1] *= this._scalingDeterminant;
  73027. mat.m[2] *= this._scalingDeterminant;
  73028. mat.getRotationMatrixToRef(result);
  73029. }
  73030. };
  73031. /**
  73032. * Get the world position of a point that is in the local space of the bone.
  73033. * @param position The local position
  73034. * @param mesh The mesh that this bone is attached to.
  73035. * @returns The world position
  73036. */
  73037. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  73038. if (mesh === void 0) { mesh = null; }
  73039. var result = BABYLON.Vector3.Zero();
  73040. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  73041. return result;
  73042. };
  73043. /**
  73044. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  73045. * @param position The local position
  73046. * @param mesh The mesh that this bone is attached to.
  73047. * @param result The vector3 that the world position should be copied to.
  73048. */
  73049. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  73050. if (mesh === void 0) { mesh = null; }
  73051. var wm = null;
  73052. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73053. if (mesh) {
  73054. wm = mesh.getWorldMatrix();
  73055. }
  73056. this._skeleton.computeAbsoluteTransforms();
  73057. var tmat = Bone._tmpMats[0];
  73058. if (mesh && wm) {
  73059. tmat.copyFrom(this.getAbsoluteTransform());
  73060. tmat.multiplyToRef(wm, tmat);
  73061. }
  73062. else {
  73063. tmat = this.getAbsoluteTransform();
  73064. }
  73065. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  73066. };
  73067. /**
  73068. * Get the local position of a point that is in world space.
  73069. * @param position The world position
  73070. * @param mesh The mesh that this bone is attached to.
  73071. * @returns The local position
  73072. */
  73073. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  73074. if (mesh === void 0) { mesh = null; }
  73075. var result = BABYLON.Vector3.Zero();
  73076. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  73077. return result;
  73078. };
  73079. /**
  73080. * Get the local position of a point that is in world space and copy it to the result param.
  73081. * @param position The world position
  73082. * @param mesh The mesh that this bone is attached to.
  73083. * @param result The vector3 that the local position should be copied to.
  73084. */
  73085. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  73086. if (mesh === void 0) { mesh = null; }
  73087. var wm = null;
  73088. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73089. if (mesh) {
  73090. wm = mesh.getWorldMatrix();
  73091. }
  73092. this._skeleton.computeAbsoluteTransforms();
  73093. var tmat = Bone._tmpMats[0];
  73094. tmat.copyFrom(this.getAbsoluteTransform());
  73095. if (mesh && wm) {
  73096. tmat.multiplyToRef(wm, tmat);
  73097. }
  73098. tmat.invert();
  73099. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  73100. };
  73101. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73102. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  73103. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73104. return Bone;
  73105. }(BABYLON.Node));
  73106. BABYLON.Bone = Bone;
  73107. })(BABYLON || (BABYLON = {}));
  73108. //# sourceMappingURL=babylon.bone.js.map
  73109. "use strict";
  73110. var BABYLON;
  73111. (function (BABYLON) {
  73112. var BoneIKController = /** @class */ (function () {
  73113. function BoneIKController(mesh, bone, options) {
  73114. this.targetPosition = BABYLON.Vector3.Zero();
  73115. this.poleTargetPosition = BABYLON.Vector3.Zero();
  73116. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  73117. this.poleAngle = 0;
  73118. this.slerpAmount = 1;
  73119. this._bone1Quat = BABYLON.Quaternion.Identity();
  73120. this._bone1Mat = BABYLON.Matrix.Identity();
  73121. this._bone2Ang = Math.PI;
  73122. this._maxAngle = Math.PI;
  73123. this._rightHandedSystem = false;
  73124. this._bendAxis = BABYLON.Vector3.Right();
  73125. this._slerping = false;
  73126. this._adjustRoll = 0;
  73127. this._bone2 = bone;
  73128. this._bone1 = bone.getParent();
  73129. if (!this._bone1) {
  73130. return;
  73131. }
  73132. this.mesh = mesh;
  73133. var bonePos = bone.getPosition();
  73134. if (bone.getAbsoluteTransform().determinant() > 0) {
  73135. this._rightHandedSystem = true;
  73136. this._bendAxis.x = 0;
  73137. this._bendAxis.y = 0;
  73138. this._bendAxis.z = -1;
  73139. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  73140. this._adjustRoll = Math.PI * .5;
  73141. this._bendAxis.z = 1;
  73142. }
  73143. }
  73144. if (this._bone1.length) {
  73145. var boneScale1 = this._bone1.getScale();
  73146. var boneScale2 = this._bone2.getScale();
  73147. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  73148. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  73149. }
  73150. else if (this._bone1.children[0]) {
  73151. mesh.computeWorldMatrix(true);
  73152. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  73153. var pos2 = this._bone2.getAbsolutePosition(mesh);
  73154. var pos3 = this._bone1.getAbsolutePosition(mesh);
  73155. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  73156. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  73157. }
  73158. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  73159. this.maxAngle = Math.PI;
  73160. if (options) {
  73161. if (options.targetMesh) {
  73162. this.targetMesh = options.targetMesh;
  73163. this.targetMesh.computeWorldMatrix(true);
  73164. }
  73165. if (options.poleTargetMesh) {
  73166. this.poleTargetMesh = options.poleTargetMesh;
  73167. this.poleTargetMesh.computeWorldMatrix(true);
  73168. }
  73169. else if (options.poleTargetBone) {
  73170. this.poleTargetBone = options.poleTargetBone;
  73171. }
  73172. else if (this._bone1.getParent()) {
  73173. this.poleTargetBone = this._bone1.getParent();
  73174. }
  73175. if (options.poleTargetLocalOffset) {
  73176. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  73177. }
  73178. if (options.poleAngle) {
  73179. this.poleAngle = options.poleAngle;
  73180. }
  73181. if (options.bendAxis) {
  73182. this._bendAxis.copyFrom(options.bendAxis);
  73183. }
  73184. if (options.maxAngle) {
  73185. this.maxAngle = options.maxAngle;
  73186. }
  73187. if (options.slerpAmount) {
  73188. this.slerpAmount = options.slerpAmount;
  73189. }
  73190. }
  73191. }
  73192. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  73193. get: function () {
  73194. return this._maxAngle;
  73195. },
  73196. set: function (value) {
  73197. this._setMaxAngle(value);
  73198. },
  73199. enumerable: true,
  73200. configurable: true
  73201. });
  73202. BoneIKController.prototype._setMaxAngle = function (ang) {
  73203. if (ang < 0) {
  73204. ang = 0;
  73205. }
  73206. if (ang > Math.PI || ang == undefined) {
  73207. ang = Math.PI;
  73208. }
  73209. this._maxAngle = ang;
  73210. var a = this._bone1Length;
  73211. var b = this._bone2Length;
  73212. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  73213. };
  73214. BoneIKController.prototype.update = function () {
  73215. var bone1 = this._bone1;
  73216. if (!bone1) {
  73217. return;
  73218. }
  73219. var target = this.targetPosition;
  73220. var poleTarget = this.poleTargetPosition;
  73221. var mat1 = BoneIKController._tmpMats[0];
  73222. var mat2 = BoneIKController._tmpMats[1];
  73223. if (this.targetMesh) {
  73224. target.copyFrom(this.targetMesh.getAbsolutePosition());
  73225. }
  73226. if (this.poleTargetBone) {
  73227. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  73228. }
  73229. else if (this.poleTargetMesh) {
  73230. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  73231. }
  73232. var bonePos = BoneIKController._tmpVecs[0];
  73233. var zaxis = BoneIKController._tmpVecs[1];
  73234. var xaxis = BoneIKController._tmpVecs[2];
  73235. var yaxis = BoneIKController._tmpVecs[3];
  73236. var upAxis = BoneIKController._tmpVecs[4];
  73237. var _tmpQuat = BoneIKController._tmpQuat;
  73238. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  73239. poleTarget.subtractToRef(bonePos, upAxis);
  73240. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  73241. upAxis.y = 1;
  73242. }
  73243. else {
  73244. upAxis.normalize();
  73245. }
  73246. target.subtractToRef(bonePos, yaxis);
  73247. yaxis.normalize();
  73248. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  73249. zaxis.normalize();
  73250. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  73251. xaxis.normalize();
  73252. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  73253. var a = this._bone1Length;
  73254. var b = this._bone2Length;
  73255. var c = BABYLON.Vector3.Distance(bonePos, target);
  73256. if (this._maxReach > 0) {
  73257. c = Math.min(this._maxReach, c);
  73258. }
  73259. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  73260. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  73261. if (acosa > 1) {
  73262. acosa = 1;
  73263. }
  73264. if (acosb > 1) {
  73265. acosb = 1;
  73266. }
  73267. if (acosa < -1) {
  73268. acosa = -1;
  73269. }
  73270. if (acosb < -1) {
  73271. acosb = -1;
  73272. }
  73273. var angA = Math.acos(acosa);
  73274. var angB = Math.acos(acosb);
  73275. var angC = -angA - angB;
  73276. if (this._rightHandedSystem) {
  73277. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  73278. mat2.multiplyToRef(mat1, mat1);
  73279. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  73280. mat2.multiplyToRef(mat1, mat1);
  73281. }
  73282. else {
  73283. var _tmpVec = BoneIKController._tmpVecs[5];
  73284. _tmpVec.copyFrom(this._bendAxis);
  73285. _tmpVec.x *= -1;
  73286. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  73287. mat2.multiplyToRef(mat1, mat1);
  73288. }
  73289. if (this.poleAngle) {
  73290. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  73291. mat1.multiplyToRef(mat2, mat1);
  73292. }
  73293. if (this._bone1) {
  73294. if (this.slerpAmount < 1) {
  73295. if (!this._slerping) {
  73296. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  73297. }
  73298. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  73299. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  73300. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  73301. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  73302. this._slerping = true;
  73303. }
  73304. else {
  73305. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  73306. this._bone1Mat.copyFrom(mat1);
  73307. this._slerping = false;
  73308. }
  73309. }
  73310. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  73311. this._bone2Ang = angC;
  73312. };
  73313. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73314. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  73315. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73316. return BoneIKController;
  73317. }());
  73318. BABYLON.BoneIKController = BoneIKController;
  73319. })(BABYLON || (BABYLON = {}));
  73320. //# sourceMappingURL=babylon.boneIKController.js.map
  73321. "use strict";
  73322. var BABYLON;
  73323. (function (BABYLON) {
  73324. var BoneLookController = /** @class */ (function () {
  73325. /**
  73326. * Create a BoneLookController
  73327. * @param mesh the mesh that the bone belongs to
  73328. * @param bone the bone that will be looking to the target
  73329. * @param target the target Vector3 to look at
  73330. * @param settings optional settings:
  73331. * - maxYaw: the maximum angle the bone will yaw to
  73332. * - minYaw: the minimum angle the bone will yaw to
  73333. * - maxPitch: the maximum angle the bone will pitch to
  73334. * - minPitch: the minimum angle the bone will yaw to
  73335. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  73336. * - upAxis: the up axis of the coordinate system
  73337. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  73338. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  73339. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  73340. * - adjustYaw: used to make an adjustment to the yaw of the bone
  73341. * - adjustPitch: used to make an adjustment to the pitch of the bone
  73342. * - adjustRoll: used to make an adjustment to the roll of the bone
  73343. **/
  73344. function BoneLookController(mesh, bone, target, options) {
  73345. /**
  73346. * The up axis of the coordinate system that is used when the bone is rotated.
  73347. */
  73348. this.upAxis = BABYLON.Vector3.Up();
  73349. /**
  73350. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  73351. */
  73352. this.upAxisSpace = BABYLON.Space.LOCAL;
  73353. /**
  73354. * Used to make an adjustment to the yaw of the bone.
  73355. */
  73356. this.adjustYaw = 0;
  73357. /**
  73358. * Used to make an adjustment to the pitch of the bone.
  73359. */
  73360. this.adjustPitch = 0;
  73361. /**
  73362. * Used to make an adjustment to the roll of the bone.
  73363. */
  73364. this.adjustRoll = 0;
  73365. /**
  73366. * 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).
  73367. */
  73368. this.slerpAmount = 1;
  73369. this._boneQuat = BABYLON.Quaternion.Identity();
  73370. this._slerping = false;
  73371. this._firstFrameSkipped = false;
  73372. this._fowardAxis = BABYLON.Vector3.Forward();
  73373. this.mesh = mesh;
  73374. this.bone = bone;
  73375. this.target = target;
  73376. if (options) {
  73377. if (options.adjustYaw) {
  73378. this.adjustYaw = options.adjustYaw;
  73379. }
  73380. if (options.adjustPitch) {
  73381. this.adjustPitch = options.adjustPitch;
  73382. }
  73383. if (options.adjustRoll) {
  73384. this.adjustRoll = options.adjustRoll;
  73385. }
  73386. if (options.maxYaw != null) {
  73387. this.maxYaw = options.maxYaw;
  73388. }
  73389. else {
  73390. this.maxYaw = Math.PI;
  73391. }
  73392. if (options.minYaw != null) {
  73393. this.minYaw = options.minYaw;
  73394. }
  73395. else {
  73396. this.minYaw = -Math.PI;
  73397. }
  73398. if (options.maxPitch != null) {
  73399. this.maxPitch = options.maxPitch;
  73400. }
  73401. else {
  73402. this.maxPitch = Math.PI;
  73403. }
  73404. if (options.minPitch != null) {
  73405. this.minPitch = options.minPitch;
  73406. }
  73407. else {
  73408. this.minPitch = -Math.PI;
  73409. }
  73410. if (options.slerpAmount != null) {
  73411. this.slerpAmount = options.slerpAmount;
  73412. }
  73413. if (options.upAxis != null) {
  73414. this.upAxis = options.upAxis;
  73415. }
  73416. if (options.upAxisSpace != null) {
  73417. this.upAxisSpace = options.upAxisSpace;
  73418. }
  73419. if (options.yawAxis != null || options.pitchAxis != null) {
  73420. var newYawAxis = BABYLON.Axis.Y;
  73421. var newPitchAxis = BABYLON.Axis.X;
  73422. if (options.yawAxis != null) {
  73423. newYawAxis = options.yawAxis.clone();
  73424. newYawAxis.normalize();
  73425. }
  73426. if (options.pitchAxis != null) {
  73427. newPitchAxis = options.pitchAxis.clone();
  73428. newPitchAxis.normalize();
  73429. }
  73430. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  73431. this._transformYawPitch = BABYLON.Matrix.Identity();
  73432. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  73433. this._transformYawPitchInv = this._transformYawPitch.clone();
  73434. this._transformYawPitch.invert();
  73435. }
  73436. }
  73437. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  73438. this.upAxisSpace = BABYLON.Space.LOCAL;
  73439. }
  73440. }
  73441. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  73442. /**
  73443. * Get/set the minimum yaw angle that the bone can look to.
  73444. */
  73445. get: function () {
  73446. return this._minYaw;
  73447. },
  73448. set: function (value) {
  73449. this._minYaw = value;
  73450. this._minYawSin = Math.sin(value);
  73451. this._minYawCos = Math.cos(value);
  73452. if (this._maxYaw != null) {
  73453. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  73454. this._yawRange = this._maxYaw - this._minYaw;
  73455. }
  73456. },
  73457. enumerable: true,
  73458. configurable: true
  73459. });
  73460. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  73461. /**
  73462. * Get/set the maximum yaw angle that the bone can look to.
  73463. */
  73464. get: function () {
  73465. return this._maxYaw;
  73466. },
  73467. set: function (value) {
  73468. this._maxYaw = value;
  73469. this._maxYawSin = Math.sin(value);
  73470. this._maxYawCos = Math.cos(value);
  73471. if (this._minYaw != null) {
  73472. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  73473. this._yawRange = this._maxYaw - this._minYaw;
  73474. }
  73475. },
  73476. enumerable: true,
  73477. configurable: true
  73478. });
  73479. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  73480. /**
  73481. * Get/set the minimum pitch angle that the bone can look to.
  73482. */
  73483. get: function () {
  73484. return this._minPitch;
  73485. },
  73486. set: function (value) {
  73487. this._minPitch = value;
  73488. this._minPitchTan = Math.tan(value);
  73489. },
  73490. enumerable: true,
  73491. configurable: true
  73492. });
  73493. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  73494. /**
  73495. * Get/set the maximum pitch angle that the bone can look to.
  73496. */
  73497. get: function () {
  73498. return this._maxPitch;
  73499. },
  73500. set: function (value) {
  73501. this._maxPitch = value;
  73502. this._maxPitchTan = Math.tan(value);
  73503. },
  73504. enumerable: true,
  73505. configurable: true
  73506. });
  73507. /**
  73508. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  73509. */
  73510. BoneLookController.prototype.update = function () {
  73511. //skip the first frame when slerping so that the mesh rotation is correct
  73512. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  73513. this._firstFrameSkipped = true;
  73514. return;
  73515. }
  73516. var bone = this.bone;
  73517. var bonePos = BoneLookController._tmpVecs[0];
  73518. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  73519. var target = this.target;
  73520. var _tmpMat1 = BoneLookController._tmpMats[0];
  73521. var _tmpMat2 = BoneLookController._tmpMats[1];
  73522. var mesh = this.mesh;
  73523. var parentBone = bone.getParent();
  73524. var upAxis = BoneLookController._tmpVecs[1];
  73525. upAxis.copyFrom(this.upAxis);
  73526. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  73527. if (this._transformYawPitch) {
  73528. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  73529. }
  73530. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  73531. }
  73532. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  73533. mesh.getDirectionToRef(upAxis, upAxis);
  73534. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  73535. upAxis.normalize();
  73536. }
  73537. }
  73538. var checkYaw = false;
  73539. var checkPitch = false;
  73540. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  73541. checkYaw = true;
  73542. }
  73543. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  73544. checkPitch = true;
  73545. }
  73546. if (checkYaw || checkPitch) {
  73547. var spaceMat = BoneLookController._tmpMats[2];
  73548. var spaceMatInv = BoneLookController._tmpMats[3];
  73549. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  73550. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  73551. }
  73552. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  73553. spaceMat.copyFrom(mesh.getWorldMatrix());
  73554. }
  73555. else {
  73556. var forwardAxis = BoneLookController._tmpVecs[2];
  73557. forwardAxis.copyFrom(this._fowardAxis);
  73558. if (this._transformYawPitch) {
  73559. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  73560. }
  73561. if (parentBone) {
  73562. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  73563. }
  73564. else {
  73565. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  73566. }
  73567. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  73568. rightAxis.normalize();
  73569. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  73570. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  73571. }
  73572. spaceMat.invertToRef(spaceMatInv);
  73573. var xzlen = null;
  73574. if (checkPitch) {
  73575. var localTarget = BoneLookController._tmpVecs[3];
  73576. target.subtractToRef(bonePos, localTarget);
  73577. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  73578. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73579. var pitch = Math.atan2(localTarget.y, xzlen);
  73580. var newPitch = pitch;
  73581. if (pitch > this._maxPitch) {
  73582. localTarget.y = this._maxPitchTan * xzlen;
  73583. newPitch = this._maxPitch;
  73584. }
  73585. else if (pitch < this._minPitch) {
  73586. localTarget.y = this._minPitchTan * xzlen;
  73587. newPitch = this._minPitch;
  73588. }
  73589. if (pitch != newPitch) {
  73590. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  73591. localTarget.addInPlace(bonePos);
  73592. target = localTarget;
  73593. }
  73594. }
  73595. if (checkYaw) {
  73596. var localTarget = BoneLookController._tmpVecs[4];
  73597. target.subtractToRef(bonePos, localTarget);
  73598. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  73599. var yaw = Math.atan2(localTarget.x, localTarget.z);
  73600. var newYaw = yaw;
  73601. if (yaw > this._maxYaw || yaw < this._minYaw) {
  73602. if (xzlen == null) {
  73603. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73604. }
  73605. if (this._yawRange > Math.PI) {
  73606. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  73607. localTarget.z = this._maxYawCos * xzlen;
  73608. localTarget.x = this._maxYawSin * xzlen;
  73609. newYaw = this._maxYaw;
  73610. }
  73611. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  73612. localTarget.z = this._minYawCos * xzlen;
  73613. localTarget.x = this._minYawSin * xzlen;
  73614. newYaw = this._minYaw;
  73615. }
  73616. }
  73617. else {
  73618. if (yaw > this._maxYaw) {
  73619. localTarget.z = this._maxYawCos * xzlen;
  73620. localTarget.x = this._maxYawSin * xzlen;
  73621. newYaw = this._maxYaw;
  73622. }
  73623. else if (yaw < this._minYaw) {
  73624. localTarget.z = this._minYawCos * xzlen;
  73625. localTarget.x = this._minYawSin * xzlen;
  73626. newYaw = this._minYaw;
  73627. }
  73628. }
  73629. }
  73630. if (this._slerping && this._yawRange > Math.PI) {
  73631. //are we going to be crossing into the min/max region?
  73632. var boneFwd = BoneLookController._tmpVecs[8];
  73633. boneFwd.copyFrom(BABYLON.Axis.Z);
  73634. if (this._transformYawPitch) {
  73635. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  73636. }
  73637. var boneRotMat = BoneLookController._tmpMats[4];
  73638. this._boneQuat.toRotationMatrix(boneRotMat);
  73639. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  73640. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  73641. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  73642. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  73643. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  73644. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  73645. if (angBtwTar > angBtwMidYaw) {
  73646. if (xzlen == null) {
  73647. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73648. }
  73649. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  73650. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  73651. if (angBtwMin < angBtwMax) {
  73652. newYaw = boneYaw + Math.PI * .75;
  73653. localTarget.z = Math.cos(newYaw) * xzlen;
  73654. localTarget.x = Math.sin(newYaw) * xzlen;
  73655. }
  73656. else {
  73657. newYaw = boneYaw - Math.PI * .75;
  73658. localTarget.z = Math.cos(newYaw) * xzlen;
  73659. localTarget.x = Math.sin(newYaw) * xzlen;
  73660. }
  73661. }
  73662. }
  73663. if (yaw != newYaw) {
  73664. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  73665. localTarget.addInPlace(bonePos);
  73666. target = localTarget;
  73667. }
  73668. }
  73669. }
  73670. var zaxis = BoneLookController._tmpVecs[5];
  73671. var xaxis = BoneLookController._tmpVecs[6];
  73672. var yaxis = BoneLookController._tmpVecs[7];
  73673. var _tmpQuat = BoneLookController._tmpQuat;
  73674. target.subtractToRef(bonePos, zaxis);
  73675. zaxis.normalize();
  73676. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  73677. xaxis.normalize();
  73678. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  73679. yaxis.normalize();
  73680. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  73681. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  73682. return;
  73683. }
  73684. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  73685. return;
  73686. }
  73687. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  73688. return;
  73689. }
  73690. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  73691. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  73692. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  73693. }
  73694. if (this.slerpAmount < 1) {
  73695. if (!this._slerping) {
  73696. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  73697. }
  73698. if (this._transformYawPitch) {
  73699. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  73700. }
  73701. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  73702. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  73703. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  73704. this._slerping = true;
  73705. }
  73706. else {
  73707. if (this._transformYawPitch) {
  73708. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  73709. }
  73710. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  73711. this._slerping = false;
  73712. }
  73713. };
  73714. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  73715. var angDiff = ang2 - ang1;
  73716. angDiff %= Math.PI * 2;
  73717. if (angDiff > Math.PI) {
  73718. angDiff -= Math.PI * 2;
  73719. }
  73720. else if (angDiff < -Math.PI) {
  73721. angDiff += Math.PI * 2;
  73722. }
  73723. return angDiff;
  73724. };
  73725. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  73726. ang1 %= (2 * Math.PI);
  73727. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  73728. ang2 %= (2 * Math.PI);
  73729. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  73730. var ab = 0;
  73731. if (ang1 < ang2) {
  73732. ab = ang2 - ang1;
  73733. }
  73734. else {
  73735. ab = ang1 - ang2;
  73736. }
  73737. if (ab > Math.PI) {
  73738. ab = Math.PI * 2 - ab;
  73739. }
  73740. return ab;
  73741. };
  73742. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  73743. ang %= (2 * Math.PI);
  73744. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  73745. ang1 %= (2 * Math.PI);
  73746. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  73747. ang2 %= (2 * Math.PI);
  73748. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  73749. if (ang1 < ang2) {
  73750. if (ang > ang1 && ang < ang2) {
  73751. return true;
  73752. }
  73753. }
  73754. else {
  73755. if (ang > ang2 && ang < ang1) {
  73756. return true;
  73757. }
  73758. }
  73759. return false;
  73760. };
  73761. 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()];
  73762. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  73763. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73764. return BoneLookController;
  73765. }());
  73766. BABYLON.BoneLookController = BoneLookController;
  73767. })(BABYLON || (BABYLON = {}));
  73768. //# sourceMappingURL=babylon.boneLookController.js.map
  73769. "use strict";
  73770. var BABYLON;
  73771. (function (BABYLON) {
  73772. var Skeleton = /** @class */ (function () {
  73773. function Skeleton(name, id, scene) {
  73774. this.name = name;
  73775. this.id = id;
  73776. this.bones = new Array();
  73777. this.needInitialSkinMatrix = false;
  73778. this._isDirty = true;
  73779. this._meshesWithPoseMatrix = new Array();
  73780. this._identity = BABYLON.Matrix.Identity();
  73781. this._ranges = {};
  73782. this._lastAbsoluteTransformsUpdateId = -1;
  73783. /**
  73784. * Specifies if the skeleton should be serialized.
  73785. */
  73786. this.doNotSerialize = false;
  73787. // Events
  73788. /**
  73789. * An event triggered before computing the skeleton's matrices
  73790. * @type {BABYLON.Observable}
  73791. */
  73792. this.onBeforeComputeObservable = new BABYLON.Observable();
  73793. this.bones = [];
  73794. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  73795. scene.skeletons.push(this);
  73796. //make sure it will recalculate the matrix next time prepare is called.
  73797. this._isDirty = true;
  73798. }
  73799. // Members
  73800. Skeleton.prototype.getTransformMatrices = function (mesh) {
  73801. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  73802. return mesh._bonesTransformMatrices;
  73803. }
  73804. if (!this._transformMatrices) {
  73805. this.prepare();
  73806. }
  73807. return this._transformMatrices;
  73808. };
  73809. Skeleton.prototype.getScene = function () {
  73810. return this._scene;
  73811. };
  73812. // Methods
  73813. /**
  73814. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  73815. */
  73816. Skeleton.prototype.toString = function (fullDetails) {
  73817. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  73818. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  73819. if (fullDetails) {
  73820. ret += ", Ranges: {";
  73821. var first = true;
  73822. for (var name_1 in this._ranges) {
  73823. if (first) {
  73824. ret += ", ";
  73825. first = false;
  73826. }
  73827. ret += name_1;
  73828. }
  73829. ret += "}";
  73830. }
  73831. return ret;
  73832. };
  73833. /**
  73834. * Get bone's index searching by name
  73835. * @param {string} name is bone's name to search for
  73836. * @return {number} Indice of the bone. Returns -1 if not found
  73837. */
  73838. Skeleton.prototype.getBoneIndexByName = function (name) {
  73839. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  73840. if (this.bones[boneIndex].name === name) {
  73841. return boneIndex;
  73842. }
  73843. }
  73844. return -1;
  73845. };
  73846. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  73847. // check name not already in use
  73848. if (!this._ranges[name]) {
  73849. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  73850. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73851. if (this.bones[i].animations[0]) {
  73852. this.bones[i].animations[0].createRange(name, from, to);
  73853. }
  73854. }
  73855. }
  73856. };
  73857. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  73858. if (deleteFrames === void 0) { deleteFrames = true; }
  73859. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73860. if (this.bones[i].animations[0]) {
  73861. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  73862. }
  73863. }
  73864. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  73865. };
  73866. Skeleton.prototype.getAnimationRange = function (name) {
  73867. return this._ranges[name];
  73868. };
  73869. /**
  73870. * Returns as an Array, all AnimationRanges defined on this skeleton
  73871. */
  73872. Skeleton.prototype.getAnimationRanges = function () {
  73873. var animationRanges = [];
  73874. var name;
  73875. var i = 0;
  73876. for (name in this._ranges) {
  73877. animationRanges[i] = this._ranges[name];
  73878. i++;
  73879. }
  73880. return animationRanges;
  73881. };
  73882. /**
  73883. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  73884. */
  73885. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  73886. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  73887. if (this._ranges[name] || !source.getAnimationRange(name)) {
  73888. return false;
  73889. }
  73890. var ret = true;
  73891. var frameOffset = this._getHighestAnimationFrame() + 1;
  73892. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  73893. var boneDict = {};
  73894. var sourceBones = source.bones;
  73895. var nBones;
  73896. var i;
  73897. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  73898. boneDict[sourceBones[i].name] = sourceBones[i];
  73899. }
  73900. if (this.bones.length !== sourceBones.length) {
  73901. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  73902. ret = false;
  73903. }
  73904. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  73905. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  73906. var boneName = this.bones[i].name;
  73907. var sourceBone = boneDict[boneName];
  73908. if (sourceBone) {
  73909. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  73910. }
  73911. else {
  73912. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  73913. ret = false;
  73914. }
  73915. }
  73916. // do not call createAnimationRange(), since it also is done to bones, which was already done
  73917. var range = source.getAnimationRange(name);
  73918. if (range) {
  73919. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  73920. }
  73921. return ret;
  73922. };
  73923. Skeleton.prototype.returnToRest = function () {
  73924. for (var index = 0; index < this.bones.length; index++) {
  73925. this.bones[index].returnToRest();
  73926. }
  73927. };
  73928. Skeleton.prototype._getHighestAnimationFrame = function () {
  73929. var ret = 0;
  73930. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73931. if (this.bones[i].animations[0]) {
  73932. var highest = this.bones[i].animations[0].getHighestFrame();
  73933. if (ret < highest) {
  73934. ret = highest;
  73935. }
  73936. }
  73937. }
  73938. return ret;
  73939. };
  73940. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  73941. var range = this.getAnimationRange(name);
  73942. if (!range) {
  73943. return null;
  73944. }
  73945. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  73946. };
  73947. Skeleton.prototype._markAsDirty = function () {
  73948. this._isDirty = true;
  73949. };
  73950. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  73951. this._meshesWithPoseMatrix.push(mesh);
  73952. };
  73953. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  73954. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  73955. if (index > -1) {
  73956. this._meshesWithPoseMatrix.splice(index, 1);
  73957. }
  73958. };
  73959. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  73960. this.onBeforeComputeObservable.notifyObservers(this);
  73961. for (var index = 0; index < this.bones.length; index++) {
  73962. var bone = this.bones[index];
  73963. var parentBone = bone.getParent();
  73964. if (parentBone) {
  73965. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  73966. }
  73967. else {
  73968. if (initialSkinMatrix) {
  73969. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  73970. }
  73971. else {
  73972. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  73973. }
  73974. }
  73975. if (bone._index !== -1) {
  73976. var mappedIndex = bone._index === null ? index : bone._index;
  73977. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  73978. }
  73979. }
  73980. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  73981. };
  73982. Skeleton.prototype.prepare = function () {
  73983. if (!this._isDirty) {
  73984. return;
  73985. }
  73986. if (this.needInitialSkinMatrix) {
  73987. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  73988. var mesh = this._meshesWithPoseMatrix[index];
  73989. var poseMatrix = mesh.getPoseMatrix();
  73990. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  73991. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  73992. }
  73993. if (this._synchronizedWithMesh !== mesh) {
  73994. this._synchronizedWithMesh = mesh;
  73995. // Prepare bones
  73996. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  73997. var bone = this.bones[boneIndex];
  73998. if (!bone.getParent()) {
  73999. var matrix = bone.getBaseMatrix();
  74000. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  74001. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  74002. }
  74003. }
  74004. }
  74005. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  74006. }
  74007. }
  74008. else {
  74009. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  74010. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  74011. }
  74012. this._computeTransformMatrices(this._transformMatrices, null);
  74013. }
  74014. this._isDirty = false;
  74015. this._scene._activeBones.addCount(this.bones.length, false);
  74016. };
  74017. Skeleton.prototype.getAnimatables = function () {
  74018. if (!this._animatables || this._animatables.length !== this.bones.length) {
  74019. this._animatables = [];
  74020. for (var index = 0; index < this.bones.length; index++) {
  74021. this._animatables.push(this.bones[index]);
  74022. }
  74023. }
  74024. return this._animatables;
  74025. };
  74026. Skeleton.prototype.clone = function (name, id) {
  74027. var result = new Skeleton(name, id || name, this._scene);
  74028. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  74029. for (var index = 0; index < this.bones.length; index++) {
  74030. var source = this.bones[index];
  74031. var parentBone = null;
  74032. var parent_1 = source.getParent();
  74033. if (parent_1) {
  74034. var parentIndex = this.bones.indexOf(parent_1);
  74035. parentBone = result.bones[parentIndex];
  74036. }
  74037. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  74038. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  74039. }
  74040. if (this._ranges) {
  74041. result._ranges = {};
  74042. for (var rangeName in this._ranges) {
  74043. var range = this._ranges[rangeName];
  74044. if (range) {
  74045. result._ranges[rangeName] = range.clone();
  74046. }
  74047. }
  74048. }
  74049. this._isDirty = true;
  74050. return result;
  74051. };
  74052. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  74053. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  74054. this.bones.forEach(function (bone) {
  74055. bone.animations.forEach(function (animation) {
  74056. animation.enableBlending = true;
  74057. animation.blendingSpeed = blendingSpeed;
  74058. });
  74059. });
  74060. };
  74061. Skeleton.prototype.dispose = function () {
  74062. this._meshesWithPoseMatrix = [];
  74063. // Animations
  74064. this.getScene().stopAnimation(this);
  74065. // Remove from scene
  74066. this.getScene().removeSkeleton(this);
  74067. };
  74068. Skeleton.prototype.serialize = function () {
  74069. var serializationObject = {};
  74070. serializationObject.name = this.name;
  74071. serializationObject.id = this.id;
  74072. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  74073. serializationObject.bones = [];
  74074. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  74075. for (var index = 0; index < this.bones.length; index++) {
  74076. var bone = this.bones[index];
  74077. var parent_2 = bone.getParent();
  74078. var serializedBone = {
  74079. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  74080. name: bone.name,
  74081. matrix: bone.getBaseMatrix().toArray(),
  74082. rest: bone.getRestPose().toArray()
  74083. };
  74084. serializationObject.bones.push(serializedBone);
  74085. if (bone.length) {
  74086. serializedBone.length = bone.length;
  74087. }
  74088. if (bone.animations && bone.animations.length > 0) {
  74089. serializedBone.animation = bone.animations[0].serialize();
  74090. }
  74091. serializationObject.ranges = [];
  74092. for (var name in this._ranges) {
  74093. var source = this._ranges[name];
  74094. if (!source) {
  74095. continue;
  74096. }
  74097. var range = {};
  74098. range.name = name;
  74099. range.from = source.from;
  74100. range.to = source.to;
  74101. serializationObject.ranges.push(range);
  74102. }
  74103. }
  74104. return serializationObject;
  74105. };
  74106. Skeleton.Parse = function (parsedSkeleton, scene) {
  74107. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  74108. if (parsedSkeleton.dimensionsAtRest) {
  74109. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  74110. }
  74111. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  74112. var index;
  74113. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  74114. var parsedBone = parsedSkeleton.bones[index];
  74115. var parentBone = null;
  74116. if (parsedBone.parentBoneIndex > -1) {
  74117. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  74118. }
  74119. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  74120. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  74121. if (parsedBone.length) {
  74122. bone.length = parsedBone.length;
  74123. }
  74124. if (parsedBone.animation) {
  74125. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  74126. }
  74127. }
  74128. // placed after bones, so createAnimationRange can cascade down
  74129. if (parsedSkeleton.ranges) {
  74130. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  74131. var data = parsedSkeleton.ranges[index];
  74132. skeleton.createAnimationRange(data.name, data.from, data.to);
  74133. }
  74134. }
  74135. return skeleton;
  74136. };
  74137. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  74138. if (forceUpdate === void 0) { forceUpdate = false; }
  74139. var renderId = this._scene.getRenderId();
  74140. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  74141. this.bones[0].computeAbsoluteTransforms();
  74142. this._lastAbsoluteTransformsUpdateId = renderId;
  74143. }
  74144. };
  74145. Skeleton.prototype.getPoseMatrix = function () {
  74146. var poseMatrix = null;
  74147. if (this._meshesWithPoseMatrix.length > 0) {
  74148. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  74149. }
  74150. return poseMatrix;
  74151. };
  74152. Skeleton.prototype.sortBones = function () {
  74153. var bones = new Array();
  74154. var visited = new Array(this.bones.length);
  74155. for (var index = 0; index < this.bones.length; index++) {
  74156. this._sortBones(index, bones, visited);
  74157. }
  74158. this.bones = bones;
  74159. };
  74160. Skeleton.prototype._sortBones = function (index, bones, visited) {
  74161. if (visited[index]) {
  74162. return;
  74163. }
  74164. visited[index] = true;
  74165. var bone = this.bones[index];
  74166. if (bone._index === undefined) {
  74167. bone._index = index;
  74168. }
  74169. var parentBone = bone.getParent();
  74170. if (parentBone) {
  74171. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  74172. }
  74173. bones.push(bone);
  74174. };
  74175. return Skeleton;
  74176. }());
  74177. BABYLON.Skeleton = Skeleton;
  74178. })(BABYLON || (BABYLON = {}));
  74179. //# sourceMappingURL=babylon.skeleton.js.map
  74180. "use strict";
  74181. var BABYLON;
  74182. (function (BABYLON) {
  74183. var SphericalPolynomial = /** @class */ (function () {
  74184. function SphericalPolynomial() {
  74185. this.x = BABYLON.Vector3.Zero();
  74186. this.y = BABYLON.Vector3.Zero();
  74187. this.z = BABYLON.Vector3.Zero();
  74188. this.xx = BABYLON.Vector3.Zero();
  74189. this.yy = BABYLON.Vector3.Zero();
  74190. this.zz = BABYLON.Vector3.Zero();
  74191. this.xy = BABYLON.Vector3.Zero();
  74192. this.yz = BABYLON.Vector3.Zero();
  74193. this.zx = BABYLON.Vector3.Zero();
  74194. }
  74195. SphericalPolynomial.prototype.addAmbient = function (color) {
  74196. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  74197. this.xx = this.xx.add(colorVector);
  74198. this.yy = this.yy.add(colorVector);
  74199. this.zz = this.zz.add(colorVector);
  74200. };
  74201. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  74202. var result = new SphericalPolynomial();
  74203. result.x = harmonics.L11.scale(1.02333);
  74204. result.y = harmonics.L1_1.scale(1.02333);
  74205. result.z = harmonics.L10.scale(1.02333);
  74206. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  74207. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  74208. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  74209. result.yz = harmonics.L2_1.scale(0.858086);
  74210. result.zx = harmonics.L21.scale(0.858086);
  74211. result.xy = harmonics.L2_2.scale(0.858086);
  74212. result.scale(1.0 / Math.PI);
  74213. return result;
  74214. };
  74215. SphericalPolynomial.prototype.scale = function (scale) {
  74216. this.x = this.x.scale(scale);
  74217. this.y = this.y.scale(scale);
  74218. this.z = this.z.scale(scale);
  74219. this.xx = this.xx.scale(scale);
  74220. this.yy = this.yy.scale(scale);
  74221. this.zz = this.zz.scale(scale);
  74222. this.yz = this.yz.scale(scale);
  74223. this.zx = this.zx.scale(scale);
  74224. this.xy = this.xy.scale(scale);
  74225. };
  74226. return SphericalPolynomial;
  74227. }());
  74228. BABYLON.SphericalPolynomial = SphericalPolynomial;
  74229. var SphericalHarmonics = /** @class */ (function () {
  74230. function SphericalHarmonics() {
  74231. this.L00 = BABYLON.Vector3.Zero();
  74232. this.L1_1 = BABYLON.Vector3.Zero();
  74233. this.L10 = BABYLON.Vector3.Zero();
  74234. this.L11 = BABYLON.Vector3.Zero();
  74235. this.L2_2 = BABYLON.Vector3.Zero();
  74236. this.L2_1 = BABYLON.Vector3.Zero();
  74237. this.L20 = BABYLON.Vector3.Zero();
  74238. this.L21 = BABYLON.Vector3.Zero();
  74239. this.L22 = BABYLON.Vector3.Zero();
  74240. }
  74241. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  74242. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  74243. var c = colorVector.scale(deltaSolidAngle);
  74244. this.L00 = this.L00.add(c.scale(0.282095));
  74245. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  74246. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  74247. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  74248. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  74249. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  74250. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  74251. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  74252. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  74253. };
  74254. SphericalHarmonics.prototype.scale = function (scale) {
  74255. this.L00 = this.L00.scale(scale);
  74256. this.L1_1 = this.L1_1.scale(scale);
  74257. this.L10 = this.L10.scale(scale);
  74258. this.L11 = this.L11.scale(scale);
  74259. this.L2_2 = this.L2_2.scale(scale);
  74260. this.L2_1 = this.L2_1.scale(scale);
  74261. this.L20 = this.L20.scale(scale);
  74262. this.L21 = this.L21.scale(scale);
  74263. this.L22 = this.L22.scale(scale);
  74264. };
  74265. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  74266. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  74267. //
  74268. // E_lm = A_l * L_lm
  74269. //
  74270. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  74271. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  74272. // the scaling factors are given in equation 9.
  74273. // Constant (Band 0)
  74274. this.L00 = this.L00.scale(3.141593);
  74275. // Linear (Band 1)
  74276. this.L1_1 = this.L1_1.scale(2.094395);
  74277. this.L10 = this.L10.scale(2.094395);
  74278. this.L11 = this.L11.scale(2.094395);
  74279. // Quadratic (Band 2)
  74280. this.L2_2 = this.L2_2.scale(0.785398);
  74281. this.L2_1 = this.L2_1.scale(0.785398);
  74282. this.L20 = this.L20.scale(0.785398);
  74283. this.L21 = this.L21.scale(0.785398);
  74284. this.L22 = this.L22.scale(0.785398);
  74285. };
  74286. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  74287. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  74288. // L = (1/pi) * E * rho
  74289. //
  74290. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  74291. this.scale(1.0 / Math.PI);
  74292. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  74293. // (The pixel shader must apply albedo after texture fetches, etc).
  74294. };
  74295. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  74296. var result = new SphericalHarmonics();
  74297. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  74298. result.L1_1 = polynomial.y.scale(0.977204);
  74299. result.L10 = polynomial.z.scale(0.977204);
  74300. result.L11 = polynomial.x.scale(0.977204);
  74301. result.L2_2 = polynomial.xy.scale(1.16538);
  74302. result.L2_1 = polynomial.yz.scale(1.16538);
  74303. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  74304. result.L21 = polynomial.zx.scale(1.16538);
  74305. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  74306. result.scale(Math.PI);
  74307. return result;
  74308. };
  74309. return SphericalHarmonics;
  74310. }());
  74311. BABYLON.SphericalHarmonics = SphericalHarmonics;
  74312. })(BABYLON || (BABYLON = {}));
  74313. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  74314. "use strict";
  74315. var BABYLON;
  74316. (function (BABYLON) {
  74317. var FileFaceOrientation = /** @class */ (function () {
  74318. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  74319. this.name = name;
  74320. this.worldAxisForNormal = worldAxisForNormal;
  74321. this.worldAxisForFileX = worldAxisForFileX;
  74322. this.worldAxisForFileY = worldAxisForFileY;
  74323. }
  74324. return FileFaceOrientation;
  74325. }());
  74326. ;
  74327. /**
  74328. * Helper class dealing with the extraction of spherical polynomial dataArray
  74329. * from a cube map.
  74330. */
  74331. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  74332. function CubeMapToSphericalPolynomialTools() {
  74333. }
  74334. /**
  74335. * Converts a texture to the according Spherical Polynomial data.
  74336. * This extracts the first 3 orders only as they are the only one used in the lighting.
  74337. *
  74338. * @param texture The texture to extract the information from.
  74339. * @return The Spherical Polynomial data.
  74340. */
  74341. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  74342. if (!texture.isCube) {
  74343. // Only supports cube Textures currently.
  74344. return null;
  74345. }
  74346. var size = texture.getSize().width;
  74347. var right = texture.readPixels(0);
  74348. var left = texture.readPixels(1);
  74349. var up;
  74350. var down;
  74351. if (texture.isRenderTarget) {
  74352. up = texture.readPixels(3);
  74353. down = texture.readPixels(2);
  74354. }
  74355. else {
  74356. up = texture.readPixels(2);
  74357. down = texture.readPixels(3);
  74358. }
  74359. var front = texture.readPixels(4);
  74360. var back = texture.readPixels(5);
  74361. var gammaSpace = texture.gammaSpace;
  74362. // Always read as RGBA.
  74363. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  74364. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74365. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74366. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74367. }
  74368. var cubeInfo = {
  74369. size: size,
  74370. right: right,
  74371. left: left,
  74372. up: up,
  74373. down: down,
  74374. front: front,
  74375. back: back,
  74376. format: format,
  74377. type: type,
  74378. gammaSpace: gammaSpace,
  74379. };
  74380. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  74381. };
  74382. /**
  74383. * Converts a cubemap to the according Spherical Polynomial data.
  74384. * This extracts the first 3 orders only as they are the only one used in the lighting.
  74385. *
  74386. * @param cubeInfo The Cube map to extract the information from.
  74387. * @return The Spherical Polynomial data.
  74388. */
  74389. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  74390. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  74391. var totalSolidAngle = 0.0;
  74392. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  74393. var du = 2.0 / cubeInfo.size;
  74394. var dv = du;
  74395. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  74396. var minUV = du * 0.5 - 1.0;
  74397. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74398. var fileFace = this.FileFaces[faceIndex];
  74399. var dataArray = cubeInfo[fileFace.name];
  74400. var v = minUV;
  74401. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  74402. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  74403. // Because SP is still linear, so summation is fine in that basis.
  74404. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  74405. for (var y = 0; y < cubeInfo.size; y++) {
  74406. var u = minUV;
  74407. for (var x = 0; x < cubeInfo.size; x++) {
  74408. // World direction (not normalised)
  74409. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  74410. worldDirection.normalize();
  74411. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  74412. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  74413. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  74414. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  74415. // Handle Integer types.
  74416. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74417. r /= 255;
  74418. g /= 255;
  74419. b /= 255;
  74420. }
  74421. // Handle Gamma space textures.
  74422. if (cubeInfo.gammaSpace) {
  74423. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  74424. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  74425. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  74426. }
  74427. var color = new BABYLON.Color3(r, g, b);
  74428. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  74429. totalSolidAngle += deltaSolidAngle;
  74430. u += du;
  74431. }
  74432. v += dv;
  74433. }
  74434. }
  74435. // Solid angle for entire sphere is 4*pi
  74436. var sphereSolidAngle = 4.0 * Math.PI;
  74437. // Adjust the solid angle to allow for how many faces we processed.
  74438. var facesProcessed = 6.0;
  74439. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  74440. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  74441. // This is needed because the numerical integration over the cube uses a
  74442. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  74443. // and also to compensate for accumulative error due to float precision in the summation.
  74444. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  74445. sphericalHarmonics.scale(correctionFactor);
  74446. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  74447. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  74448. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  74449. };
  74450. CubeMapToSphericalPolynomialTools.FileFaces = [
  74451. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  74452. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  74453. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  74454. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  74455. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  74456. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  74457. ];
  74458. return CubeMapToSphericalPolynomialTools;
  74459. }());
  74460. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  74461. })(BABYLON || (BABYLON = {}));
  74462. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  74463. "use strict";
  74464. var BABYLON;
  74465. (function (BABYLON) {
  74466. /**
  74467. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  74468. */
  74469. var PanoramaToCubeMapTools = /** @class */ (function () {
  74470. function PanoramaToCubeMapTools() {
  74471. }
  74472. /**
  74473. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  74474. *
  74475. * @param float32Array The source data.
  74476. * @param inputWidth The width of the input panorama.
  74477. * @param inputhHeight The height of the input panorama.
  74478. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  74479. * @return The cubemap data
  74480. */
  74481. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  74482. if (!float32Array) {
  74483. throw "ConvertPanoramaToCubemap: input cannot be null";
  74484. }
  74485. if (float32Array.length != inputWidth * inputHeight * 3) {
  74486. throw "ConvertPanoramaToCubemap: input size is wrong";
  74487. }
  74488. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  74489. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  74490. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  74491. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  74492. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  74493. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  74494. return {
  74495. front: textureFront,
  74496. back: textureBack,
  74497. left: textureLeft,
  74498. right: textureRight,
  74499. up: textureUp,
  74500. down: textureDown,
  74501. size: size,
  74502. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  74503. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  74504. gammaSpace: false,
  74505. };
  74506. };
  74507. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  74508. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  74509. var textureArray = new Float32Array(buffer);
  74510. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  74511. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  74512. var dy = 1 / texSize;
  74513. var fy = 0;
  74514. for (var y = 0; y < texSize; y++) {
  74515. var xv1 = faceData[0];
  74516. var xv2 = faceData[2];
  74517. for (var x = 0; x < texSize; x++) {
  74518. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  74519. v.normalize();
  74520. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  74521. // 3 channels per pixels
  74522. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  74523. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  74524. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  74525. xv1 = xv1.add(rotDX1);
  74526. xv2 = xv2.add(rotDX2);
  74527. }
  74528. fy += dy;
  74529. }
  74530. return textureArray;
  74531. };
  74532. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  74533. var theta = Math.atan2(vDir.z, vDir.x);
  74534. var phi = Math.acos(vDir.y);
  74535. while (theta < -Math.PI)
  74536. theta += 2 * Math.PI;
  74537. while (theta > Math.PI)
  74538. theta -= 2 * Math.PI;
  74539. var dx = theta / Math.PI;
  74540. var dy = phi / Math.PI;
  74541. // recenter.
  74542. dx = dx * 0.5 + 0.5;
  74543. var px = Math.round(dx * inputWidth);
  74544. if (px < 0)
  74545. px = 0;
  74546. else if (px >= inputWidth)
  74547. px = inputWidth - 1;
  74548. var py = Math.round(dy * inputHeight);
  74549. if (py < 0)
  74550. py = 0;
  74551. else if (py >= inputHeight)
  74552. py = inputHeight - 1;
  74553. var inputY = (inputHeight - py - 1);
  74554. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  74555. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  74556. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  74557. return {
  74558. r: r,
  74559. g: g,
  74560. b: b
  74561. };
  74562. };
  74563. PanoramaToCubeMapTools.FACE_FRONT = [
  74564. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74565. new BABYLON.Vector3(1.0, -1.0, -1.0),
  74566. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  74567. new BABYLON.Vector3(1.0, 1.0, -1.0)
  74568. ];
  74569. PanoramaToCubeMapTools.FACE_BACK = [
  74570. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74571. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74572. new BABYLON.Vector3(1.0, 1.0, 1.0),
  74573. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  74574. ];
  74575. PanoramaToCubeMapTools.FACE_RIGHT = [
  74576. new BABYLON.Vector3(1.0, -1.0, -1.0),
  74577. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74578. new BABYLON.Vector3(1.0, 1.0, -1.0),
  74579. new BABYLON.Vector3(1.0, 1.0, 1.0)
  74580. ];
  74581. PanoramaToCubeMapTools.FACE_LEFT = [
  74582. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74583. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74584. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  74585. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  74586. ];
  74587. PanoramaToCubeMapTools.FACE_DOWN = [
  74588. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  74589. new BABYLON.Vector3(1.0, 1.0, -1.0),
  74590. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  74591. new BABYLON.Vector3(1.0, 1.0, 1.0)
  74592. ];
  74593. PanoramaToCubeMapTools.FACE_UP = [
  74594. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74595. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74596. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74597. new BABYLON.Vector3(1.0, -1.0, -1.0)
  74598. ];
  74599. return PanoramaToCubeMapTools;
  74600. }());
  74601. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  74602. })(BABYLON || (BABYLON = {}));
  74603. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  74604. "use strict";
  74605. var BABYLON;
  74606. (function (BABYLON) {
  74607. ;
  74608. /**
  74609. * This groups tools to convert HDR texture to native colors array.
  74610. */
  74611. var HDRTools = /** @class */ (function () {
  74612. function HDRTools() {
  74613. }
  74614. HDRTools.Ldexp = function (mantissa, exponent) {
  74615. if (exponent > 1023) {
  74616. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  74617. }
  74618. if (exponent < -1074) {
  74619. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  74620. }
  74621. return mantissa * Math.pow(2, exponent);
  74622. };
  74623. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  74624. if (exponent > 0) {
  74625. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  74626. float32array[index + 0] = red * exponent;
  74627. float32array[index + 1] = green * exponent;
  74628. float32array[index + 2] = blue * exponent;
  74629. }
  74630. else {
  74631. float32array[index + 0] = 0;
  74632. float32array[index + 1] = 0;
  74633. float32array[index + 2] = 0;
  74634. }
  74635. };
  74636. HDRTools.readStringLine = function (uint8array, startIndex) {
  74637. var line = "";
  74638. var character = "";
  74639. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  74640. character = String.fromCharCode(uint8array[i]);
  74641. if (character == "\n") {
  74642. break;
  74643. }
  74644. line += character;
  74645. }
  74646. return line;
  74647. };
  74648. /**
  74649. * Reads header information from an RGBE texture stored in a native array.
  74650. * More information on this format are available here:
  74651. * https://en.wikipedia.org/wiki/RGBE_image_format
  74652. *
  74653. * @param uint8array The binary file stored in native array.
  74654. * @return The header information.
  74655. */
  74656. HDRTools.RGBE_ReadHeader = function (uint8array) {
  74657. var height = 0;
  74658. var width = 0;
  74659. var line = this.readStringLine(uint8array, 0);
  74660. if (line[0] != '#' || line[1] != '?') {
  74661. throw "Bad HDR Format.";
  74662. }
  74663. var endOfHeader = false;
  74664. var findFormat = false;
  74665. var lineIndex = 0;
  74666. do {
  74667. lineIndex += (line.length + 1);
  74668. line = this.readStringLine(uint8array, lineIndex);
  74669. if (line == "FORMAT=32-bit_rle_rgbe") {
  74670. findFormat = true;
  74671. }
  74672. else if (line.length == 0) {
  74673. endOfHeader = true;
  74674. }
  74675. } while (!endOfHeader);
  74676. if (!findFormat) {
  74677. throw "HDR Bad header format, unsupported FORMAT";
  74678. }
  74679. lineIndex += (line.length + 1);
  74680. line = this.readStringLine(uint8array, lineIndex);
  74681. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  74682. var match = sizeRegexp.exec(line);
  74683. // TODO. Support +Y and -X if needed.
  74684. if (!match || match.length < 3) {
  74685. throw "HDR Bad header format, no size";
  74686. }
  74687. width = parseInt(match[2]);
  74688. height = parseInt(match[1]);
  74689. if (width < 8 || width > 0x7fff) {
  74690. throw "HDR Bad header format, unsupported size";
  74691. }
  74692. lineIndex += (line.length + 1);
  74693. return {
  74694. height: height,
  74695. width: width,
  74696. dataPosition: lineIndex
  74697. };
  74698. };
  74699. /**
  74700. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  74701. * This RGBE texture needs to store the information as a panorama.
  74702. *
  74703. * More information on this format are available here:
  74704. * https://en.wikipedia.org/wiki/RGBE_image_format
  74705. *
  74706. * @param buffer The binary file stored in an array buffer.
  74707. * @param size The expected size of the extracted cubemap.
  74708. * @return The Cube Map information.
  74709. */
  74710. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  74711. var uint8array = new Uint8Array(buffer);
  74712. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  74713. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  74714. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  74715. return cubeMapData;
  74716. };
  74717. /**
  74718. * Returns the pixels data extracted from an RGBE texture.
  74719. * This pixels will be stored left to right up to down in the R G B order in one array.
  74720. *
  74721. * More information on this format are available here:
  74722. * https://en.wikipedia.org/wiki/RGBE_image_format
  74723. *
  74724. * @param uint8array The binary file stored in an array buffer.
  74725. * @param hdrInfo The header information of the file.
  74726. * @return The pixels data in RGB right to left up to down order.
  74727. */
  74728. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  74729. // Keep for multi format supports.
  74730. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  74731. };
  74732. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  74733. var num_scanlines = hdrInfo.height;
  74734. var scanline_width = hdrInfo.width;
  74735. var a, b, c, d, count;
  74736. var dataIndex = hdrInfo.dataPosition;
  74737. var index = 0, endIndex = 0, i = 0;
  74738. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  74739. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  74740. // 3 channels of 4 bytes per pixel in float.
  74741. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  74742. var resultArray = new Float32Array(resultBuffer);
  74743. // read in each successive scanline
  74744. while (num_scanlines > 0) {
  74745. a = uint8array[dataIndex++];
  74746. b = uint8array[dataIndex++];
  74747. c = uint8array[dataIndex++];
  74748. d = uint8array[dataIndex++];
  74749. if (a != 2 || b != 2 || (c & 0x80)) {
  74750. // this file is not run length encoded
  74751. throw "HDR Bad header format, not RLE";
  74752. }
  74753. if (((c << 8) | d) != scanline_width) {
  74754. throw "HDR Bad header format, wrong scan line width";
  74755. }
  74756. index = 0;
  74757. // read each of the four channels for the scanline into the buffer
  74758. for (i = 0; i < 4; i++) {
  74759. endIndex = (i + 1) * scanline_width;
  74760. while (index < endIndex) {
  74761. a = uint8array[dataIndex++];
  74762. b = uint8array[dataIndex++];
  74763. if (a > 128) {
  74764. // a run of the same value
  74765. count = a - 128;
  74766. if ((count == 0) || (count > endIndex - index)) {
  74767. throw "HDR Bad Format, bad scanline data (run)";
  74768. }
  74769. while (count-- > 0) {
  74770. scanLineArray[index++] = b;
  74771. }
  74772. }
  74773. else {
  74774. // a non-run
  74775. count = a;
  74776. if ((count == 0) || (count > endIndex - index)) {
  74777. throw "HDR Bad Format, bad scanline data (non-run)";
  74778. }
  74779. scanLineArray[index++] = b;
  74780. if (--count > 0) {
  74781. for (var j = 0; j < count; j++) {
  74782. scanLineArray[index++] = uint8array[dataIndex++];
  74783. }
  74784. }
  74785. }
  74786. }
  74787. }
  74788. // now convert data from buffer into floats
  74789. for (i = 0; i < scanline_width; i++) {
  74790. a = scanLineArray[i];
  74791. b = scanLineArray[i + scanline_width];
  74792. c = scanLineArray[i + 2 * scanline_width];
  74793. d = scanLineArray[i + 3 * scanline_width];
  74794. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  74795. }
  74796. num_scanlines--;
  74797. }
  74798. return resultArray;
  74799. };
  74800. return HDRTools;
  74801. }());
  74802. BABYLON.HDRTools = HDRTools;
  74803. })(BABYLON || (BABYLON = {}));
  74804. //# sourceMappingURL=babylon.hdr.js.map
  74805. "use strict";
  74806. var BABYLON;
  74807. (function (BABYLON) {
  74808. /**
  74809. * This represents a texture coming from an HDR input.
  74810. *
  74811. * The only supported format is currently panorama picture stored in RGBE format.
  74812. * Example of such files can be found on HDRLib: http://hdrlib.com/
  74813. */
  74814. var HDRCubeTexture = /** @class */ (function (_super) {
  74815. __extends(HDRCubeTexture, _super);
  74816. /**
  74817. * Instantiates an HDRTexture from the following parameters.
  74818. *
  74819. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  74820. * @param scene The scene the texture will be used in
  74821. * @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.
  74822. * @param noMipmap Forces to not generate the mipmap if true
  74823. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  74824. * @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)
  74825. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  74826. */
  74827. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  74828. if (noMipmap === void 0) { noMipmap = false; }
  74829. if (generateHarmonics === void 0) { generateHarmonics = true; }
  74830. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  74831. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  74832. if (onLoad === void 0) { onLoad = null; }
  74833. if (onError === void 0) { onError = null; }
  74834. var _this = _super.call(this, scene) || this;
  74835. _this._useInGammaSpace = false;
  74836. _this._generateHarmonics = true;
  74837. _this._isBABYLONPreprocessed = false;
  74838. _this._onLoad = null;
  74839. _this._onError = null;
  74840. /**
  74841. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  74842. */
  74843. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  74844. /**
  74845. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  74846. * This is usefull at run time to apply the good shader.
  74847. */
  74848. _this.isPMREM = false;
  74849. _this._isBlocking = true;
  74850. /**
  74851. * Gets or sets the center of the bounding box associated with the cube texture
  74852. * It must define where the camera used to render the texture was set
  74853. */
  74854. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  74855. if (!url) {
  74856. return _this;
  74857. }
  74858. _this.name = url;
  74859. _this.url = url;
  74860. _this.hasAlpha = false;
  74861. _this.isCube = true;
  74862. _this._textureMatrix = BABYLON.Matrix.Identity();
  74863. _this._onLoad = onLoad;
  74864. _this._onError = onError;
  74865. _this.gammaSpace = false;
  74866. var caps = scene.getEngine().getCaps();
  74867. if (size) {
  74868. _this._isBABYLONPreprocessed = false;
  74869. _this._noMipmap = noMipmap;
  74870. _this._size = size;
  74871. _this._useInGammaSpace = useInGammaSpace;
  74872. _this._usePMREMGenerator = usePMREMGenerator &&
  74873. caps.textureLOD &&
  74874. caps.textureFloat &&
  74875. !_this._useInGammaSpace;
  74876. }
  74877. else {
  74878. _this._isBABYLONPreprocessed = true;
  74879. _this._noMipmap = false;
  74880. _this._useInGammaSpace = false;
  74881. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  74882. !_this._useInGammaSpace;
  74883. }
  74884. _this.isPMREM = _this._usePMREMGenerator;
  74885. _this._texture = _this._getFromCache(url, _this._noMipmap);
  74886. if (!_this._texture) {
  74887. if (!scene.useDelayedTextureLoading) {
  74888. _this.loadTexture();
  74889. }
  74890. else {
  74891. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  74892. }
  74893. }
  74894. return _this;
  74895. }
  74896. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  74897. /**
  74898. * Gets wether or not the texture is blocking during loading.
  74899. */
  74900. get: function () {
  74901. return this._isBlocking;
  74902. },
  74903. /**
  74904. * Sets wether or not the texture is blocking during loading.
  74905. */
  74906. set: function (value) {
  74907. this._isBlocking = value;
  74908. },
  74909. enumerable: true,
  74910. configurable: true
  74911. });
  74912. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  74913. get: function () {
  74914. return this._boundingBoxSize;
  74915. },
  74916. /**
  74917. * Gets or sets the size of the bounding box associated with the cube texture
  74918. * When defined, the cubemap will switch to local mode
  74919. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  74920. * @example https://www.babylonjs-playground.com/#RNASML
  74921. */
  74922. set: function (value) {
  74923. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  74924. return;
  74925. }
  74926. this._boundingBoxSize = value;
  74927. var scene = this.getScene();
  74928. if (scene) {
  74929. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  74930. }
  74931. },
  74932. enumerable: true,
  74933. configurable: true
  74934. });
  74935. /**
  74936. * Occurs when the file is a preprocessed .babylon.hdr file.
  74937. */
  74938. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  74939. var _this = this;
  74940. var mipLevels = 0;
  74941. var floatArrayView = null;
  74942. var scene = this.getScene();
  74943. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  74944. var mips = new Array();
  74945. if (!floatArrayView) {
  74946. return mips;
  74947. }
  74948. var startIndex = 30;
  74949. for (var level = 0; level < mipLevels; level++) {
  74950. mips.push([]);
  74951. // Fill each pixel of the mip level.
  74952. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  74953. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74954. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  74955. mips[level].push(faceData);
  74956. startIndex += faceSize;
  74957. }
  74958. }
  74959. return mips;
  74960. } : null;
  74961. var callback = function (buffer) {
  74962. var scene = _this.getScene();
  74963. if (!scene) {
  74964. return null;
  74965. }
  74966. // Create Native Array Views
  74967. var intArrayView = new Int32Array(buffer);
  74968. floatArrayView = new Float32Array(buffer);
  74969. // Fill header.
  74970. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  74971. _this._size = intArrayView[1]; // CubeMap max mip face size.
  74972. // Update Texture Information.
  74973. if (!_this._texture) {
  74974. return null;
  74975. }
  74976. _this._texture.updateSize(_this._size, _this._size);
  74977. // Fill polynomial information.
  74978. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  74979. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  74980. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  74981. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  74982. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  74983. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  74984. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  74985. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  74986. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  74987. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  74988. _this.sphericalPolynomial = sphericalPolynomial;
  74989. // Fill pixel data.
  74990. mipLevels = intArrayView[29]; // Number of mip levels.
  74991. var startIndex = 30;
  74992. var data = [];
  74993. var faceSize = Math.pow(_this._size, 2) * 3;
  74994. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74995. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  74996. startIndex += faceSize;
  74997. }
  74998. var results = [];
  74999. var byteArray = null;
  75000. // Push each faces.
  75001. for (var k = 0; k < 6; k++) {
  75002. var dataFace = null;
  75003. // To be deprecated.
  75004. if (version === 1) {
  75005. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  75006. dataFace = data[j];
  75007. }
  75008. // If special cases.
  75009. if (!mipmapGenerator && dataFace) {
  75010. if (!scene.getEngine().getCaps().textureFloat) {
  75011. // 3 channels of 1 bytes per pixel in bytes.
  75012. var byteBuffer = new ArrayBuffer(faceSize);
  75013. byteArray = new Uint8Array(byteBuffer);
  75014. }
  75015. for (var i = 0; i < _this._size * _this._size; i++) {
  75016. // Put in gamma space if requested.
  75017. if (_this._useInGammaSpace) {
  75018. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  75019. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  75020. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  75021. }
  75022. // Convert to int texture for fallback.
  75023. if (byteArray) {
  75024. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  75025. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  75026. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  75027. // May use luminance instead if the result is not accurate.
  75028. var max = Math.max(Math.max(r, g), b);
  75029. if (max > 255) {
  75030. var scale = 255 / max;
  75031. r *= scale;
  75032. g *= scale;
  75033. b *= scale;
  75034. }
  75035. byteArray[(i * 3) + 0] = r;
  75036. byteArray[(i * 3) + 1] = g;
  75037. byteArray[(i * 3) + 2] = b;
  75038. }
  75039. }
  75040. }
  75041. // Fill the array accordingly.
  75042. if (byteArray) {
  75043. results.push(byteArray);
  75044. }
  75045. else {
  75046. results.push(dataFace);
  75047. }
  75048. }
  75049. return results;
  75050. };
  75051. if (scene) {
  75052. 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);
  75053. }
  75054. };
  75055. /**
  75056. * Occurs when the file is raw .hdr file.
  75057. */
  75058. HDRCubeTexture.prototype.loadHDRTexture = function () {
  75059. var _this = this;
  75060. var callback = function (buffer) {
  75061. var scene = _this.getScene();
  75062. if (!scene) {
  75063. return null;
  75064. }
  75065. // Extract the raw linear data.
  75066. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  75067. // Generate harmonics if needed.
  75068. if (_this._generateHarmonics) {
  75069. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  75070. _this.sphericalPolynomial = sphericalPolynomial;
  75071. }
  75072. var results = [];
  75073. var byteArray = null;
  75074. // Push each faces.
  75075. for (var j = 0; j < 6; j++) {
  75076. // Create uintarray fallback.
  75077. if (!scene.getEngine().getCaps().textureFloat) {
  75078. // 3 channels of 1 bytes per pixel in bytes.
  75079. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  75080. byteArray = new Uint8Array(byteBuffer);
  75081. }
  75082. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  75083. // If special cases.
  75084. if (_this._useInGammaSpace || byteArray) {
  75085. for (var i = 0; i < _this._size * _this._size; i++) {
  75086. // Put in gamma space if requested.
  75087. if (_this._useInGammaSpace) {
  75088. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  75089. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  75090. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  75091. }
  75092. // Convert to int texture for fallback.
  75093. if (byteArray) {
  75094. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  75095. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  75096. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  75097. // May use luminance instead if the result is not accurate.
  75098. var max = Math.max(Math.max(r, g), b);
  75099. if (max > 255) {
  75100. var scale = 255 / max;
  75101. r *= scale;
  75102. g *= scale;
  75103. b *= scale;
  75104. }
  75105. byteArray[(i * 3) + 0] = r;
  75106. byteArray[(i * 3) + 1] = g;
  75107. byteArray[(i * 3) + 2] = b;
  75108. }
  75109. }
  75110. }
  75111. if (byteArray) {
  75112. results.push(byteArray);
  75113. }
  75114. else {
  75115. results.push(dataFace);
  75116. }
  75117. }
  75118. return results;
  75119. };
  75120. var mipmapGenerator = null;
  75121. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  75122. // if (!this._noMipmap &&
  75123. // this._usePMREMGenerator) {
  75124. // mipmapGenerator = (data: ArrayBufferView[]) => {
  75125. // // Custom setup of the generator matching with the PBR shader values.
  75126. // var generator = new BABYLON.PMREMGenerator(data,
  75127. // this._size,
  75128. // this._size,
  75129. // 0,
  75130. // 3,
  75131. // this.getScene().getEngine().getCaps().textureFloat,
  75132. // 2048,
  75133. // 0.25,
  75134. // false,
  75135. // true);
  75136. // return generator.filterCubeMap();
  75137. // };
  75138. // }
  75139. var scene = this.getScene();
  75140. if (scene) {
  75141. 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);
  75142. }
  75143. };
  75144. /**
  75145. * Starts the loading process of the texture.
  75146. */
  75147. HDRCubeTexture.prototype.loadTexture = function () {
  75148. if (this._isBABYLONPreprocessed) {
  75149. this.loadBabylonTexture();
  75150. }
  75151. else {
  75152. this.loadHDRTexture();
  75153. }
  75154. };
  75155. HDRCubeTexture.prototype.clone = function () {
  75156. var scene = this.getScene();
  75157. if (!scene) {
  75158. return this;
  75159. }
  75160. var size = (this._isBABYLONPreprocessed ? null : this._size);
  75161. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  75162. // Base texture
  75163. newTexture.level = this.level;
  75164. newTexture.wrapU = this.wrapU;
  75165. newTexture.wrapV = this.wrapV;
  75166. newTexture.coordinatesIndex = this.coordinatesIndex;
  75167. newTexture.coordinatesMode = this.coordinatesMode;
  75168. return newTexture;
  75169. };
  75170. // Methods
  75171. HDRCubeTexture.prototype.delayLoad = function () {
  75172. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  75173. return;
  75174. }
  75175. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  75176. this._texture = this._getFromCache(this.url, this._noMipmap);
  75177. if (!this._texture) {
  75178. this.loadTexture();
  75179. }
  75180. };
  75181. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  75182. return this._textureMatrix;
  75183. };
  75184. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  75185. this._textureMatrix = value;
  75186. };
  75187. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  75188. var texture = null;
  75189. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  75190. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  75191. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  75192. texture.name = parsedTexture.name;
  75193. texture.hasAlpha = parsedTexture.hasAlpha;
  75194. texture.level = parsedTexture.level;
  75195. texture.coordinatesMode = parsedTexture.coordinatesMode;
  75196. texture.isBlocking = parsedTexture.isBlocking;
  75197. }
  75198. if (texture) {
  75199. if (parsedTexture.boundingBoxPosition) {
  75200. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  75201. }
  75202. if (parsedTexture.boundingBoxSize) {
  75203. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  75204. }
  75205. }
  75206. return texture;
  75207. };
  75208. HDRCubeTexture.prototype.serialize = function () {
  75209. if (!this.name) {
  75210. return null;
  75211. }
  75212. var serializationObject = {};
  75213. serializationObject.name = this.name;
  75214. serializationObject.hasAlpha = this.hasAlpha;
  75215. serializationObject.isCube = true;
  75216. serializationObject.level = this.level;
  75217. serializationObject.size = this._size;
  75218. serializationObject.coordinatesMode = this.coordinatesMode;
  75219. serializationObject.useInGammaSpace = this._useInGammaSpace;
  75220. serializationObject.generateHarmonics = this._generateHarmonics;
  75221. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  75222. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  75223. serializationObject.customType = "BABYLON.HDRCubeTexture";
  75224. serializationObject.noMipmap = this._noMipmap;
  75225. serializationObject.isBlocking = this._isBlocking;
  75226. return serializationObject;
  75227. };
  75228. /**
  75229. * Saves as a file the data contained in the texture in a binary format.
  75230. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  75231. * as the spherical used in the lighting.
  75232. * @param url The HDR file url.
  75233. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  75234. * @param onError Method called if any error happens during download.
  75235. * @return The packed binary data.
  75236. */
  75237. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  75238. if (onError === void 0) { onError = null; }
  75239. var callback = function (buffer) {
  75240. var data = new Blob([buffer], { type: 'application/octet-stream' });
  75241. // Returns a URL you can use as a href.
  75242. var objUrl = window.URL.createObjectURL(data);
  75243. // Simulates a link to it and click to dowload.
  75244. var a = document.createElement("a");
  75245. document.body.appendChild(a);
  75246. a.style.display = "none";
  75247. a.href = objUrl;
  75248. a.download = "envmap.babylon.hdr";
  75249. a.click();
  75250. };
  75251. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  75252. };
  75253. /**
  75254. * Serializes the data contained in the texture in a binary format.
  75255. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  75256. * as the spherical used in the lighting.
  75257. * @param url The HDR file url.
  75258. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  75259. * @param onError Method called if any error happens during download.
  75260. * @return The packed binary data.
  75261. */
  75262. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  75263. if (onError === void 0) { onError = null; }
  75264. // Needs the url tho create the texture.
  75265. if (!url) {
  75266. return;
  75267. }
  75268. // Check Power of two size.
  75269. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  75270. return;
  75271. }
  75272. // Coming Back in 3.x.
  75273. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  75274. };
  75275. HDRCubeTexture._facesMapping = [
  75276. "right",
  75277. "left",
  75278. "up",
  75279. "down",
  75280. "front",
  75281. "back"
  75282. ];
  75283. return HDRCubeTexture;
  75284. }(BABYLON.BaseTexture));
  75285. BABYLON.HDRCubeTexture = HDRCubeTexture;
  75286. })(BABYLON || (BABYLON = {}));
  75287. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  75288. "use strict";
  75289. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  75290. // Huge respect for a such great lib.
  75291. // Earcut license:
  75292. // Copyright (c) 2016, Mapbox
  75293. //
  75294. // Permission to use, copy, modify, and/or distribute this software for any purpose
  75295. // with or without fee is hereby granted, provided that the above copyright notice
  75296. // and this permission notice appear in all copies.
  75297. //
  75298. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  75299. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  75300. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  75301. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  75302. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  75303. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  75304. // THIS SOFTWARE.
  75305. var Earcut;
  75306. (function (Earcut) {
  75307. /**
  75308. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  75309. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  75310. * @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).
  75311. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  75312. */
  75313. function earcut(data, holeIndices, dim) {
  75314. dim = dim || 2;
  75315. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  75316. if (!outerNode)
  75317. return triangles;
  75318. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  75319. if (hasHoles)
  75320. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  75321. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  75322. if (data.length > 80 * dim) {
  75323. minX = maxX = data[0];
  75324. minY = maxY = data[1];
  75325. for (var i = dim; i < outerLen; i += dim) {
  75326. x = data[i];
  75327. y = data[i + 1];
  75328. if (x < minX)
  75329. minX = x;
  75330. if (y < minY)
  75331. minY = y;
  75332. if (x > maxX)
  75333. maxX = x;
  75334. if (y > maxY)
  75335. maxY = y;
  75336. }
  75337. // minX, minY and size are later used to transform coords into integers for z-order calculation
  75338. size = Math.max(maxX - minX, maxY - minY);
  75339. }
  75340. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  75341. return triangles;
  75342. }
  75343. Earcut.earcut = earcut;
  75344. var Node = /** @class */ (function () {
  75345. function Node(i, x, y) {
  75346. this.i = i;
  75347. this.x = x;
  75348. this.y = y;
  75349. this.prev = null;
  75350. this.next = null;
  75351. this.z = null;
  75352. this.prevZ = null;
  75353. this.nextZ = null;
  75354. this.steiner = false;
  75355. }
  75356. return Node;
  75357. }());
  75358. // create a circular doubly linked list from polygon points in the specified winding order
  75359. function linkedList(data, start, end, dim, clockwise) {
  75360. var i, last = null;
  75361. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  75362. for (i = start; i < end; i += dim)
  75363. last = insertNode(i, data[i], data[i + 1], last);
  75364. }
  75365. else {
  75366. for (i = end - dim; i >= start; i -= dim)
  75367. last = insertNode(i, data[i], data[i + 1], last);
  75368. }
  75369. if (last && equals(last, last.next)) {
  75370. removeNode(last);
  75371. last = last.next;
  75372. }
  75373. return last;
  75374. }
  75375. // eliminate colinear or duplicate points
  75376. function filterPoints(start, end) {
  75377. if (!start)
  75378. return start;
  75379. if (!end)
  75380. end = start;
  75381. var p = start, again;
  75382. do {
  75383. again = false;
  75384. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  75385. removeNode(p);
  75386. p = end = p.prev;
  75387. if (p === p.next)
  75388. return undefined;
  75389. again = true;
  75390. }
  75391. else {
  75392. p = p.next;
  75393. }
  75394. } while (again || p !== end);
  75395. return end;
  75396. }
  75397. // main ear slicing loop which triangulates a polygon (given as a linked list)
  75398. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  75399. if (!ear)
  75400. return;
  75401. // interlink polygon nodes in z-order
  75402. if (!pass && size)
  75403. indexCurve(ear, minX, minY, size);
  75404. var stop = ear, prev, next;
  75405. // iterate through ears, slicing them one by one
  75406. while (ear.prev !== ear.next) {
  75407. prev = ear.prev;
  75408. next = ear.next;
  75409. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  75410. // cut off the triangle
  75411. triangles.push(prev.i / dim);
  75412. triangles.push(ear.i / dim);
  75413. triangles.push(next.i / dim);
  75414. removeNode(ear);
  75415. // skipping the next vertice leads to less sliver triangles
  75416. ear = next.next;
  75417. stop = next.next;
  75418. continue;
  75419. }
  75420. ear = next;
  75421. // if we looped through the whole remaining polygon and can't find any more ears
  75422. if (ear === stop) {
  75423. // try filtering points and slicing again
  75424. if (!pass) {
  75425. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  75426. // if this didn't work, try curing all small self-intersections locally
  75427. }
  75428. else if (pass === 1) {
  75429. ear = cureLocalIntersections(ear, triangles, dim);
  75430. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  75431. // as a last resort, try splitting the remaining polygon into two
  75432. }
  75433. else if (pass === 2) {
  75434. splitEarcut(ear, triangles, dim, minX, minY, size);
  75435. }
  75436. break;
  75437. }
  75438. }
  75439. }
  75440. // check whether a polygon node forms a valid ear with adjacent nodes
  75441. function isEar(ear) {
  75442. var a = ear.prev, b = ear, c = ear.next;
  75443. if (area(a, b, c) >= 0)
  75444. return false; // reflex, can't be an ear
  75445. // now make sure we don't have other points inside the potential ear
  75446. var p = ear.next.next;
  75447. while (p !== ear.prev) {
  75448. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75449. area(p.prev, p, p.next) >= 0)
  75450. return false;
  75451. p = p.next;
  75452. }
  75453. return true;
  75454. }
  75455. function isEarHashed(ear, minX, minY, size) {
  75456. var a = ear.prev, b = ear, c = ear.next;
  75457. if (area(a, b, c) >= 0)
  75458. return false; // reflex, can't be an ear
  75459. // triangle bbox; min & max are calculated like this for speed
  75460. 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);
  75461. // z-order range for the current triangle bbox;
  75462. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  75463. // first look for points inside the triangle in increasing z-order
  75464. var p = ear.nextZ;
  75465. while (p && p.z <= maxZ) {
  75466. if (p !== ear.prev &&
  75467. p !== ear.next &&
  75468. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75469. area(p.prev, p, p.next) >= 0)
  75470. return false;
  75471. p = p.nextZ;
  75472. }
  75473. // then look for points in decreasing z-order
  75474. p = ear.prevZ;
  75475. while (p && p.z >= minZ) {
  75476. if (p !== ear.prev &&
  75477. p !== ear.next &&
  75478. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75479. area(p.prev, p, p.next) >= 0)
  75480. return false;
  75481. p = p.prevZ;
  75482. }
  75483. return true;
  75484. }
  75485. // go through all polygon nodes and cure small local self-intersections
  75486. function cureLocalIntersections(start, triangles, dim) {
  75487. var p = start;
  75488. do {
  75489. var a = p.prev, b = p.next.next;
  75490. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  75491. triangles.push(a.i / dim);
  75492. triangles.push(p.i / dim);
  75493. triangles.push(b.i / dim);
  75494. // remove two nodes involved
  75495. removeNode(p);
  75496. removeNode(p.next);
  75497. p = start = b;
  75498. }
  75499. p = p.next;
  75500. } while (p !== start);
  75501. return p;
  75502. }
  75503. // try splitting polygon into two and triangulate them independently
  75504. function splitEarcut(start, triangles, dim, minX, minY, size) {
  75505. // look for a valid diagonal that divides the polygon into two
  75506. var a = start;
  75507. do {
  75508. var b = a.next.next;
  75509. while (b !== a.prev) {
  75510. if (a.i !== b.i && isValidDiagonal(a, b)) {
  75511. // split the polygon in two by the diagonal
  75512. var c = splitPolygon(a, b);
  75513. // filter colinear points around the cuts
  75514. a = filterPoints(a, a.next);
  75515. c = filterPoints(c, c.next);
  75516. // run earcut on each half
  75517. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  75518. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  75519. return;
  75520. }
  75521. b = b.next;
  75522. }
  75523. a = a.next;
  75524. } while (a !== start);
  75525. }
  75526. // link every hole into the outer loop, producing a single-ring polygon without holes
  75527. function eliminateHoles(data, holeIndices, outerNode, dim) {
  75528. var queue = [], i, len, start, end, list;
  75529. for (i = 0, len = holeIndices.length; i < len; i++) {
  75530. start = holeIndices[i] * dim;
  75531. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  75532. list = linkedList(data, start, end, dim, false);
  75533. if (list === list.next)
  75534. list.steiner = true;
  75535. queue.push(getLeftmost(list));
  75536. }
  75537. queue.sort(compareX);
  75538. // process holes from left to right
  75539. for (i = 0; i < queue.length; i++) {
  75540. eliminateHole(queue[i], outerNode);
  75541. outerNode = filterPoints(outerNode, outerNode.next);
  75542. }
  75543. return outerNode;
  75544. }
  75545. function compareX(a, b) {
  75546. return a.x - b.x;
  75547. }
  75548. // find a bridge between vertices that connects hole with an outer ring and and link it
  75549. function eliminateHole(hole, outerNode) {
  75550. outerNode = findHoleBridge(hole, outerNode);
  75551. if (outerNode) {
  75552. var b = splitPolygon(outerNode, hole);
  75553. filterPoints(b, b.next);
  75554. }
  75555. }
  75556. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  75557. function findHoleBridge(hole, outerNode) {
  75558. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  75559. // find a segment intersected by a ray from the hole's leftmost point to the left;
  75560. // segment's endpoint with lesser x will be potential connection point
  75561. do {
  75562. if (hy <= p.y && hy >= p.next.y) {
  75563. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  75564. if (x <= hx && x > qx) {
  75565. qx = x;
  75566. if (x === hx) {
  75567. if (hy === p.y)
  75568. return p;
  75569. if (hy === p.next.y)
  75570. return p.next;
  75571. }
  75572. m = p.x < p.next.x ? p : p.next;
  75573. }
  75574. }
  75575. p = p.next;
  75576. } while (p !== outerNode);
  75577. if (!m)
  75578. return null;
  75579. if (hx === qx)
  75580. return m.prev; // hole touches outer segment; pick lower endpoint
  75581. // look for points inside the triangle of hole point, segment intersection and endpoint;
  75582. // if there are no points found, we have a valid connection;
  75583. // otherwise choose the point of the minimum angle with the ray as connection point
  75584. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  75585. p = m.next;
  75586. while (p !== stop) {
  75587. if (hx >= p.x &&
  75588. p.x >= mx &&
  75589. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  75590. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  75591. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  75592. m = p;
  75593. tanMin = tan;
  75594. }
  75595. }
  75596. p = p.next;
  75597. }
  75598. return m;
  75599. }
  75600. // interlink polygon nodes in z-order
  75601. function indexCurve(start, minX, minY, size) {
  75602. var p = start;
  75603. do {
  75604. if (p.z === null)
  75605. p.z = zOrder(p.x, p.y, minX, minY, size);
  75606. p.prevZ = p.prev;
  75607. p.nextZ = p.next;
  75608. p = p.next;
  75609. } while (p !== start);
  75610. p.prevZ.nextZ = null;
  75611. p.prevZ = null;
  75612. sortLinked(p);
  75613. }
  75614. // Simon Tatham's linked list merge sort algorithm
  75615. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  75616. function sortLinked(list) {
  75617. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  75618. do {
  75619. p = list;
  75620. list = null;
  75621. tail = null;
  75622. numMerges = 0;
  75623. while (p) {
  75624. numMerges++;
  75625. q = p;
  75626. pSize = 0;
  75627. for (i = 0; i < inSize; i++) {
  75628. pSize++;
  75629. q = q.nextZ;
  75630. if (!q)
  75631. break;
  75632. }
  75633. qSize = inSize;
  75634. while (pSize > 0 || (qSize > 0 && q)) {
  75635. if (pSize === 0) {
  75636. e = q;
  75637. q = q.nextZ;
  75638. qSize--;
  75639. }
  75640. else if (qSize === 0 || !q) {
  75641. e = p;
  75642. p = p.nextZ;
  75643. pSize--;
  75644. }
  75645. else if (p.z <= q.z) {
  75646. e = p;
  75647. p = p.nextZ;
  75648. pSize--;
  75649. }
  75650. else {
  75651. e = q;
  75652. q = q.nextZ;
  75653. qSize--;
  75654. }
  75655. if (tail)
  75656. tail.nextZ = e;
  75657. else
  75658. list = e;
  75659. e.prevZ = tail;
  75660. tail = e;
  75661. }
  75662. p = q;
  75663. }
  75664. tail.nextZ = null;
  75665. inSize *= 2;
  75666. } while (numMerges > 1);
  75667. return list;
  75668. }
  75669. // z-order of a point given coords and size of the data bounding box
  75670. function zOrder(x, y, minX, minY, size) {
  75671. // coords are transformed into non-negative 15-bit integer range
  75672. x = 32767 * (x - minX) / size;
  75673. y = 32767 * (y - minY) / size;
  75674. x = (x | (x << 8)) & 0x00FF00FF;
  75675. x = (x | (x << 4)) & 0x0F0F0F0F;
  75676. x = (x | (x << 2)) & 0x33333333;
  75677. x = (x | (x << 1)) & 0x55555555;
  75678. y = (y | (y << 8)) & 0x00FF00FF;
  75679. y = (y | (y << 4)) & 0x0F0F0F0F;
  75680. y = (y | (y << 2)) & 0x33333333;
  75681. y = (y | (y << 1)) & 0x55555555;
  75682. return x | (y << 1);
  75683. }
  75684. // find the leftmost node of a polygon ring
  75685. function getLeftmost(start) {
  75686. var p = start, leftmost = start;
  75687. do {
  75688. if (p.x < leftmost.x)
  75689. leftmost = p;
  75690. p = p.next;
  75691. } while (p !== start);
  75692. return leftmost;
  75693. }
  75694. // check if a point lies within a convex triangle
  75695. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  75696. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  75697. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  75698. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  75699. }
  75700. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  75701. function isValidDiagonal(a, b) {
  75702. return a.next.i !== b.i &&
  75703. a.prev.i !== b.i &&
  75704. !intersectsPolygon(a, b) &&
  75705. locallyInside(a, b) &&
  75706. locallyInside(b, a) &&
  75707. middleInside(a, b);
  75708. }
  75709. // signed area of a triangle
  75710. function area(p, q, r) {
  75711. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  75712. }
  75713. // check if two points are equal
  75714. function equals(p1, p2) {
  75715. return p1.x === p2.x && p1.y === p2.y;
  75716. }
  75717. // check if two segments intersect
  75718. function intersects(p1, q1, p2, q2) {
  75719. if ((equals(p1, q1) && equals(p2, q2)) ||
  75720. (equals(p1, q2) && equals(p2, q1)))
  75721. return true;
  75722. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  75723. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  75724. }
  75725. // check if a polygon diagonal intersects any polygon segments
  75726. function intersectsPolygon(a, b) {
  75727. var p = a;
  75728. do {
  75729. if (p.i !== a.i &&
  75730. p.next.i !== a.i &&
  75731. p.i !== b.i &&
  75732. p.next.i !== b.i &&
  75733. intersects(p, p.next, a, b))
  75734. return true;
  75735. p = p.next;
  75736. } while (p !== a);
  75737. return false;
  75738. }
  75739. // check if a polygon diagonal is locally inside the polygon
  75740. function locallyInside(a, b) {
  75741. return area(a.prev, a, a.next) < 0
  75742. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  75743. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  75744. }
  75745. // check if the middle point of a polygon diagonal is inside the polygon
  75746. function middleInside(a, b) {
  75747. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  75748. do {
  75749. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  75750. inside = !inside;
  75751. p = p.next;
  75752. } while (p !== a);
  75753. return inside;
  75754. }
  75755. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  75756. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  75757. function splitPolygon(a, b) {
  75758. 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;
  75759. a.next = b;
  75760. b.prev = a;
  75761. a2.next = an;
  75762. an.prev = a2;
  75763. b2.next = a2;
  75764. a2.prev = b2;
  75765. bp.next = b2;
  75766. b2.prev = bp;
  75767. return b2;
  75768. }
  75769. // create a node and optionally link it with previous one (in a circular doubly linked list)
  75770. function insertNode(i, x, y, last) {
  75771. var p = new Node(i, x, y);
  75772. if (!last) {
  75773. p.prev = p;
  75774. p.next = p;
  75775. }
  75776. else {
  75777. p.next = last.next;
  75778. p.prev = last;
  75779. last.next.prev = p;
  75780. last.next = p;
  75781. }
  75782. return p;
  75783. }
  75784. function removeNode(p) {
  75785. p.next.prev = p.prev;
  75786. p.prev.next = p.next;
  75787. if (p.prevZ)
  75788. p.prevZ.nextZ = p.nextZ;
  75789. if (p.nextZ)
  75790. p.nextZ.prevZ = p.prevZ;
  75791. }
  75792. /**
  75793. * return a percentage difference between the polygon area and its triangulation area;
  75794. * used to verify correctness of triangulation
  75795. */
  75796. function deviation(data, holeIndices, dim, triangles) {
  75797. var hasHoles = holeIndices && holeIndices.length;
  75798. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  75799. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  75800. if (hasHoles) {
  75801. for (var i = 0, len = holeIndices.length; i < len; i++) {
  75802. var start = holeIndices[i] * dim;
  75803. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  75804. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  75805. }
  75806. }
  75807. var trianglesArea = 0;
  75808. for (i = 0; i < triangles.length; i += 3) {
  75809. var a = triangles[i] * dim;
  75810. var b = triangles[i + 1] * dim;
  75811. var c = triangles[i + 2] * dim;
  75812. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  75813. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  75814. }
  75815. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  75816. }
  75817. Earcut.deviation = deviation;
  75818. ;
  75819. function signedArea(data, start, end, dim) {
  75820. var sum = 0;
  75821. for (var i = start, j = end - dim; i < end; i += dim) {
  75822. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  75823. j = i;
  75824. }
  75825. return sum;
  75826. }
  75827. /**
  75828. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  75829. */
  75830. function flatten(data) {
  75831. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  75832. for (var i = 0; i < data.length; i++) {
  75833. for (var j = 0; j < data[i].length; j++) {
  75834. for (var d = 0; d < dim; d++)
  75835. result.vertices.push(data[i][j][d]);
  75836. }
  75837. if (i > 0) {
  75838. holeIndex += data[i - 1].length;
  75839. result.holes.push(holeIndex);
  75840. }
  75841. }
  75842. return result;
  75843. }
  75844. Earcut.flatten = flatten;
  75845. ;
  75846. })(Earcut || (Earcut = {}));
  75847. //# sourceMappingURL=babylon.earcut.js.map
  75848. "use strict";
  75849. var BABYLON;
  75850. (function (BABYLON) {
  75851. var IndexedVector2 = /** @class */ (function (_super) {
  75852. __extends(IndexedVector2, _super);
  75853. function IndexedVector2(original, index) {
  75854. var _this = _super.call(this, original.x, original.y) || this;
  75855. _this.index = index;
  75856. return _this;
  75857. }
  75858. return IndexedVector2;
  75859. }(BABYLON.Vector2));
  75860. var PolygonPoints = /** @class */ (function () {
  75861. function PolygonPoints() {
  75862. this.elements = new Array();
  75863. }
  75864. PolygonPoints.prototype.add = function (originalPoints) {
  75865. var _this = this;
  75866. var result = new Array();
  75867. originalPoints.forEach(function (point) {
  75868. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  75869. var newPoint = new IndexedVector2(point, _this.elements.length);
  75870. result.push(newPoint);
  75871. _this.elements.push(newPoint);
  75872. }
  75873. });
  75874. return result;
  75875. };
  75876. PolygonPoints.prototype.computeBounds = function () {
  75877. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  75878. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  75879. this.elements.forEach(function (point) {
  75880. // x
  75881. if (point.x < lmin.x) {
  75882. lmin.x = point.x;
  75883. }
  75884. else if (point.x > lmax.x) {
  75885. lmax.x = point.x;
  75886. }
  75887. // y
  75888. if (point.y < lmin.y) {
  75889. lmin.y = point.y;
  75890. }
  75891. else if (point.y > lmax.y) {
  75892. lmax.y = point.y;
  75893. }
  75894. });
  75895. return {
  75896. min: lmin,
  75897. max: lmax,
  75898. width: lmax.x - lmin.x,
  75899. height: lmax.y - lmin.y
  75900. };
  75901. };
  75902. return PolygonPoints;
  75903. }());
  75904. var Polygon = /** @class */ (function () {
  75905. function Polygon() {
  75906. }
  75907. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  75908. return [
  75909. new BABYLON.Vector2(xmin, ymin),
  75910. new BABYLON.Vector2(xmax, ymin),
  75911. new BABYLON.Vector2(xmax, ymax),
  75912. new BABYLON.Vector2(xmin, ymax)
  75913. ];
  75914. };
  75915. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  75916. if (cx === void 0) { cx = 0; }
  75917. if (cy === void 0) { cy = 0; }
  75918. if (numberOfSides === void 0) { numberOfSides = 32; }
  75919. var result = new Array();
  75920. var angle = 0;
  75921. var increment = (Math.PI * 2) / numberOfSides;
  75922. for (var i = 0; i < numberOfSides; i++) {
  75923. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  75924. angle -= increment;
  75925. }
  75926. return result;
  75927. };
  75928. Polygon.Parse = function (input) {
  75929. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  75930. var i, result = [];
  75931. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  75932. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  75933. }
  75934. return result;
  75935. };
  75936. Polygon.StartingAt = function (x, y) {
  75937. return BABYLON.Path2.StartingAt(x, y);
  75938. };
  75939. return Polygon;
  75940. }());
  75941. BABYLON.Polygon = Polygon;
  75942. var PolygonMeshBuilder = /** @class */ (function () {
  75943. function PolygonMeshBuilder(name, contours, scene) {
  75944. this._points = new PolygonPoints();
  75945. this._outlinepoints = new PolygonPoints();
  75946. this._holes = new Array();
  75947. this._epoints = new Array();
  75948. this._eholes = new Array();
  75949. this._name = name;
  75950. this._scene = scene;
  75951. var points;
  75952. if (contours instanceof BABYLON.Path2) {
  75953. points = contours.getPoints();
  75954. }
  75955. else {
  75956. points = contours;
  75957. }
  75958. this._addToepoint(points);
  75959. this._points.add(points);
  75960. this._outlinepoints.add(points);
  75961. }
  75962. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  75963. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  75964. var p = points_1[_i];
  75965. this._epoints.push(p.x, p.y);
  75966. }
  75967. };
  75968. PolygonMeshBuilder.prototype.addHole = function (hole) {
  75969. this._points.add(hole);
  75970. var holepoints = new PolygonPoints();
  75971. holepoints.add(hole);
  75972. this._holes.push(holepoints);
  75973. this._eholes.push(this._epoints.length / 2);
  75974. this._addToepoint(hole);
  75975. return this;
  75976. };
  75977. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  75978. var _this = this;
  75979. if (updatable === void 0) { updatable = false; }
  75980. if (depth === void 0) { depth = 0; }
  75981. var result = new BABYLON.Mesh(this._name, this._scene);
  75982. var normals = new Array();
  75983. var positions = new Array();
  75984. var uvs = new Array();
  75985. var bounds = this._points.computeBounds();
  75986. this._points.elements.forEach(function (p) {
  75987. normals.push(0, 1.0, 0);
  75988. positions.push(p.x, 0, p.y);
  75989. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  75990. });
  75991. var indices = new Array();
  75992. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  75993. for (var i = 0; i < res.length; i++) {
  75994. indices.push(res[i]);
  75995. }
  75996. if (depth > 0) {
  75997. var positionscount = (positions.length / 3); //get the current pointcount
  75998. this._points.elements.forEach(function (p) {
  75999. normals.push(0, -1.0, 0);
  76000. positions.push(p.x, -depth, p.y);
  76001. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  76002. });
  76003. var totalCount = indices.length;
  76004. for (var i = 0; i < totalCount; i += 3) {
  76005. var i0 = indices[i + 0];
  76006. var i1 = indices[i + 1];
  76007. var i2 = indices[i + 2];
  76008. indices.push(i2 + positionscount);
  76009. indices.push(i1 + positionscount);
  76010. indices.push(i0 + positionscount);
  76011. }
  76012. //Add the sides
  76013. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  76014. this._holes.forEach(function (hole) {
  76015. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  76016. });
  76017. }
  76018. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  76019. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  76020. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  76021. result.setIndices(indices);
  76022. return result;
  76023. };
  76024. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  76025. var StartIndex = positions.length / 3;
  76026. var ulength = 0;
  76027. for (var i = 0; i < points.elements.length; i++) {
  76028. var p = points.elements[i];
  76029. var p1;
  76030. if ((i + 1) > points.elements.length - 1) {
  76031. p1 = points.elements[0];
  76032. }
  76033. else {
  76034. p1 = points.elements[i + 1];
  76035. }
  76036. positions.push(p.x, 0, p.y);
  76037. positions.push(p.x, -depth, p.y);
  76038. positions.push(p1.x, 0, p1.y);
  76039. positions.push(p1.x, -depth, p1.y);
  76040. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  76041. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  76042. var v3 = v2.subtract(v1);
  76043. var v4 = new BABYLON.Vector3(0, 1, 0);
  76044. var vn = BABYLON.Vector3.Cross(v3, v4);
  76045. vn = vn.normalize();
  76046. uvs.push(ulength / bounds.width, 0);
  76047. uvs.push(ulength / bounds.width, 1);
  76048. ulength += v3.length();
  76049. uvs.push((ulength / bounds.width), 0);
  76050. uvs.push((ulength / bounds.width), 1);
  76051. if (!flip) {
  76052. normals.push(-vn.x, -vn.y, -vn.z);
  76053. normals.push(-vn.x, -vn.y, -vn.z);
  76054. normals.push(-vn.x, -vn.y, -vn.z);
  76055. normals.push(-vn.x, -vn.y, -vn.z);
  76056. indices.push(StartIndex);
  76057. indices.push(StartIndex + 1);
  76058. indices.push(StartIndex + 2);
  76059. indices.push(StartIndex + 1);
  76060. indices.push(StartIndex + 3);
  76061. indices.push(StartIndex + 2);
  76062. }
  76063. else {
  76064. normals.push(vn.x, vn.y, vn.z);
  76065. normals.push(vn.x, vn.y, vn.z);
  76066. normals.push(vn.x, vn.y, vn.z);
  76067. normals.push(vn.x, vn.y, vn.z);
  76068. indices.push(StartIndex);
  76069. indices.push(StartIndex + 2);
  76070. indices.push(StartIndex + 1);
  76071. indices.push(StartIndex + 1);
  76072. indices.push(StartIndex + 2);
  76073. indices.push(StartIndex + 3);
  76074. }
  76075. StartIndex += 4;
  76076. }
  76077. ;
  76078. };
  76079. return PolygonMeshBuilder;
  76080. }());
  76081. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  76082. })(BABYLON || (BABYLON = {}));
  76083. //# sourceMappingURL=babylon.polygonMesh.js.map
  76084. "use strict";
  76085. var BABYLON;
  76086. (function (BABYLON) {
  76087. // Unique ID when we import meshes from Babylon to CSG
  76088. var currentCSGMeshId = 0;
  76089. // # class Vertex
  76090. // Represents a vertex of a polygon. Use your own vertex class instead of this
  76091. // one to provide additional features like texture coordinates and vertex
  76092. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  76093. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  76094. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  76095. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  76096. // is not used anywhere else.
  76097. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  76098. var Vertex = /** @class */ (function () {
  76099. function Vertex(pos, normal, uv) {
  76100. this.pos = pos;
  76101. this.normal = normal;
  76102. this.uv = uv;
  76103. }
  76104. Vertex.prototype.clone = function () {
  76105. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  76106. };
  76107. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  76108. // orientation of a polygon is flipped.
  76109. Vertex.prototype.flip = function () {
  76110. this.normal = this.normal.scale(-1);
  76111. };
  76112. // Create a new vertex between this vertex and `other` by linearly
  76113. // interpolating all properties using a parameter of `t`. Subclasses should
  76114. // override this to interpolate additional properties.
  76115. Vertex.prototype.interpolate = function (other, t) {
  76116. 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));
  76117. };
  76118. return Vertex;
  76119. }());
  76120. // # class Plane
  76121. // Represents a plane in 3D space.
  76122. var Plane = /** @class */ (function () {
  76123. function Plane(normal, w) {
  76124. this.normal = normal;
  76125. this.w = w;
  76126. }
  76127. Plane.FromPoints = function (a, b, c) {
  76128. var v0 = c.subtract(a);
  76129. var v1 = b.subtract(a);
  76130. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  76131. return null;
  76132. }
  76133. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  76134. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  76135. };
  76136. Plane.prototype.clone = function () {
  76137. return new Plane(this.normal.clone(), this.w);
  76138. };
  76139. Plane.prototype.flip = function () {
  76140. this.normal.scaleInPlace(-1);
  76141. this.w = -this.w;
  76142. };
  76143. // Split `polygon` by this plane if needed, then put the polygon or polygon
  76144. // fragments in the appropriate lists. Coplanar polygons go into either
  76145. // `coplanarFront` or `coplanarBack` depending on their orientation with
  76146. // respect to this plane. Polygons in front or in back of this plane go into
  76147. // either `front` or `back`.
  76148. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  76149. var COPLANAR = 0;
  76150. var FRONT = 1;
  76151. var BACK = 2;
  76152. var SPANNING = 3;
  76153. // Classify each point as well as the entire polygon into one of the above
  76154. // four classes.
  76155. var polygonType = 0;
  76156. var types = [];
  76157. var i;
  76158. var t;
  76159. for (i = 0; i < polygon.vertices.length; i++) {
  76160. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  76161. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  76162. polygonType |= type;
  76163. types.push(type);
  76164. }
  76165. // Put the polygon in the correct list, splitting it when necessary.
  76166. switch (polygonType) {
  76167. case COPLANAR:
  76168. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  76169. break;
  76170. case FRONT:
  76171. front.push(polygon);
  76172. break;
  76173. case BACK:
  76174. back.push(polygon);
  76175. break;
  76176. case SPANNING:
  76177. var f = [], b = [];
  76178. for (i = 0; i < polygon.vertices.length; i++) {
  76179. var j = (i + 1) % polygon.vertices.length;
  76180. var ti = types[i], tj = types[j];
  76181. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  76182. if (ti !== BACK)
  76183. f.push(vi);
  76184. if (ti !== FRONT)
  76185. b.push(ti !== BACK ? vi.clone() : vi);
  76186. if ((ti | tj) === SPANNING) {
  76187. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  76188. var v = vi.interpolate(vj, t);
  76189. f.push(v);
  76190. b.push(v.clone());
  76191. }
  76192. }
  76193. var poly;
  76194. if (f.length >= 3) {
  76195. poly = new Polygon(f, polygon.shared);
  76196. if (poly.plane)
  76197. front.push(poly);
  76198. }
  76199. if (b.length >= 3) {
  76200. poly = new Polygon(b, polygon.shared);
  76201. if (poly.plane)
  76202. back.push(poly);
  76203. }
  76204. break;
  76205. }
  76206. };
  76207. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  76208. // point is on the plane.
  76209. Plane.EPSILON = 1e-5;
  76210. return Plane;
  76211. }());
  76212. // # class Polygon
  76213. // Represents a convex polygon. The vertices used to initialize a polygon must
  76214. // be coplanar and form a convex loop.
  76215. //
  76216. // Each convex polygon has a `shared` property, which is shared between all
  76217. // polygons that are clones of each other or were split from the same polygon.
  76218. // This can be used to define per-polygon properties (such as surface color).
  76219. var Polygon = /** @class */ (function () {
  76220. function Polygon(vertices, shared) {
  76221. this.vertices = vertices;
  76222. this.shared = shared;
  76223. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  76224. }
  76225. Polygon.prototype.clone = function () {
  76226. var vertices = this.vertices.map(function (v) { return v.clone(); });
  76227. return new Polygon(vertices, this.shared);
  76228. };
  76229. Polygon.prototype.flip = function () {
  76230. this.vertices.reverse().map(function (v) { v.flip(); });
  76231. this.plane.flip();
  76232. };
  76233. return Polygon;
  76234. }());
  76235. // # class Node
  76236. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  76237. // by picking a polygon to split along. That polygon (and all other coplanar
  76238. // polygons) are added directly to that node and the other polygons are added to
  76239. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  76240. // no distinction between internal and leaf nodes.
  76241. var Node = /** @class */ (function () {
  76242. function Node(polygons) {
  76243. this.plane = null;
  76244. this.front = null;
  76245. this.back = null;
  76246. this.polygons = new Array();
  76247. if (polygons) {
  76248. this.build(polygons);
  76249. }
  76250. }
  76251. Node.prototype.clone = function () {
  76252. var node = new Node();
  76253. node.plane = this.plane && this.plane.clone();
  76254. node.front = this.front && this.front.clone();
  76255. node.back = this.back && this.back.clone();
  76256. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  76257. return node;
  76258. };
  76259. // Convert solid space to empty space and empty space to solid space.
  76260. Node.prototype.invert = function () {
  76261. for (var i = 0; i < this.polygons.length; i++) {
  76262. this.polygons[i].flip();
  76263. }
  76264. if (this.plane) {
  76265. this.plane.flip();
  76266. }
  76267. if (this.front) {
  76268. this.front.invert();
  76269. }
  76270. if (this.back) {
  76271. this.back.invert();
  76272. }
  76273. var temp = this.front;
  76274. this.front = this.back;
  76275. this.back = temp;
  76276. };
  76277. // Recursively remove all polygons in `polygons` that are inside this BSP
  76278. // tree.
  76279. Node.prototype.clipPolygons = function (polygons) {
  76280. if (!this.plane)
  76281. return polygons.slice();
  76282. var front = new Array(), back = new Array();
  76283. for (var i = 0; i < polygons.length; i++) {
  76284. this.plane.splitPolygon(polygons[i], front, back, front, back);
  76285. }
  76286. if (this.front) {
  76287. front = this.front.clipPolygons(front);
  76288. }
  76289. if (this.back) {
  76290. back = this.back.clipPolygons(back);
  76291. }
  76292. else {
  76293. back = [];
  76294. }
  76295. return front.concat(back);
  76296. };
  76297. // Remove all polygons in this BSP tree that are inside the other BSP tree
  76298. // `bsp`.
  76299. Node.prototype.clipTo = function (bsp) {
  76300. this.polygons = bsp.clipPolygons(this.polygons);
  76301. if (this.front)
  76302. this.front.clipTo(bsp);
  76303. if (this.back)
  76304. this.back.clipTo(bsp);
  76305. };
  76306. // Return a list of all polygons in this BSP tree.
  76307. Node.prototype.allPolygons = function () {
  76308. var polygons = this.polygons.slice();
  76309. if (this.front)
  76310. polygons = polygons.concat(this.front.allPolygons());
  76311. if (this.back)
  76312. polygons = polygons.concat(this.back.allPolygons());
  76313. return polygons;
  76314. };
  76315. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  76316. // new polygons are filtered down to the bottom of the tree and become new
  76317. // nodes there. Each set of polygons is partitioned using the first polygon
  76318. // (no heuristic is used to pick a good split).
  76319. Node.prototype.build = function (polygons) {
  76320. if (!polygons.length)
  76321. return;
  76322. if (!this.plane)
  76323. this.plane = polygons[0].plane.clone();
  76324. var front = new Array(), back = new Array();
  76325. for (var i = 0; i < polygons.length; i++) {
  76326. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  76327. }
  76328. if (front.length) {
  76329. if (!this.front)
  76330. this.front = new Node();
  76331. this.front.build(front);
  76332. }
  76333. if (back.length) {
  76334. if (!this.back)
  76335. this.back = new Node();
  76336. this.back.build(back);
  76337. }
  76338. };
  76339. return Node;
  76340. }());
  76341. var CSG = /** @class */ (function () {
  76342. function CSG() {
  76343. this.polygons = new Array();
  76344. }
  76345. // Convert BABYLON.Mesh to BABYLON.CSG
  76346. CSG.FromMesh = function (mesh) {
  76347. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  76348. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  76349. if (mesh instanceof BABYLON.Mesh) {
  76350. mesh.computeWorldMatrix(true);
  76351. matrix = mesh.getWorldMatrix();
  76352. meshPosition = mesh.position.clone();
  76353. meshRotation = mesh.rotation.clone();
  76354. if (mesh.rotationQuaternion) {
  76355. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  76356. }
  76357. meshScaling = mesh.scaling.clone();
  76358. }
  76359. else {
  76360. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  76361. }
  76362. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  76363. var subMeshes = mesh.subMeshes;
  76364. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  76365. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  76366. vertices = [];
  76367. for (var j = 0; j < 3; j++) {
  76368. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  76369. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  76370. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  76371. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  76372. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  76373. vertex = new Vertex(position, normal, uv);
  76374. vertices.push(vertex);
  76375. }
  76376. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  76377. // To handle the case of degenerated triangle
  76378. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  76379. if (polygon.plane)
  76380. polygons.push(polygon);
  76381. }
  76382. }
  76383. var csg = CSG.FromPolygons(polygons);
  76384. csg.matrix = matrix;
  76385. csg.position = meshPosition;
  76386. csg.rotation = meshRotation;
  76387. csg.scaling = meshScaling;
  76388. csg.rotationQuaternion = meshRotationQuaternion;
  76389. currentCSGMeshId++;
  76390. return csg;
  76391. };
  76392. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  76393. CSG.FromPolygons = function (polygons) {
  76394. var csg = new CSG();
  76395. csg.polygons = polygons;
  76396. return csg;
  76397. };
  76398. CSG.prototype.clone = function () {
  76399. var csg = new CSG();
  76400. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  76401. csg.copyTransformAttributes(this);
  76402. return csg;
  76403. };
  76404. CSG.prototype.union = function (csg) {
  76405. var a = new Node(this.clone().polygons);
  76406. var b = new Node(csg.clone().polygons);
  76407. a.clipTo(b);
  76408. b.clipTo(a);
  76409. b.invert();
  76410. b.clipTo(a);
  76411. b.invert();
  76412. a.build(b.allPolygons());
  76413. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76414. };
  76415. CSG.prototype.unionInPlace = function (csg) {
  76416. var a = new Node(this.polygons);
  76417. var b = new Node(csg.polygons);
  76418. a.clipTo(b);
  76419. b.clipTo(a);
  76420. b.invert();
  76421. b.clipTo(a);
  76422. b.invert();
  76423. a.build(b.allPolygons());
  76424. this.polygons = a.allPolygons();
  76425. };
  76426. CSG.prototype.subtract = function (csg) {
  76427. var a = new Node(this.clone().polygons);
  76428. var b = new Node(csg.clone().polygons);
  76429. a.invert();
  76430. a.clipTo(b);
  76431. b.clipTo(a);
  76432. b.invert();
  76433. b.clipTo(a);
  76434. b.invert();
  76435. a.build(b.allPolygons());
  76436. a.invert();
  76437. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76438. };
  76439. CSG.prototype.subtractInPlace = function (csg) {
  76440. var a = new Node(this.polygons);
  76441. var b = new Node(csg.polygons);
  76442. a.invert();
  76443. a.clipTo(b);
  76444. b.clipTo(a);
  76445. b.invert();
  76446. b.clipTo(a);
  76447. b.invert();
  76448. a.build(b.allPolygons());
  76449. a.invert();
  76450. this.polygons = a.allPolygons();
  76451. };
  76452. CSG.prototype.intersect = function (csg) {
  76453. var a = new Node(this.clone().polygons);
  76454. var b = new Node(csg.clone().polygons);
  76455. a.invert();
  76456. b.clipTo(a);
  76457. b.invert();
  76458. a.clipTo(b);
  76459. b.clipTo(a);
  76460. a.build(b.allPolygons());
  76461. a.invert();
  76462. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76463. };
  76464. CSG.prototype.intersectInPlace = function (csg) {
  76465. var a = new Node(this.polygons);
  76466. var b = new Node(csg.polygons);
  76467. a.invert();
  76468. b.clipTo(a);
  76469. b.invert();
  76470. a.clipTo(b);
  76471. b.clipTo(a);
  76472. a.build(b.allPolygons());
  76473. a.invert();
  76474. this.polygons = a.allPolygons();
  76475. };
  76476. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  76477. // not modified.
  76478. CSG.prototype.inverse = function () {
  76479. var csg = this.clone();
  76480. csg.inverseInPlace();
  76481. return csg;
  76482. };
  76483. CSG.prototype.inverseInPlace = function () {
  76484. this.polygons.map(function (p) { p.flip(); });
  76485. };
  76486. // This is used to keep meshes transformations so they can be restored
  76487. // when we build back a Babylon Mesh
  76488. // NB : All CSG operations are performed in world coordinates
  76489. CSG.prototype.copyTransformAttributes = function (csg) {
  76490. this.matrix = csg.matrix;
  76491. this.position = csg.position;
  76492. this.rotation = csg.rotation;
  76493. this.scaling = csg.scaling;
  76494. this.rotationQuaternion = csg.rotationQuaternion;
  76495. return this;
  76496. };
  76497. // Build Raw mesh from CSG
  76498. // Coordinates here are in world space
  76499. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  76500. var matrix = this.matrix.clone();
  76501. matrix.invert();
  76502. 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;
  76503. if (keepSubMeshes) {
  76504. // Sort Polygons, since subMeshes are indices range
  76505. polygons.sort(function (a, b) {
  76506. if (a.shared.meshId === b.shared.meshId) {
  76507. return a.shared.subMeshId - b.shared.subMeshId;
  76508. }
  76509. else {
  76510. return a.shared.meshId - b.shared.meshId;
  76511. }
  76512. });
  76513. }
  76514. for (var i = 0, il = polygons.length; i < il; i++) {
  76515. polygon = polygons[i];
  76516. // Building SubMeshes
  76517. if (!subMesh_dict[polygon.shared.meshId]) {
  76518. subMesh_dict[polygon.shared.meshId] = {};
  76519. }
  76520. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  76521. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  76522. indexStart: +Infinity,
  76523. indexEnd: -Infinity,
  76524. materialIndex: polygon.shared.materialIndex
  76525. };
  76526. }
  76527. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  76528. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  76529. polygonIndices[0] = 0;
  76530. polygonIndices[1] = j - 1;
  76531. polygonIndices[2] = j;
  76532. for (var k = 0; k < 3; k++) {
  76533. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  76534. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  76535. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  76536. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  76537. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  76538. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  76539. // Check if 2 points can be merged
  76540. if (!(typeof vertex_idx !== 'undefined' &&
  76541. normals[vertex_idx * 3] === localNormal.x &&
  76542. normals[vertex_idx * 3 + 1] === localNormal.y &&
  76543. normals[vertex_idx * 3 + 2] === localNormal.z &&
  76544. uvs[vertex_idx * 2] === uv.x &&
  76545. uvs[vertex_idx * 2 + 1] === uv.y)) {
  76546. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  76547. uvs.push(uv.x, uv.y);
  76548. normals.push(normal.x, normal.y, normal.z);
  76549. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  76550. }
  76551. indices.push(vertex_idx);
  76552. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  76553. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  76554. currentIndex++;
  76555. }
  76556. }
  76557. }
  76558. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  76559. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  76560. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  76561. mesh.setIndices(indices, null);
  76562. if (keepSubMeshes) {
  76563. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  76564. var materialIndexOffset = 0, materialMaxIndex;
  76565. mesh.subMeshes = new Array();
  76566. for (var m in subMesh_dict) {
  76567. materialMaxIndex = -1;
  76568. for (var sm in subMesh_dict[m]) {
  76569. subMesh_obj = subMesh_dict[m][sm];
  76570. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  76571. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  76572. }
  76573. materialIndexOffset += ++materialMaxIndex;
  76574. }
  76575. }
  76576. return mesh;
  76577. };
  76578. // Build Mesh from CSG taking material and transforms into account
  76579. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  76580. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  76581. mesh.material = material;
  76582. mesh.position.copyFrom(this.position);
  76583. mesh.rotation.copyFrom(this.rotation);
  76584. if (this.rotationQuaternion) {
  76585. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  76586. }
  76587. mesh.scaling.copyFrom(this.scaling);
  76588. mesh.computeWorldMatrix(true);
  76589. return mesh;
  76590. };
  76591. return CSG;
  76592. }());
  76593. BABYLON.CSG = CSG;
  76594. })(BABYLON || (BABYLON = {}));
  76595. //# sourceMappingURL=babylon.csg.js.map
  76596. "use strict";
  76597. var BABYLON;
  76598. (function (BABYLON) {
  76599. var LensFlare = /** @class */ (function () {
  76600. function LensFlare(size, position, color, imgUrl, system) {
  76601. this.size = size;
  76602. this.position = position;
  76603. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  76604. this.color = color || new BABYLON.Color3(1, 1, 1);
  76605. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  76606. this._system = system;
  76607. system.lensFlares.push(this);
  76608. }
  76609. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  76610. return new LensFlare(size, position, color, imgUrl, system);
  76611. };
  76612. LensFlare.prototype.dispose = function () {
  76613. if (this.texture) {
  76614. this.texture.dispose();
  76615. }
  76616. // Remove from scene
  76617. var index = this._system.lensFlares.indexOf(this);
  76618. this._system.lensFlares.splice(index, 1);
  76619. };
  76620. ;
  76621. return LensFlare;
  76622. }());
  76623. BABYLON.LensFlare = LensFlare;
  76624. })(BABYLON || (BABYLON = {}));
  76625. //# sourceMappingURL=babylon.lensFlare.js.map
  76626. "use strict";
  76627. var BABYLON;
  76628. (function (BABYLON) {
  76629. var LensFlareSystem = /** @class */ (function () {
  76630. function LensFlareSystem(name, emitter, scene) {
  76631. this.name = name;
  76632. this.lensFlares = new Array();
  76633. this.borderLimit = 300;
  76634. this.viewportBorder = 0;
  76635. this.layerMask = 0x0FFFFFFF;
  76636. this._vertexBuffers = {};
  76637. this._isEnabled = true;
  76638. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76639. this._emitter = emitter;
  76640. this.id = name;
  76641. scene.lensFlareSystems.push(this);
  76642. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  76643. var engine = scene.getEngine();
  76644. // VBO
  76645. var vertices = [];
  76646. vertices.push(1, 1);
  76647. vertices.push(-1, 1);
  76648. vertices.push(-1, -1);
  76649. vertices.push(1, -1);
  76650. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76651. // Indices
  76652. var indices = [];
  76653. indices.push(0);
  76654. indices.push(1);
  76655. indices.push(2);
  76656. indices.push(0);
  76657. indices.push(2);
  76658. indices.push(3);
  76659. this._indexBuffer = engine.createIndexBuffer(indices);
  76660. // Effects
  76661. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  76662. }
  76663. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  76664. get: function () {
  76665. return this._isEnabled;
  76666. },
  76667. set: function (value) {
  76668. this._isEnabled = value;
  76669. },
  76670. enumerable: true,
  76671. configurable: true
  76672. });
  76673. LensFlareSystem.prototype.getScene = function () {
  76674. return this._scene;
  76675. };
  76676. LensFlareSystem.prototype.getEmitter = function () {
  76677. return this._emitter;
  76678. };
  76679. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  76680. this._emitter = newEmitter;
  76681. };
  76682. LensFlareSystem.prototype.getEmitterPosition = function () {
  76683. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  76684. };
  76685. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  76686. var position = this.getEmitterPosition();
  76687. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  76688. this._positionX = position.x;
  76689. this._positionY = position.y;
  76690. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  76691. if (this.viewportBorder > 0) {
  76692. globalViewport.x -= this.viewportBorder;
  76693. globalViewport.y -= this.viewportBorder;
  76694. globalViewport.width += this.viewportBorder * 2;
  76695. globalViewport.height += this.viewportBorder * 2;
  76696. position.x += this.viewportBorder;
  76697. position.y += this.viewportBorder;
  76698. this._positionX += this.viewportBorder;
  76699. this._positionY += this.viewportBorder;
  76700. }
  76701. if (position.z > 0) {
  76702. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  76703. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  76704. return true;
  76705. }
  76706. return true;
  76707. }
  76708. return false;
  76709. };
  76710. LensFlareSystem.prototype._isVisible = function () {
  76711. if (!this._isEnabled || !this._scene.activeCamera) {
  76712. return false;
  76713. }
  76714. var emitterPosition = this.getEmitterPosition();
  76715. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  76716. var distance = direction.length();
  76717. direction.normalize();
  76718. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  76719. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  76720. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  76721. };
  76722. LensFlareSystem.prototype.render = function () {
  76723. if (!this._effect.isReady() || !this._scene.activeCamera)
  76724. return false;
  76725. var engine = this._scene.getEngine();
  76726. var viewport = this._scene.activeCamera.viewport;
  76727. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  76728. // Position
  76729. if (!this.computeEffectivePosition(globalViewport)) {
  76730. return false;
  76731. }
  76732. // Visibility
  76733. if (!this._isVisible()) {
  76734. return false;
  76735. }
  76736. // Intensity
  76737. var awayX;
  76738. var awayY;
  76739. if (this._positionX < this.borderLimit + globalViewport.x) {
  76740. awayX = this.borderLimit + globalViewport.x - this._positionX;
  76741. }
  76742. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  76743. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  76744. }
  76745. else {
  76746. awayX = 0;
  76747. }
  76748. if (this._positionY < this.borderLimit + globalViewport.y) {
  76749. awayY = this.borderLimit + globalViewport.y - this._positionY;
  76750. }
  76751. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  76752. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  76753. }
  76754. else {
  76755. awayY = 0;
  76756. }
  76757. var away = (awayX > awayY) ? awayX : awayY;
  76758. away -= this.viewportBorder;
  76759. if (away > this.borderLimit) {
  76760. away = this.borderLimit;
  76761. }
  76762. var intensity = 1.0 - (away / this.borderLimit);
  76763. if (intensity < 0) {
  76764. return false;
  76765. }
  76766. if (intensity > 1.0) {
  76767. intensity = 1.0;
  76768. }
  76769. if (this.viewportBorder > 0) {
  76770. globalViewport.x += this.viewportBorder;
  76771. globalViewport.y += this.viewportBorder;
  76772. globalViewport.width -= this.viewportBorder * 2;
  76773. globalViewport.height -= this.viewportBorder * 2;
  76774. this._positionX -= this.viewportBorder;
  76775. this._positionY -= this.viewportBorder;
  76776. }
  76777. // Position
  76778. var centerX = globalViewport.x + globalViewport.width / 2;
  76779. var centerY = globalViewport.y + globalViewport.height / 2;
  76780. var distX = centerX - this._positionX;
  76781. var distY = centerY - this._positionY;
  76782. // Effects
  76783. engine.enableEffect(this._effect);
  76784. engine.setState(false);
  76785. engine.setDepthBuffer(false);
  76786. // VBOs
  76787. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  76788. // Flares
  76789. for (var index = 0; index < this.lensFlares.length; index++) {
  76790. var flare = this.lensFlares[index];
  76791. engine.setAlphaMode(flare.alphaMode);
  76792. var x = centerX - (distX * flare.position);
  76793. var y = centerY - (distY * flare.position);
  76794. var cw = flare.size;
  76795. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  76796. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  76797. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  76798. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  76799. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  76800. // Texture
  76801. this._effect.setTexture("textureSampler", flare.texture);
  76802. // Color
  76803. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  76804. // Draw order
  76805. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76806. }
  76807. engine.setDepthBuffer(true);
  76808. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76809. return true;
  76810. };
  76811. LensFlareSystem.prototype.dispose = function () {
  76812. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76813. if (vertexBuffer) {
  76814. vertexBuffer.dispose();
  76815. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76816. }
  76817. if (this._indexBuffer) {
  76818. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  76819. this._indexBuffer = null;
  76820. }
  76821. while (this.lensFlares.length) {
  76822. this.lensFlares[0].dispose();
  76823. }
  76824. // Remove from scene
  76825. var index = this._scene.lensFlareSystems.indexOf(this);
  76826. this._scene.lensFlareSystems.splice(index, 1);
  76827. };
  76828. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  76829. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  76830. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  76831. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  76832. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  76833. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  76834. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  76835. var parsedFlare = parsedLensFlareSystem.flares[index];
  76836. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  76837. }
  76838. return lensFlareSystem;
  76839. };
  76840. LensFlareSystem.prototype.serialize = function () {
  76841. var serializationObject = {};
  76842. serializationObject.id = this.id;
  76843. serializationObject.name = this.name;
  76844. serializationObject.emitterId = this.getEmitter().id;
  76845. serializationObject.borderLimit = this.borderLimit;
  76846. serializationObject.flares = [];
  76847. for (var index = 0; index < this.lensFlares.length; index++) {
  76848. var flare = this.lensFlares[index];
  76849. serializationObject.flares.push({
  76850. size: flare.size,
  76851. position: flare.position,
  76852. color: flare.color.asArray(),
  76853. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  76854. });
  76855. }
  76856. return serializationObject;
  76857. };
  76858. return LensFlareSystem;
  76859. }());
  76860. BABYLON.LensFlareSystem = LensFlareSystem;
  76861. })(BABYLON || (BABYLON = {}));
  76862. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  76863. "use strict";
  76864. var BABYLON;
  76865. (function (BABYLON) {
  76866. /**
  76867. * This is a holder class for the physics joint created by the physics plugin.
  76868. * It holds a set of functions to control the underlying joint.
  76869. */
  76870. var PhysicsJoint = /** @class */ (function () {
  76871. function PhysicsJoint(type, jointData) {
  76872. this.type = type;
  76873. this.jointData = jointData;
  76874. jointData.nativeParams = jointData.nativeParams || {};
  76875. }
  76876. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  76877. get: function () {
  76878. return this._physicsJoint;
  76879. },
  76880. set: function (newJoint) {
  76881. if (this._physicsJoint) {
  76882. //remove from the wolrd
  76883. }
  76884. this._physicsJoint = newJoint;
  76885. },
  76886. enumerable: true,
  76887. configurable: true
  76888. });
  76889. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  76890. set: function (physicsPlugin) {
  76891. this._physicsPlugin = physicsPlugin;
  76892. },
  76893. enumerable: true,
  76894. configurable: true
  76895. });
  76896. /**
  76897. * Execute a function that is physics-plugin specific.
  76898. * @param {Function} func the function that will be executed.
  76899. * It accepts two parameters: the physics world and the physics joint.
  76900. */
  76901. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  76902. func(this._physicsPlugin.world, this._physicsJoint);
  76903. };
  76904. //TODO check if the native joints are the same
  76905. //Joint Types
  76906. PhysicsJoint.DistanceJoint = 0;
  76907. PhysicsJoint.HingeJoint = 1;
  76908. PhysicsJoint.BallAndSocketJoint = 2;
  76909. PhysicsJoint.WheelJoint = 3;
  76910. PhysicsJoint.SliderJoint = 4;
  76911. //OIMO
  76912. PhysicsJoint.PrismaticJoint = 5;
  76913. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  76914. PhysicsJoint.UniversalJoint = 6;
  76915. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  76916. //Cannon
  76917. //Similar to a Ball-Joint. Different in params
  76918. PhysicsJoint.PointToPointJoint = 8;
  76919. //Cannon only at the moment
  76920. PhysicsJoint.SpringJoint = 9;
  76921. PhysicsJoint.LockJoint = 10;
  76922. return PhysicsJoint;
  76923. }());
  76924. BABYLON.PhysicsJoint = PhysicsJoint;
  76925. /**
  76926. * A class representing a physics distance joint.
  76927. */
  76928. var DistanceJoint = /** @class */ (function (_super) {
  76929. __extends(DistanceJoint, _super);
  76930. function DistanceJoint(jointData) {
  76931. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  76932. }
  76933. /**
  76934. * Update the predefined distance.
  76935. */
  76936. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  76937. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  76938. };
  76939. return DistanceJoint;
  76940. }(PhysicsJoint));
  76941. BABYLON.DistanceJoint = DistanceJoint;
  76942. var MotorEnabledJoint = /** @class */ (function (_super) {
  76943. __extends(MotorEnabledJoint, _super);
  76944. function MotorEnabledJoint(type, jointData) {
  76945. return _super.call(this, type, jointData) || this;
  76946. }
  76947. /**
  76948. * Set the motor values.
  76949. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76950. * @param {number} force the force to apply
  76951. * @param {number} maxForce max force for this motor.
  76952. */
  76953. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  76954. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  76955. };
  76956. /**
  76957. * Set the motor's limits.
  76958. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76959. */
  76960. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  76961. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  76962. };
  76963. return MotorEnabledJoint;
  76964. }(PhysicsJoint));
  76965. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  76966. /**
  76967. * This class represents a single hinge physics joint
  76968. */
  76969. var HingeJoint = /** @class */ (function (_super) {
  76970. __extends(HingeJoint, _super);
  76971. function HingeJoint(jointData) {
  76972. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  76973. }
  76974. /**
  76975. * Set the motor values.
  76976. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76977. * @param {number} force the force to apply
  76978. * @param {number} maxForce max force for this motor.
  76979. */
  76980. HingeJoint.prototype.setMotor = function (force, maxForce) {
  76981. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  76982. };
  76983. /**
  76984. * Set the motor's limits.
  76985. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76986. */
  76987. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  76988. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  76989. };
  76990. return HingeJoint;
  76991. }(MotorEnabledJoint));
  76992. BABYLON.HingeJoint = HingeJoint;
  76993. /**
  76994. * This class represents a dual hinge physics joint (same as wheel joint)
  76995. */
  76996. var Hinge2Joint = /** @class */ (function (_super) {
  76997. __extends(Hinge2Joint, _super);
  76998. function Hinge2Joint(jointData) {
  76999. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  77000. }
  77001. /**
  77002. * Set the motor values.
  77003. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77004. * @param {number} force the force to apply
  77005. * @param {number} maxForce max force for this motor.
  77006. * @param {motorIndex} the motor's index, 0 or 1.
  77007. */
  77008. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  77009. if (motorIndex === void 0) { motorIndex = 0; }
  77010. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  77011. };
  77012. /**
  77013. * Set the motor limits.
  77014. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77015. * @param {number} upperLimit the upper limit
  77016. * @param {number} lowerLimit lower limit
  77017. * @param {motorIndex} the motor's index, 0 or 1.
  77018. */
  77019. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  77020. if (motorIndex === void 0) { motorIndex = 0; }
  77021. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  77022. };
  77023. return Hinge2Joint;
  77024. }(MotorEnabledJoint));
  77025. BABYLON.Hinge2Joint = Hinge2Joint;
  77026. })(BABYLON || (BABYLON = {}));
  77027. //# sourceMappingURL=babylon.physicsJoint.js.map
  77028. "use strict";
  77029. var BABYLON;
  77030. (function (BABYLON) {
  77031. var PhysicsImpostor = /** @class */ (function () {
  77032. function PhysicsImpostor(object, type, _options, _scene) {
  77033. if (_options === void 0) { _options = { mass: 0 }; }
  77034. var _this = this;
  77035. this.object = object;
  77036. this.type = type;
  77037. this._options = _options;
  77038. this._scene = _scene;
  77039. this._bodyUpdateRequired = false;
  77040. this._onBeforePhysicsStepCallbacks = new Array();
  77041. this._onAfterPhysicsStepCallbacks = new Array();
  77042. this._onPhysicsCollideCallbacks = [];
  77043. this._deltaPosition = BABYLON.Vector3.Zero();
  77044. this._isDisposed = false;
  77045. //temp variables for parent rotation calculations
  77046. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  77047. this._tmpQuat = new BABYLON.Quaternion();
  77048. this._tmpQuat2 = new BABYLON.Quaternion();
  77049. /**
  77050. * this function is executed by the physics engine.
  77051. */
  77052. this.beforeStep = function () {
  77053. if (!_this._physicsEngine) {
  77054. return;
  77055. }
  77056. _this.object.translate(_this._deltaPosition, -1);
  77057. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  77058. _this.object.computeWorldMatrix(false);
  77059. if (_this.object.parent && _this.object.rotationQuaternion) {
  77060. _this.getParentsRotation();
  77061. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  77062. }
  77063. else {
  77064. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  77065. }
  77066. if (!_this._options.disableBidirectionalTransformation) {
  77067. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  77068. }
  77069. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  77070. func(_this);
  77071. });
  77072. };
  77073. /**
  77074. * this function is executed by the physics engine.
  77075. */
  77076. this.afterStep = function () {
  77077. if (!_this._physicsEngine) {
  77078. return;
  77079. }
  77080. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  77081. func(_this);
  77082. });
  77083. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  77084. // object has now its world rotation. needs to be converted to local.
  77085. if (_this.object.parent && _this.object.rotationQuaternion) {
  77086. _this.getParentsRotation();
  77087. _this._tmpQuat.conjugateInPlace();
  77088. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  77089. }
  77090. // take the position set and make it the absolute position of this object.
  77091. _this.object.setAbsolutePosition(_this.object.position);
  77092. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  77093. _this.object.translate(_this._deltaPosition, 1);
  77094. };
  77095. /**
  77096. * Legacy collision detection event support
  77097. */
  77098. this.onCollideEvent = null;
  77099. //event and body object due to cannon's event-based architecture.
  77100. this.onCollide = function (e) {
  77101. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  77102. return;
  77103. }
  77104. if (!_this._physicsEngine) {
  77105. return;
  77106. }
  77107. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  77108. if (otherImpostor) {
  77109. // Legacy collision detection event support
  77110. if (_this.onCollideEvent) {
  77111. _this.onCollideEvent(_this, otherImpostor);
  77112. }
  77113. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  77114. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  77115. }).forEach(function (obj) {
  77116. obj.callback(_this, otherImpostor);
  77117. });
  77118. }
  77119. };
  77120. //sanity check!
  77121. if (!this.object) {
  77122. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  77123. return;
  77124. }
  77125. //legacy support for old syntax.
  77126. if (!this._scene && object.getScene) {
  77127. this._scene = object.getScene();
  77128. }
  77129. if (!this._scene) {
  77130. return;
  77131. }
  77132. this._physicsEngine = this._scene.getPhysicsEngine();
  77133. if (!this._physicsEngine) {
  77134. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  77135. }
  77136. else {
  77137. //set the object's quaternion, if not set
  77138. if (!this.object.rotationQuaternion) {
  77139. if (this.object.rotation) {
  77140. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  77141. }
  77142. else {
  77143. this.object.rotationQuaternion = new BABYLON.Quaternion();
  77144. }
  77145. }
  77146. //default options params
  77147. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  77148. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  77149. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  77150. this._joints = [];
  77151. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  77152. if (!this.object.parent || this._options.ignoreParent) {
  77153. this._init();
  77154. }
  77155. else if (this.object.parent.physicsImpostor) {
  77156. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  77157. }
  77158. }
  77159. }
  77160. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  77161. get: function () {
  77162. return this._isDisposed;
  77163. },
  77164. enumerable: true,
  77165. configurable: true
  77166. });
  77167. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  77168. get: function () {
  77169. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  77170. },
  77171. set: function (value) {
  77172. this.setMass(value);
  77173. },
  77174. enumerable: true,
  77175. configurable: true
  77176. });
  77177. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  77178. get: function () {
  77179. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  77180. },
  77181. set: function (value) {
  77182. if (!this._physicsEngine) {
  77183. return;
  77184. }
  77185. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  77186. },
  77187. enumerable: true,
  77188. configurable: true
  77189. });
  77190. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  77191. get: function () {
  77192. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  77193. },
  77194. set: function (value) {
  77195. if (!this._physicsEngine) {
  77196. return;
  77197. }
  77198. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  77199. },
  77200. enumerable: true,
  77201. configurable: true
  77202. });
  77203. /**
  77204. * This function will completly initialize this impostor.
  77205. * It will create a new body - but only if this mesh has no parent.
  77206. * If it has, this impostor will not be used other than to define the impostor
  77207. * of the child mesh.
  77208. */
  77209. PhysicsImpostor.prototype._init = function () {
  77210. if (!this._physicsEngine) {
  77211. return;
  77212. }
  77213. this._physicsEngine.removeImpostor(this);
  77214. this.physicsBody = null;
  77215. this._parent = this._parent || this._getPhysicsParent();
  77216. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  77217. this._physicsEngine.addImpostor(this);
  77218. }
  77219. };
  77220. PhysicsImpostor.prototype._getPhysicsParent = function () {
  77221. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  77222. var parentMesh = this.object.parent;
  77223. return parentMesh.physicsImpostor;
  77224. }
  77225. return null;
  77226. };
  77227. /**
  77228. * Should a new body be generated.
  77229. */
  77230. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  77231. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  77232. };
  77233. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  77234. this.forceUpdate();
  77235. };
  77236. /**
  77237. * Force a regeneration of this or the parent's impostor's body.
  77238. * Use under cautious - This will remove all joints already implemented.
  77239. */
  77240. PhysicsImpostor.prototype.forceUpdate = function () {
  77241. this._init();
  77242. if (this.parent && !this._options.ignoreParent) {
  77243. this.parent.forceUpdate();
  77244. }
  77245. };
  77246. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  77247. /*public get mesh(): AbstractMesh {
  77248. return this._mesh;
  77249. }*/
  77250. /**
  77251. * Gets the body that holds this impostor. Either its own, or its parent.
  77252. */
  77253. get: function () {
  77254. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  77255. },
  77256. /**
  77257. * Set the physics body. Used mainly by the physics engine/plugin
  77258. */
  77259. set: function (physicsBody) {
  77260. if (this._physicsBody && this._physicsEngine) {
  77261. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  77262. }
  77263. this._physicsBody = physicsBody;
  77264. this.resetUpdateFlags();
  77265. },
  77266. enumerable: true,
  77267. configurable: true
  77268. });
  77269. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  77270. get: function () {
  77271. return !this._options.ignoreParent && this._parent ? this._parent : null;
  77272. },
  77273. set: function (value) {
  77274. this._parent = value;
  77275. },
  77276. enumerable: true,
  77277. configurable: true
  77278. });
  77279. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  77280. this._bodyUpdateRequired = false;
  77281. };
  77282. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  77283. if (this.object.getBoundingInfo) {
  77284. var q = this.object.rotationQuaternion;
  77285. //reset rotation
  77286. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  77287. //calculate the world matrix with no rotation
  77288. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  77289. var boundingInfo = this.object.getBoundingInfo();
  77290. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  77291. //bring back the rotation
  77292. this.object.rotationQuaternion = q;
  77293. //calculate the world matrix with the new rotation
  77294. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  77295. return size;
  77296. }
  77297. else {
  77298. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  77299. }
  77300. };
  77301. PhysicsImpostor.prototype.getObjectCenter = function () {
  77302. if (this.object.getBoundingInfo) {
  77303. var boundingInfo = this.object.getBoundingInfo();
  77304. return boundingInfo.boundingBox.centerWorld;
  77305. }
  77306. else {
  77307. return this.object.position;
  77308. }
  77309. };
  77310. /**
  77311. * Get a specific parametes from the options parameter.
  77312. */
  77313. PhysicsImpostor.prototype.getParam = function (paramName) {
  77314. return this._options[paramName];
  77315. };
  77316. /**
  77317. * Sets a specific parameter in the options given to the physics plugin
  77318. */
  77319. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  77320. this._options[paramName] = value;
  77321. this._bodyUpdateRequired = true;
  77322. };
  77323. /**
  77324. * Specifically change the body's mass option. Won't recreate the physics body object
  77325. */
  77326. PhysicsImpostor.prototype.setMass = function (mass) {
  77327. if (this.getParam("mass") !== mass) {
  77328. this.setParam("mass", mass);
  77329. }
  77330. if (this._physicsEngine) {
  77331. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  77332. }
  77333. };
  77334. PhysicsImpostor.prototype.getLinearVelocity = function () {
  77335. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  77336. };
  77337. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  77338. if (this._physicsEngine) {
  77339. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  77340. }
  77341. };
  77342. PhysicsImpostor.prototype.getAngularVelocity = function () {
  77343. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  77344. };
  77345. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  77346. if (this._physicsEngine) {
  77347. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  77348. }
  77349. };
  77350. /**
  77351. * Execute a function with the physics plugin native code.
  77352. * Provide a function the will have two variables - the world object and the physics body object.
  77353. */
  77354. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  77355. if (this._physicsEngine) {
  77356. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  77357. }
  77358. };
  77359. /**
  77360. * Register a function that will be executed before the physics world is stepping forward.
  77361. */
  77362. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  77363. this._onBeforePhysicsStepCallbacks.push(func);
  77364. };
  77365. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  77366. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  77367. if (index > -1) {
  77368. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  77369. }
  77370. else {
  77371. BABYLON.Tools.Warn("Function to remove was not found");
  77372. }
  77373. };
  77374. /**
  77375. * Register a function that will be executed after the physics step
  77376. */
  77377. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  77378. this._onAfterPhysicsStepCallbacks.push(func);
  77379. };
  77380. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  77381. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  77382. if (index > -1) {
  77383. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  77384. }
  77385. else {
  77386. BABYLON.Tools.Warn("Function to remove was not found");
  77387. }
  77388. };
  77389. /**
  77390. * register a function that will be executed when this impostor collides against a different body.
  77391. */
  77392. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  77393. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  77394. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  77395. };
  77396. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  77397. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  77398. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  77399. if (index > -1) {
  77400. this._onPhysicsCollideCallbacks.splice(index, 1);
  77401. }
  77402. else {
  77403. BABYLON.Tools.Warn("Function to remove was not found");
  77404. }
  77405. };
  77406. PhysicsImpostor.prototype.getParentsRotation = function () {
  77407. var parent = this.object.parent;
  77408. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  77409. while (parent) {
  77410. if (parent.rotationQuaternion) {
  77411. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  77412. }
  77413. else {
  77414. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  77415. }
  77416. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  77417. parent = parent.parent;
  77418. }
  77419. return this._tmpQuat;
  77420. };
  77421. /**
  77422. * Apply a force
  77423. */
  77424. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  77425. if (this._physicsEngine) {
  77426. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  77427. }
  77428. return this;
  77429. };
  77430. /**
  77431. * Apply an impulse
  77432. */
  77433. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  77434. if (this._physicsEngine) {
  77435. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  77436. }
  77437. return this;
  77438. };
  77439. /**
  77440. * A help function to create a joint.
  77441. */
  77442. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  77443. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  77444. this.addJoint(otherImpostor, joint);
  77445. return this;
  77446. };
  77447. /**
  77448. * Add a joint to this impostor with a different impostor.
  77449. */
  77450. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  77451. this._joints.push({
  77452. otherImpostor: otherImpostor,
  77453. joint: joint
  77454. });
  77455. if (this._physicsEngine) {
  77456. this._physicsEngine.addJoint(this, otherImpostor, joint);
  77457. }
  77458. return this;
  77459. };
  77460. /**
  77461. * Will keep this body still, in a sleep mode.
  77462. */
  77463. PhysicsImpostor.prototype.sleep = function () {
  77464. if (this._physicsEngine) {
  77465. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  77466. }
  77467. return this;
  77468. };
  77469. /**
  77470. * Wake the body up.
  77471. */
  77472. PhysicsImpostor.prototype.wakeUp = function () {
  77473. if (this._physicsEngine) {
  77474. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  77475. }
  77476. return this;
  77477. };
  77478. PhysicsImpostor.prototype.clone = function (newObject) {
  77479. if (!newObject)
  77480. return null;
  77481. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  77482. };
  77483. PhysicsImpostor.prototype.dispose = function () {
  77484. var _this = this;
  77485. //no dispose if no physics engine is available.
  77486. if (!this._physicsEngine) {
  77487. return;
  77488. }
  77489. this._joints.forEach(function (j) {
  77490. if (_this._physicsEngine) {
  77491. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  77492. }
  77493. });
  77494. //dispose the physics body
  77495. this._physicsEngine.removeImpostor(this);
  77496. if (this.parent) {
  77497. this.parent.forceUpdate();
  77498. }
  77499. else {
  77500. /*this._object.getChildMeshes().forEach(function(mesh) {
  77501. if (mesh.physicsImpostor) {
  77502. if (disposeChildren) {
  77503. mesh.physicsImpostor.dispose();
  77504. mesh.physicsImpostor = null;
  77505. }
  77506. }
  77507. })*/
  77508. }
  77509. this._isDisposed = true;
  77510. };
  77511. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  77512. this._deltaPosition.copyFrom(position);
  77513. };
  77514. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  77515. if (!this._deltaRotation) {
  77516. this._deltaRotation = new BABYLON.Quaternion();
  77517. }
  77518. this._deltaRotation.copyFrom(rotation);
  77519. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  77520. };
  77521. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  77522. if (this._physicsEngine) {
  77523. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  77524. }
  77525. return this;
  77526. };
  77527. PhysicsImpostor.prototype.getRadius = function () {
  77528. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  77529. };
  77530. /**
  77531. * Sync a bone with this impostor
  77532. * @param bone The bone to sync to the impostor.
  77533. * @param boneMesh The mesh that the bone is influencing.
  77534. * @param jointPivot The pivot of the joint / bone in local space.
  77535. * @param distToJoint Optional distance from the impostor to the joint.
  77536. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  77537. */
  77538. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  77539. var tempVec = PhysicsImpostor._tmpVecs[0];
  77540. var mesh = this.object;
  77541. if (mesh.rotationQuaternion) {
  77542. if (adjustRotation) {
  77543. var tempQuat = PhysicsImpostor._tmpQuat;
  77544. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  77545. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  77546. }
  77547. else {
  77548. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  77549. }
  77550. }
  77551. tempVec.x = 0;
  77552. tempVec.y = 0;
  77553. tempVec.z = 0;
  77554. if (jointPivot) {
  77555. tempVec.x = jointPivot.x;
  77556. tempVec.y = jointPivot.y;
  77557. tempVec.z = jointPivot.z;
  77558. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  77559. if (distToJoint === undefined || distToJoint === null) {
  77560. distToJoint = jointPivot.length();
  77561. }
  77562. tempVec.x *= distToJoint;
  77563. tempVec.y *= distToJoint;
  77564. tempVec.z *= distToJoint;
  77565. }
  77566. if (bone.getParent()) {
  77567. tempVec.addInPlace(mesh.getAbsolutePosition());
  77568. bone.setAbsolutePosition(tempVec, boneMesh);
  77569. }
  77570. else {
  77571. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  77572. boneMesh.position.x -= tempVec.x;
  77573. boneMesh.position.y -= tempVec.y;
  77574. boneMesh.position.z -= tempVec.z;
  77575. }
  77576. };
  77577. /**
  77578. * Sync impostor to a bone
  77579. * @param bone The bone that the impostor will be synced to.
  77580. * @param boneMesh The mesh that the bone is influencing.
  77581. * @param jointPivot The pivot of the joint / bone in local space.
  77582. * @param distToJoint Optional distance from the impostor to the joint.
  77583. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  77584. * @param boneAxis Optional vector3 axis the bone is aligned with
  77585. */
  77586. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  77587. var mesh = this.object;
  77588. if (mesh.rotationQuaternion) {
  77589. if (adjustRotation) {
  77590. var tempQuat = PhysicsImpostor._tmpQuat;
  77591. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  77592. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  77593. }
  77594. else {
  77595. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  77596. }
  77597. }
  77598. var pos = PhysicsImpostor._tmpVecs[0];
  77599. var boneDir = PhysicsImpostor._tmpVecs[1];
  77600. if (!boneAxis) {
  77601. boneAxis = PhysicsImpostor._tmpVecs[2];
  77602. boneAxis.x = 0;
  77603. boneAxis.y = 1;
  77604. boneAxis.z = 0;
  77605. }
  77606. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  77607. bone.getAbsolutePositionToRef(boneMesh, pos);
  77608. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  77609. distToJoint = jointPivot.length();
  77610. }
  77611. if (distToJoint !== undefined && distToJoint !== null) {
  77612. pos.x += boneDir.x * distToJoint;
  77613. pos.y += boneDir.y * distToJoint;
  77614. pos.z += boneDir.z * distToJoint;
  77615. }
  77616. mesh.setAbsolutePosition(pos);
  77617. };
  77618. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  77619. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  77620. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77621. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  77622. //Impostor types
  77623. PhysicsImpostor.NoImpostor = 0;
  77624. PhysicsImpostor.SphereImpostor = 1;
  77625. PhysicsImpostor.BoxImpostor = 2;
  77626. PhysicsImpostor.PlaneImpostor = 3;
  77627. PhysicsImpostor.MeshImpostor = 4;
  77628. PhysicsImpostor.CylinderImpostor = 7;
  77629. PhysicsImpostor.ParticleImpostor = 8;
  77630. PhysicsImpostor.HeightmapImpostor = 9;
  77631. return PhysicsImpostor;
  77632. }());
  77633. BABYLON.PhysicsImpostor = PhysicsImpostor;
  77634. })(BABYLON || (BABYLON = {}));
  77635. //# sourceMappingURL=babylon.physicsImpostor.js.map
  77636. "use strict";
  77637. var BABYLON;
  77638. (function (BABYLON) {
  77639. var PhysicsEngine = /** @class */ (function () {
  77640. function PhysicsEngine(gravity, _physicsPlugin) {
  77641. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  77642. this._physicsPlugin = _physicsPlugin;
  77643. //new methods and parameters
  77644. this._impostors = [];
  77645. this._joints = [];
  77646. if (!this._physicsPlugin.isSupported()) {
  77647. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  77648. + "Please make sure it is included.");
  77649. }
  77650. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  77651. this.setGravity(gravity);
  77652. this.setTimeStep();
  77653. }
  77654. PhysicsEngine.prototype.setGravity = function (gravity) {
  77655. this.gravity = gravity;
  77656. this._physicsPlugin.setGravity(this.gravity);
  77657. };
  77658. /**
  77659. * Set the time step of the physics engine.
  77660. * default is 1/60.
  77661. * To slow it down, enter 1/600 for example.
  77662. * To speed it up, 1/30
  77663. * @param {number} newTimeStep the new timestep to apply to this world.
  77664. */
  77665. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  77666. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  77667. this._physicsPlugin.setTimeStep(newTimeStep);
  77668. };
  77669. /**
  77670. * Get the time step of the physics engine.
  77671. */
  77672. PhysicsEngine.prototype.getTimeStep = function () {
  77673. return this._physicsPlugin.getTimeStep();
  77674. };
  77675. PhysicsEngine.prototype.dispose = function () {
  77676. this._impostors.forEach(function (impostor) {
  77677. impostor.dispose();
  77678. });
  77679. this._physicsPlugin.dispose();
  77680. };
  77681. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  77682. return this._physicsPlugin.name;
  77683. };
  77684. /**
  77685. * Adding a new impostor for the impostor tracking.
  77686. * This will be done by the impostor itself.
  77687. * @param {PhysicsImpostor} impostor the impostor to add
  77688. */
  77689. PhysicsEngine.prototype.addImpostor = function (impostor) {
  77690. impostor.uniqueId = this._impostors.push(impostor);
  77691. //if no parent, generate the body
  77692. if (!impostor.parent) {
  77693. this._physicsPlugin.generatePhysicsBody(impostor);
  77694. }
  77695. };
  77696. /**
  77697. * Remove an impostor from the engine.
  77698. * This impostor and its mesh will not longer be updated by the physics engine.
  77699. * @param {PhysicsImpostor} impostor the impostor to remove
  77700. */
  77701. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  77702. var index = this._impostors.indexOf(impostor);
  77703. if (index > -1) {
  77704. var removed = this._impostors.splice(index, 1);
  77705. //Is it needed?
  77706. if (removed.length) {
  77707. //this will also remove it from the world.
  77708. removed[0].physicsBody = null;
  77709. }
  77710. }
  77711. };
  77712. /**
  77713. * Add a joint to the physics engine
  77714. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  77715. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  77716. * @param {PhysicsJoint} the joint that will connect both impostors.
  77717. */
  77718. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  77719. var impostorJoint = {
  77720. mainImpostor: mainImpostor,
  77721. connectedImpostor: connectedImpostor,
  77722. joint: joint
  77723. };
  77724. joint.physicsPlugin = this._physicsPlugin;
  77725. this._joints.push(impostorJoint);
  77726. this._physicsPlugin.generateJoint(impostorJoint);
  77727. };
  77728. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  77729. var matchingJoints = this._joints.filter(function (impostorJoint) {
  77730. return (impostorJoint.connectedImpostor === connectedImpostor
  77731. && impostorJoint.joint === joint
  77732. && impostorJoint.mainImpostor === mainImpostor);
  77733. });
  77734. if (matchingJoints.length) {
  77735. this._physicsPlugin.removeJoint(matchingJoints[0]);
  77736. //TODO remove it from the list as well
  77737. }
  77738. };
  77739. /**
  77740. * Called by the scene. no need to call it.
  77741. */
  77742. PhysicsEngine.prototype._step = function (delta) {
  77743. var _this = this;
  77744. //check if any mesh has no body / requires an update
  77745. this._impostors.forEach(function (impostor) {
  77746. if (impostor.isBodyInitRequired()) {
  77747. _this._physicsPlugin.generatePhysicsBody(impostor);
  77748. }
  77749. });
  77750. if (delta > 0.1) {
  77751. delta = 0.1;
  77752. }
  77753. else if (delta <= 0) {
  77754. delta = 1.0 / 60.0;
  77755. }
  77756. this._physicsPlugin.executeStep(delta, this._impostors);
  77757. };
  77758. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  77759. return this._physicsPlugin;
  77760. };
  77761. PhysicsEngine.prototype.getImpostors = function () {
  77762. return this._impostors;
  77763. };
  77764. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  77765. for (var i = 0; i < this._impostors.length; ++i) {
  77766. if (this._impostors[i].object === object) {
  77767. return this._impostors[i];
  77768. }
  77769. }
  77770. return null;
  77771. };
  77772. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  77773. for (var i = 0; i < this._impostors.length; ++i) {
  77774. if (this._impostors[i].physicsBody === body) {
  77775. return this._impostors[i];
  77776. }
  77777. }
  77778. return null;
  77779. };
  77780. // Statics
  77781. PhysicsEngine.Epsilon = 0.001;
  77782. return PhysicsEngine;
  77783. }());
  77784. BABYLON.PhysicsEngine = PhysicsEngine;
  77785. })(BABYLON || (BABYLON = {}));
  77786. //# sourceMappingURL=babylon.physicsEngine.js.map
  77787. "use strict";
  77788. var BABYLON;
  77789. (function (BABYLON) {
  77790. var PhysicsHelper = /** @class */ (function () {
  77791. function PhysicsHelper(scene) {
  77792. this._scene = scene;
  77793. this._physicsEngine = this._scene.getPhysicsEngine();
  77794. if (!this._physicsEngine) {
  77795. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  77796. }
  77797. }
  77798. /**
  77799. * @param {Vector3} origin the origin of the explosion
  77800. * @param {number} radius the explosion radius
  77801. * @param {number} strength the explosion strength
  77802. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77803. */
  77804. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  77805. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77806. if (!this._physicsEngine) {
  77807. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  77808. return null;
  77809. }
  77810. var impostors = this._physicsEngine.getImpostors();
  77811. if (impostors.length === 0) {
  77812. return null;
  77813. }
  77814. var event = new PhysicsRadialExplosionEvent(this._scene);
  77815. impostors.forEach(function (impostor) {
  77816. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  77817. if (!impostorForceAndContactPoint) {
  77818. return;
  77819. }
  77820. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77821. });
  77822. event.dispose(false);
  77823. return event;
  77824. };
  77825. /**
  77826. * @param {Vector3} origin the origin of the explosion
  77827. * @param {number} radius the explosion radius
  77828. * @param {number} strength the explosion strength
  77829. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77830. */
  77831. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  77832. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77833. if (!this._physicsEngine) {
  77834. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77835. return null;
  77836. }
  77837. var impostors = this._physicsEngine.getImpostors();
  77838. if (impostors.length === 0) {
  77839. return null;
  77840. }
  77841. var event = new PhysicsRadialExplosionEvent(this._scene);
  77842. impostors.forEach(function (impostor) {
  77843. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  77844. if (!impostorForceAndContactPoint) {
  77845. return;
  77846. }
  77847. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77848. });
  77849. event.dispose(false);
  77850. return event;
  77851. };
  77852. /**
  77853. * @param {Vector3} origin the origin of the explosion
  77854. * @param {number} radius the explosion radius
  77855. * @param {number} strength the explosion strength
  77856. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77857. */
  77858. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  77859. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77860. if (!this._physicsEngine) {
  77861. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77862. return null;
  77863. }
  77864. var impostors = this._physicsEngine.getImpostors();
  77865. if (impostors.length === 0) {
  77866. return null;
  77867. }
  77868. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  77869. event.dispose(false);
  77870. return event;
  77871. };
  77872. /**
  77873. * @param {Vector3} origin the origin of the updraft
  77874. * @param {number} radius the radius of the updraft
  77875. * @param {number} strength the strength of the updraft
  77876. * @param {number} height the height of the updraft
  77877. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  77878. */
  77879. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  77880. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  77881. if (!this._physicsEngine) {
  77882. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77883. return null;
  77884. }
  77885. if (this._physicsEngine.getImpostors().length === 0) {
  77886. return null;
  77887. }
  77888. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  77889. event.dispose(false);
  77890. return event;
  77891. };
  77892. /**
  77893. * @param {Vector3} origin the of the vortex
  77894. * @param {number} radius the radius of the vortex
  77895. * @param {number} strength the strength of the vortex
  77896. * @param {number} height the height of the vortex
  77897. */
  77898. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  77899. if (!this._physicsEngine) {
  77900. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77901. return null;
  77902. }
  77903. if (this._physicsEngine.getImpostors().length === 0) {
  77904. return null;
  77905. }
  77906. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  77907. event.dispose(false);
  77908. return event;
  77909. };
  77910. return PhysicsHelper;
  77911. }());
  77912. BABYLON.PhysicsHelper = PhysicsHelper;
  77913. /***** Radial explosion *****/
  77914. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  77915. function PhysicsRadialExplosionEvent(scene) {
  77916. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  77917. this._rays = [];
  77918. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  77919. this._scene = scene;
  77920. }
  77921. /**
  77922. * Returns the data related to the radial explosion event (sphere & rays).
  77923. * @returns {PhysicsRadialExplosionEventData}
  77924. */
  77925. PhysicsRadialExplosionEvent.prototype.getData = function () {
  77926. this._dataFetched = true;
  77927. return {
  77928. sphere: this._sphere,
  77929. rays: this._rays,
  77930. };
  77931. };
  77932. /**
  77933. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  77934. * @param impostor
  77935. * @param {Vector3} origin the origin of the explosion
  77936. * @param {number} radius the explosion radius
  77937. * @param {number} strength the explosion strength
  77938. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  77939. * @returns {Nullable<PhysicsForceAndContactPoint>}
  77940. */
  77941. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  77942. if (impostor.mass === 0) {
  77943. return null;
  77944. }
  77945. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  77946. return null;
  77947. }
  77948. if (impostor.object.getClassName() !== 'Mesh') {
  77949. return null;
  77950. }
  77951. var impostorObject = impostor.object;
  77952. var impostorObjectCenter = impostor.getObjectCenter();
  77953. var direction = impostorObjectCenter.subtract(origin);
  77954. var ray = new BABYLON.Ray(origin, direction, radius);
  77955. this._rays.push(ray);
  77956. var hit = ray.intersectsMesh(impostorObject);
  77957. var contactPoint = hit.pickedPoint;
  77958. if (!contactPoint) {
  77959. return null;
  77960. }
  77961. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  77962. if (distanceFromOrigin > radius) {
  77963. return null;
  77964. }
  77965. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  77966. ? strength
  77967. : strength * (1 - (distanceFromOrigin / radius));
  77968. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  77969. return { force: force, contactPoint: contactPoint };
  77970. };
  77971. /**
  77972. * Disposes the sphere.
  77973. * @param {bolean} force
  77974. */
  77975. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  77976. var _this = this;
  77977. if (force === void 0) { force = true; }
  77978. if (force) {
  77979. this._sphere.dispose();
  77980. }
  77981. else {
  77982. setTimeout(function () {
  77983. if (!_this._dataFetched) {
  77984. _this._sphere.dispose();
  77985. }
  77986. }, 0);
  77987. }
  77988. };
  77989. /*** Helpers ***/
  77990. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  77991. if (!this._sphere) {
  77992. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  77993. this._sphere.isVisible = false;
  77994. }
  77995. };
  77996. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  77997. var impostorObject = impostor.object;
  77998. this._prepareSphere();
  77999. this._sphere.position = origin;
  78000. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  78001. this._sphere._updateBoundingInfo();
  78002. this._sphere.computeWorldMatrix(true);
  78003. return this._sphere.intersectsMesh(impostorObject, true);
  78004. };
  78005. return PhysicsRadialExplosionEvent;
  78006. }());
  78007. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  78008. /***** Gravitational Field *****/
  78009. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  78010. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  78011. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78012. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78013. this._physicsHelper = physicsHelper;
  78014. this._scene = scene;
  78015. this._origin = origin;
  78016. this._radius = radius;
  78017. this._strength = strength;
  78018. this._falloff = falloff;
  78019. this._tickCallback = this._tick.bind(this);
  78020. }
  78021. /**
  78022. * Returns the data related to the gravitational field event (sphere).
  78023. * @returns {PhysicsGravitationalFieldEventData}
  78024. */
  78025. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  78026. this._dataFetched = true;
  78027. return {
  78028. sphere: this._sphere,
  78029. };
  78030. };
  78031. /**
  78032. * Enables the gravitational field.
  78033. */
  78034. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  78035. this._tickCallback.call(this);
  78036. this._scene.registerBeforeRender(this._tickCallback);
  78037. };
  78038. /**
  78039. * Disables the gravitational field.
  78040. */
  78041. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  78042. this._scene.unregisterBeforeRender(this._tickCallback);
  78043. };
  78044. /**
  78045. * Disposes the sphere.
  78046. * @param {bolean} force
  78047. */
  78048. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  78049. var _this = this;
  78050. if (force === void 0) { force = true; }
  78051. if (force) {
  78052. this._sphere.dispose();
  78053. }
  78054. else {
  78055. setTimeout(function () {
  78056. if (!_this._dataFetched) {
  78057. _this._sphere.dispose();
  78058. }
  78059. }, 0);
  78060. }
  78061. };
  78062. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  78063. // Since the params won't change, we fetch the event only once
  78064. if (this._sphere) {
  78065. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  78066. }
  78067. else {
  78068. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  78069. if (radialExplosionEvent) {
  78070. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  78071. }
  78072. }
  78073. };
  78074. return PhysicsGravitationalFieldEvent;
  78075. }());
  78076. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  78077. /***** Updraft *****/
  78078. var PhysicsUpdraftEvent = /** @class */ (function () {
  78079. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  78080. this._scene = _scene;
  78081. this._origin = _origin;
  78082. this._radius = _radius;
  78083. this._strength = _strength;
  78084. this._height = _height;
  78085. this._updraftMode = _updraftMode;
  78086. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  78087. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  78088. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  78089. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78090. this._physicsEngine = this._scene.getPhysicsEngine();
  78091. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  78092. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  78093. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  78094. this._originDirection = this._origin.subtract(this._originTop).normalize();
  78095. }
  78096. this._tickCallback = this._tick.bind(this);
  78097. }
  78098. /**
  78099. * Returns the data related to the updraft event (cylinder).
  78100. * @returns {PhysicsUpdraftEventData}
  78101. */
  78102. PhysicsUpdraftEvent.prototype.getData = function () {
  78103. this._dataFetched = true;
  78104. return {
  78105. cylinder: this._cylinder,
  78106. };
  78107. };
  78108. /**
  78109. * Enables the updraft.
  78110. */
  78111. PhysicsUpdraftEvent.prototype.enable = function () {
  78112. this._tickCallback.call(this);
  78113. this._scene.registerBeforeRender(this._tickCallback);
  78114. };
  78115. /**
  78116. * Disables the cortex.
  78117. */
  78118. PhysicsUpdraftEvent.prototype.disable = function () {
  78119. this._scene.unregisterBeforeRender(this._tickCallback);
  78120. };
  78121. /**
  78122. * Disposes the sphere.
  78123. * @param {bolean} force
  78124. */
  78125. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  78126. var _this = this;
  78127. if (force === void 0) { force = true; }
  78128. if (force) {
  78129. this._cylinder.dispose();
  78130. }
  78131. else {
  78132. setTimeout(function () {
  78133. if (!_this._dataFetched) {
  78134. _this._cylinder.dispose();
  78135. }
  78136. }, 0);
  78137. }
  78138. };
  78139. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  78140. if (impostor.mass === 0) {
  78141. return null;
  78142. }
  78143. if (!this._intersectsWithCylinder(impostor)) {
  78144. return null;
  78145. }
  78146. var impostorObjectCenter = impostor.getObjectCenter();
  78147. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  78148. var direction = this._originDirection;
  78149. }
  78150. else {
  78151. var direction = impostorObjectCenter.subtract(this._originTop);
  78152. }
  78153. var multiplier = this._strength * -1;
  78154. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  78155. return { force: force, contactPoint: impostorObjectCenter };
  78156. };
  78157. PhysicsUpdraftEvent.prototype._tick = function () {
  78158. var _this = this;
  78159. this._physicsEngine.getImpostors().forEach(function (impostor) {
  78160. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  78161. if (!impostorForceAndContactPoint) {
  78162. return;
  78163. }
  78164. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78165. });
  78166. };
  78167. /*** Helpers ***/
  78168. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  78169. if (!this._cylinder) {
  78170. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  78171. height: this._height,
  78172. diameter: this._radius * 2,
  78173. }, this._scene);
  78174. this._cylinder.isVisible = false;
  78175. }
  78176. };
  78177. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  78178. var impostorObject = impostor.object;
  78179. this._prepareCylinder();
  78180. this._cylinder.position = this._cylinderPosition;
  78181. return this._cylinder.intersectsMesh(impostorObject, true);
  78182. };
  78183. return PhysicsUpdraftEvent;
  78184. }());
  78185. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  78186. /***** Vortex *****/
  78187. var PhysicsVortexEvent = /** @class */ (function () {
  78188. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  78189. this._scene = _scene;
  78190. this._origin = _origin;
  78191. this._radius = _radius;
  78192. this._strength = _strength;
  78193. this._height = _height;
  78194. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  78195. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  78196. this._updraftMultiplier = 0.02;
  78197. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  78198. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78199. this._physicsEngine = this._scene.getPhysicsEngine();
  78200. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  78201. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  78202. this._tickCallback = this._tick.bind(this);
  78203. }
  78204. /**
  78205. * Returns the data related to the vortex event (cylinder).
  78206. * @returns {PhysicsVortexEventData}
  78207. */
  78208. PhysicsVortexEvent.prototype.getData = function () {
  78209. this._dataFetched = true;
  78210. return {
  78211. cylinder: this._cylinder,
  78212. };
  78213. };
  78214. /**
  78215. * Enables the vortex.
  78216. */
  78217. PhysicsVortexEvent.prototype.enable = function () {
  78218. this._tickCallback.call(this);
  78219. this._scene.registerBeforeRender(this._tickCallback);
  78220. };
  78221. /**
  78222. * Disables the cortex.
  78223. */
  78224. PhysicsVortexEvent.prototype.disable = function () {
  78225. this._scene.unregisterBeforeRender(this._tickCallback);
  78226. };
  78227. /**
  78228. * Disposes the sphere.
  78229. * @param {bolean} force
  78230. */
  78231. PhysicsVortexEvent.prototype.dispose = function (force) {
  78232. var _this = this;
  78233. if (force === void 0) { force = true; }
  78234. if (force) {
  78235. this._cylinder.dispose();
  78236. }
  78237. else {
  78238. setTimeout(function () {
  78239. if (!_this._dataFetched) {
  78240. _this._cylinder.dispose();
  78241. }
  78242. }, 0);
  78243. }
  78244. };
  78245. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  78246. if (impostor.mass === 0) {
  78247. return null;
  78248. }
  78249. if (!this._intersectsWithCylinder(impostor)) {
  78250. return null;
  78251. }
  78252. if (impostor.object.getClassName() !== 'Mesh') {
  78253. return null;
  78254. }
  78255. var impostorObject = impostor.object;
  78256. var impostorObjectCenter = impostor.getObjectCenter();
  78257. 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)
  78258. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  78259. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  78260. var hit = ray.intersectsMesh(impostorObject);
  78261. var contactPoint = hit.pickedPoint;
  78262. if (!contactPoint) {
  78263. return null;
  78264. }
  78265. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  78266. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  78267. var directionToOrigin = contactPoint.normalize();
  78268. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  78269. directionToOrigin = directionToOrigin.negate();
  78270. }
  78271. // TODO: find a more physically based solution
  78272. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  78273. var forceX = directionToOrigin.x * this._strength / 8;
  78274. var forceY = directionToOrigin.y * this._updraftMultiplier;
  78275. var forceZ = directionToOrigin.z * this._strength / 8;
  78276. }
  78277. else {
  78278. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  78279. var forceY = this._originTop.y * this._updraftMultiplier;
  78280. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  78281. }
  78282. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  78283. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  78284. return { force: force, contactPoint: impostorObjectCenter };
  78285. };
  78286. PhysicsVortexEvent.prototype._tick = function () {
  78287. var _this = this;
  78288. this._physicsEngine.getImpostors().forEach(function (impostor) {
  78289. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  78290. if (!impostorForceAndContactPoint) {
  78291. return;
  78292. }
  78293. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78294. });
  78295. };
  78296. /*** Helpers ***/
  78297. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  78298. if (!this._cylinder) {
  78299. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  78300. height: this._height,
  78301. diameter: this._radius * 2,
  78302. }, this._scene);
  78303. this._cylinder.isVisible = false;
  78304. }
  78305. };
  78306. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  78307. var impostorObject = impostor.object;
  78308. this._prepareCylinder();
  78309. this._cylinder.position = this._cylinderPosition;
  78310. return this._cylinder.intersectsMesh(impostorObject, true);
  78311. };
  78312. return PhysicsVortexEvent;
  78313. }());
  78314. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  78315. /***** Enums *****/
  78316. /**
  78317. * The strenght of the force in correspondence to the distance of the affected object
  78318. */
  78319. var PhysicsRadialImpulseFalloff;
  78320. (function (PhysicsRadialImpulseFalloff) {
  78321. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  78322. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  78323. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  78324. /**
  78325. * The strenght of the force in correspondence to the distance of the affected object
  78326. */
  78327. var PhysicsUpdraftMode;
  78328. (function (PhysicsUpdraftMode) {
  78329. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  78330. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  78331. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  78332. })(BABYLON || (BABYLON = {}));
  78333. //# sourceMappingURL=babylon.physicsHelper.js.map
  78334. "use strict";
  78335. var BABYLON;
  78336. (function (BABYLON) {
  78337. var CannonJSPlugin = /** @class */ (function () {
  78338. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  78339. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  78340. if (iterations === void 0) { iterations = 10; }
  78341. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  78342. this.name = "CannonJSPlugin";
  78343. this._physicsMaterials = new Array();
  78344. this._fixedTimeStep = 1 / 60;
  78345. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  78346. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : ( true ? __webpack_require__(17) : undefined);
  78347. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  78348. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  78349. this._tmpPosition = BABYLON.Vector3.Zero();
  78350. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  78351. this._tmpUnityRotation = new BABYLON.Quaternion();
  78352. if (!this.isSupported()) {
  78353. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  78354. return;
  78355. }
  78356. this._extendNamespace();
  78357. this.world = new this.BJSCANNON.World();
  78358. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  78359. this.world.solver.iterations = iterations;
  78360. }
  78361. CannonJSPlugin.prototype.setGravity = function (gravity) {
  78362. this.world.gravity.copy(gravity);
  78363. };
  78364. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  78365. this._fixedTimeStep = timeStep;
  78366. };
  78367. CannonJSPlugin.prototype.getTimeStep = function () {
  78368. return this._fixedTimeStep;
  78369. };
  78370. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  78371. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  78372. };
  78373. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  78374. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  78375. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  78376. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  78377. };
  78378. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  78379. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  78380. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  78381. impostor.physicsBody.applyForce(impulse, worldPoint);
  78382. };
  78383. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  78384. //parent-child relationship. Does this impostor has a parent impostor?
  78385. if (impostor.parent) {
  78386. if (impostor.physicsBody) {
  78387. this.removePhysicsBody(impostor);
  78388. //TODO is that needed?
  78389. impostor.forceUpdate();
  78390. }
  78391. return;
  78392. }
  78393. //should a new body be created for this impostor?
  78394. if (impostor.isBodyInitRequired()) {
  78395. var shape = this._createShape(impostor);
  78396. //unregister events, if body is being changed
  78397. var oldBody = impostor.physicsBody;
  78398. if (oldBody) {
  78399. this.removePhysicsBody(impostor);
  78400. }
  78401. //create the body and material
  78402. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  78403. var bodyCreationObject = {
  78404. mass: impostor.getParam("mass"),
  78405. material: material
  78406. };
  78407. // A simple extend, in case native options were used.
  78408. var nativeOptions = impostor.getParam("nativeOptions");
  78409. for (var key in nativeOptions) {
  78410. if (nativeOptions.hasOwnProperty(key)) {
  78411. bodyCreationObject[key] = nativeOptions[key];
  78412. }
  78413. }
  78414. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  78415. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  78416. this.world.addEventListener("preStep", impostor.beforeStep);
  78417. this.world.addEventListener("postStep", impostor.afterStep);
  78418. impostor.physicsBody.addShape(shape);
  78419. this.world.add(impostor.physicsBody);
  78420. //try to keep the body moving in the right direction by taking old properties.
  78421. //Should be tested!
  78422. if (oldBody) {
  78423. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  78424. impostor.physicsBody[param].copy(oldBody[param]);
  78425. });
  78426. }
  78427. this._processChildMeshes(impostor);
  78428. }
  78429. //now update the body's transformation
  78430. this._updatePhysicsBodyTransformation(impostor);
  78431. };
  78432. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  78433. var _this = this;
  78434. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  78435. var currentRotation = mainImpostor.object.rotationQuaternion;
  78436. if (meshChildren.length) {
  78437. var processMesh = function (localPosition, mesh) {
  78438. if (!currentRotation || !mesh.rotationQuaternion) {
  78439. return;
  78440. }
  78441. var childImpostor = mesh.getPhysicsImpostor();
  78442. if (childImpostor) {
  78443. var parent = childImpostor.parent;
  78444. if (parent !== mainImpostor) {
  78445. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  78446. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  78447. if (childImpostor.physicsBody) {
  78448. _this.removePhysicsBody(childImpostor);
  78449. childImpostor.physicsBody = null;
  78450. }
  78451. childImpostor.parent = mainImpostor;
  78452. childImpostor.resetUpdateFlags();
  78453. 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));
  78454. //Add the mass of the children.
  78455. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  78456. }
  78457. }
  78458. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  78459. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  78460. };
  78461. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  78462. }
  78463. };
  78464. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  78465. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  78466. this.world.removeEventListener("preStep", impostor.beforeStep);
  78467. this.world.removeEventListener("postStep", impostor.afterStep);
  78468. this.world.remove(impostor.physicsBody);
  78469. };
  78470. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  78471. var mainBody = impostorJoint.mainImpostor.physicsBody;
  78472. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  78473. if (!mainBody || !connectedBody) {
  78474. return;
  78475. }
  78476. var constraint;
  78477. var jointData = impostorJoint.joint.jointData;
  78478. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  78479. var constraintData = {
  78480. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  78481. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  78482. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  78483. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  78484. maxForce: jointData.nativeParams.maxForce,
  78485. collideConnected: !!jointData.collision
  78486. };
  78487. switch (impostorJoint.joint.type) {
  78488. case BABYLON.PhysicsJoint.HingeJoint:
  78489. case BABYLON.PhysicsJoint.Hinge2Joint:
  78490. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  78491. break;
  78492. case BABYLON.PhysicsJoint.DistanceJoint:
  78493. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  78494. break;
  78495. case BABYLON.PhysicsJoint.SpringJoint:
  78496. var springData = jointData;
  78497. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  78498. restLength: springData.length,
  78499. stiffness: springData.stiffness,
  78500. damping: springData.damping,
  78501. localAnchorA: constraintData.pivotA,
  78502. localAnchorB: constraintData.pivotB
  78503. });
  78504. break;
  78505. case BABYLON.PhysicsJoint.LockJoint:
  78506. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  78507. break;
  78508. case BABYLON.PhysicsJoint.PointToPointJoint:
  78509. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  78510. default:
  78511. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  78512. break;
  78513. }
  78514. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  78515. constraint.collideConnected = !!jointData.collision;
  78516. impostorJoint.joint.physicsJoint = constraint;
  78517. //don't add spring as constraint, as it is not one.
  78518. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  78519. this.world.addConstraint(constraint);
  78520. }
  78521. else {
  78522. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  78523. constraint.applyForce();
  78524. });
  78525. }
  78526. };
  78527. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  78528. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  78529. };
  78530. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  78531. var index;
  78532. var mat;
  78533. for (index = 0; index < this._physicsMaterials.length; index++) {
  78534. mat = this._physicsMaterials[index];
  78535. if (mat.friction === friction && mat.restitution === restitution) {
  78536. return mat;
  78537. }
  78538. }
  78539. var currentMat = new this.BJSCANNON.Material(name);
  78540. currentMat.friction = friction;
  78541. currentMat.restitution = restitution;
  78542. this._physicsMaterials.push(currentMat);
  78543. return currentMat;
  78544. };
  78545. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  78546. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  78547. };
  78548. CannonJSPlugin.prototype._createShape = function (impostor) {
  78549. var object = impostor.object;
  78550. var returnValue;
  78551. var extendSize = impostor.getObjectExtendSize();
  78552. switch (impostor.type) {
  78553. case BABYLON.PhysicsImpostor.SphereImpostor:
  78554. var radiusX = extendSize.x;
  78555. var radiusY = extendSize.y;
  78556. var radiusZ = extendSize.z;
  78557. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  78558. break;
  78559. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  78560. case BABYLON.PhysicsImpostor.CylinderImpostor:
  78561. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  78562. break;
  78563. case BABYLON.PhysicsImpostor.BoxImpostor:
  78564. var box = extendSize.scale(0.5);
  78565. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  78566. break;
  78567. case BABYLON.PhysicsImpostor.PlaneImpostor:
  78568. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  78569. returnValue = new this.BJSCANNON.Plane();
  78570. break;
  78571. case BABYLON.PhysicsImpostor.MeshImpostor:
  78572. // should transform the vertex data to world coordinates!!
  78573. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  78574. var rawFaces = object.getIndices ? object.getIndices() : [];
  78575. if (!rawVerts)
  78576. return;
  78577. // get only scale! so the object could transform correctly.
  78578. var oldPosition = object.position.clone();
  78579. var oldRotation = object.rotation && object.rotation.clone();
  78580. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  78581. object.position.copyFromFloats(0, 0, 0);
  78582. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  78583. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  78584. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  78585. var transform = object.computeWorldMatrix(true);
  78586. // convert rawVerts to object space
  78587. var temp = new Array();
  78588. var index;
  78589. for (index = 0; index < rawVerts.length; index += 3) {
  78590. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  78591. }
  78592. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  78593. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  78594. //now set back the transformation!
  78595. object.position.copyFrom(oldPosition);
  78596. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  78597. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  78598. break;
  78599. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  78600. var oldPosition2 = object.position.clone();
  78601. var oldRotation2 = object.rotation && object.rotation.clone();
  78602. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  78603. object.position.copyFromFloats(0, 0, 0);
  78604. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  78605. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  78606. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  78607. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  78608. returnValue = this._createHeightmap(object);
  78609. object.position.copyFrom(oldPosition2);
  78610. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  78611. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  78612. object.computeWorldMatrix(true);
  78613. break;
  78614. case BABYLON.PhysicsImpostor.ParticleImpostor:
  78615. returnValue = new this.BJSCANNON.Particle();
  78616. break;
  78617. }
  78618. return returnValue;
  78619. };
  78620. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  78621. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  78622. var transform = object.computeWorldMatrix(true);
  78623. // convert rawVerts to object space
  78624. var temp = new Array();
  78625. var index;
  78626. for (index = 0; index < pos.length; index += 3) {
  78627. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  78628. }
  78629. pos = temp;
  78630. var matrix = new Array();
  78631. //For now pointDepth will not be used and will be automatically calculated.
  78632. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  78633. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  78634. var boundingInfo = object.getBoundingInfo();
  78635. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  78636. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  78637. var elementSize = dim * 2 / arraySize;
  78638. for (var i = 0; i < pos.length; i = i + 3) {
  78639. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  78640. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  78641. var y = -pos[i + 2] + minY;
  78642. if (!matrix[x]) {
  78643. matrix[x] = [];
  78644. }
  78645. if (!matrix[x][z]) {
  78646. matrix[x][z] = y;
  78647. }
  78648. matrix[x][z] = Math.max(y, matrix[x][z]);
  78649. }
  78650. for (var x = 0; x <= arraySize; ++x) {
  78651. if (!matrix[x]) {
  78652. var loc = 1;
  78653. while (!matrix[(x + loc) % arraySize]) {
  78654. loc++;
  78655. }
  78656. matrix[x] = matrix[(x + loc) % arraySize].slice();
  78657. //console.log("missing x", x);
  78658. }
  78659. for (var z = 0; z <= arraySize; ++z) {
  78660. if (!matrix[x][z]) {
  78661. var loc = 1;
  78662. var newValue;
  78663. while (newValue === undefined) {
  78664. newValue = matrix[x][(z + loc++) % arraySize];
  78665. }
  78666. matrix[x][z] = newValue;
  78667. }
  78668. }
  78669. }
  78670. var shape = new this.BJSCANNON.Heightfield(matrix, {
  78671. elementSize: elementSize
  78672. });
  78673. //For future reference, needed for body transformation
  78674. shape.minY = minY;
  78675. return shape;
  78676. };
  78677. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  78678. var object = impostor.object;
  78679. //make sure it is updated...
  78680. object.computeWorldMatrix && object.computeWorldMatrix(true);
  78681. // The delta between the mesh position and the mesh bounding box center
  78682. var bInfo = object.getBoundingInfo();
  78683. if (!bInfo)
  78684. return;
  78685. var center = impostor.getObjectCenter();
  78686. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  78687. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  78688. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  78689. this._tmpPosition.copyFrom(center);
  78690. var quaternion = object.rotationQuaternion;
  78691. if (!quaternion) {
  78692. return;
  78693. }
  78694. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  78695. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  78696. //-90 DEG in X, precalculated
  78697. quaternion = quaternion.multiply(this._minus90X);
  78698. //Invert! (Precalculated, 90 deg in X)
  78699. //No need to clone. this will never change.
  78700. impostor.setDeltaRotation(this._plus90X);
  78701. }
  78702. //If it is a heightfield, if should be centered.
  78703. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  78704. var mesh = object;
  78705. var boundingInfo = mesh.getBoundingInfo();
  78706. //calculate the correct body position:
  78707. var rotationQuaternion = mesh.rotationQuaternion;
  78708. mesh.rotationQuaternion = this._tmpUnityRotation;
  78709. mesh.computeWorldMatrix(true);
  78710. //get original center with no rotation
  78711. var c = center.clone();
  78712. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  78713. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  78714. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  78715. mesh.setPreTransformMatrix(p);
  78716. mesh.computeWorldMatrix(true);
  78717. //calculate the translation
  78718. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  78719. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  78720. //add it inverted to the delta
  78721. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  78722. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  78723. //rotation is back
  78724. mesh.rotationQuaternion = rotationQuaternion;
  78725. mesh.setPreTransformMatrix(oldPivot);
  78726. mesh.computeWorldMatrix(true);
  78727. }
  78728. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  78729. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  78730. //this._tmpPosition.copyFrom(object.position);
  78731. }
  78732. impostor.setDeltaPosition(this._tmpDeltaPosition);
  78733. //Now update the impostor object
  78734. impostor.physicsBody.position.copy(this._tmpPosition);
  78735. impostor.physicsBody.quaternion.copy(quaternion);
  78736. };
  78737. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  78738. impostor.object.position.copyFrom(impostor.physicsBody.position);
  78739. if (impostor.object.rotationQuaternion) {
  78740. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  78741. }
  78742. };
  78743. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  78744. impostor.physicsBody.position.copy(newPosition);
  78745. impostor.physicsBody.quaternion.copy(newRotation);
  78746. };
  78747. CannonJSPlugin.prototype.isSupported = function () {
  78748. return this.BJSCANNON !== undefined;
  78749. };
  78750. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  78751. impostor.physicsBody.velocity.copy(velocity);
  78752. };
  78753. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  78754. impostor.physicsBody.angularVelocity.copy(velocity);
  78755. };
  78756. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  78757. var v = impostor.physicsBody.velocity;
  78758. if (!v) {
  78759. return null;
  78760. }
  78761. return new BABYLON.Vector3(v.x, v.y, v.z);
  78762. };
  78763. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  78764. var v = impostor.physicsBody.angularVelocity;
  78765. if (!v) {
  78766. return null;
  78767. }
  78768. return new BABYLON.Vector3(v.x, v.y, v.z);
  78769. };
  78770. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  78771. impostor.physicsBody.mass = mass;
  78772. impostor.physicsBody.updateMassProperties();
  78773. };
  78774. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  78775. return impostor.physicsBody.mass;
  78776. };
  78777. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  78778. return impostor.physicsBody.material.friction;
  78779. };
  78780. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  78781. impostor.physicsBody.material.friction = friction;
  78782. };
  78783. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  78784. return impostor.physicsBody.material.restitution;
  78785. };
  78786. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  78787. impostor.physicsBody.material.restitution = restitution;
  78788. };
  78789. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  78790. impostor.physicsBody.sleep();
  78791. };
  78792. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  78793. impostor.physicsBody.wakeUp();
  78794. };
  78795. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  78796. joint.physicsJoint.distance = maxDistance;
  78797. };
  78798. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  78799. // if (!motorIndex) {
  78800. // joint.physicsJoint.enableMotor();
  78801. // }
  78802. // }
  78803. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  78804. // if (!motorIndex) {
  78805. // joint.physicsJoint.disableMotor();
  78806. // }
  78807. // }
  78808. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  78809. if (!motorIndex) {
  78810. joint.physicsJoint.enableMotor();
  78811. joint.physicsJoint.setMotorSpeed(speed);
  78812. if (maxForce) {
  78813. this.setLimit(joint, maxForce);
  78814. }
  78815. }
  78816. };
  78817. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  78818. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  78819. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  78820. };
  78821. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  78822. var body = impostor.physicsBody;
  78823. mesh.position.x = body.position.x;
  78824. mesh.position.y = body.position.y;
  78825. mesh.position.z = body.position.z;
  78826. if (mesh.rotationQuaternion) {
  78827. mesh.rotationQuaternion.x = body.quaternion.x;
  78828. mesh.rotationQuaternion.y = body.quaternion.y;
  78829. mesh.rotationQuaternion.z = body.quaternion.z;
  78830. mesh.rotationQuaternion.w = body.quaternion.w;
  78831. }
  78832. };
  78833. CannonJSPlugin.prototype.getRadius = function (impostor) {
  78834. var shape = impostor.physicsBody.shapes[0];
  78835. return shape.boundingSphereRadius;
  78836. };
  78837. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  78838. var shape = impostor.physicsBody.shapes[0];
  78839. result.x = shape.halfExtents.x * 2;
  78840. result.y = shape.halfExtents.y * 2;
  78841. result.z = shape.halfExtents.z * 2;
  78842. };
  78843. CannonJSPlugin.prototype.dispose = function () {
  78844. };
  78845. CannonJSPlugin.prototype._extendNamespace = function () {
  78846. //this will force cannon to execute at least one step when using interpolation
  78847. var step_tmp1 = new this.BJSCANNON.Vec3();
  78848. var Engine = this.BJSCANNON;
  78849. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  78850. maxSubSteps = maxSubSteps || 10;
  78851. timeSinceLastCalled = timeSinceLastCalled || 0;
  78852. if (timeSinceLastCalled === 0) {
  78853. this.internalStep(dt);
  78854. this.time += dt;
  78855. }
  78856. else {
  78857. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  78858. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  78859. var t0 = performance.now();
  78860. for (var i = 0; i !== internalSteps; i++) {
  78861. this.internalStep(dt);
  78862. if (performance.now() - t0 > dt * 1000) {
  78863. break;
  78864. }
  78865. }
  78866. this.time += timeSinceLastCalled;
  78867. var h = this.time % dt;
  78868. var h_div_dt = h / dt;
  78869. var interpvelo = step_tmp1;
  78870. var bodies = this.bodies;
  78871. for (var j = 0; j !== bodies.length; j++) {
  78872. var b = bodies[j];
  78873. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  78874. b.position.vsub(b.previousPosition, interpvelo);
  78875. interpvelo.scale(h_div_dt, interpvelo);
  78876. b.position.vadd(interpvelo, b.interpolatedPosition);
  78877. }
  78878. else {
  78879. b.interpolatedPosition.copy(b.position);
  78880. b.interpolatedQuaternion.copy(b.quaternion);
  78881. }
  78882. }
  78883. }
  78884. };
  78885. };
  78886. return CannonJSPlugin;
  78887. }());
  78888. BABYLON.CannonJSPlugin = CannonJSPlugin;
  78889. })(BABYLON || (BABYLON = {}));
  78890. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  78891. "use strict";
  78892. var BABYLON;
  78893. (function (BABYLON) {
  78894. var OimoJSPlugin = /** @class */ (function () {
  78895. function OimoJSPlugin(iterations) {
  78896. this.name = "OimoJSPlugin";
  78897. this._tmpImpostorsArray = [];
  78898. this._tmpPositionVector = BABYLON.Vector3.Zero();
  78899. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : ( true ? __webpack_require__(18) : undefined);
  78900. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  78901. this.world.worldscale(1);
  78902. this.world.clear();
  78903. //making sure no stats are calculated
  78904. this.world.isNoStat = true;
  78905. }
  78906. OimoJSPlugin.prototype.setGravity = function (gravity) {
  78907. this.world.gravity.copy(gravity);
  78908. };
  78909. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  78910. this.world.timeStep = timeStep;
  78911. };
  78912. OimoJSPlugin.prototype.getTimeStep = function () {
  78913. return this.world.timeStep;
  78914. };
  78915. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  78916. var _this = this;
  78917. impostors.forEach(function (impostor) {
  78918. impostor.beforeStep();
  78919. });
  78920. this.world.step();
  78921. impostors.forEach(function (impostor) {
  78922. impostor.afterStep();
  78923. //update the ordered impostors array
  78924. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  78925. });
  78926. //check for collisions
  78927. var contact = this.world.contacts;
  78928. while (contact !== null) {
  78929. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  78930. contact = contact.next;
  78931. continue;
  78932. }
  78933. //is this body colliding with any other? get the impostor
  78934. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  78935. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  78936. if (!mainImpostor || !collidingImpostor) {
  78937. contact = contact.next;
  78938. continue;
  78939. }
  78940. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  78941. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  78942. contact = contact.next;
  78943. }
  78944. };
  78945. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  78946. var mass = impostor.physicsBody.massInfo.mass;
  78947. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  78948. };
  78949. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  78950. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  78951. this.applyImpulse(impostor, force, contactPoint);
  78952. };
  78953. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  78954. var _this = this;
  78955. //parent-child relationship. Does this impostor has a parent impostor?
  78956. if (impostor.parent) {
  78957. if (impostor.physicsBody) {
  78958. this.removePhysicsBody(impostor);
  78959. //TODO is that needed?
  78960. impostor.forceUpdate();
  78961. }
  78962. return;
  78963. }
  78964. if (impostor.isBodyInitRequired()) {
  78965. var bodyConfig = {
  78966. name: impostor.uniqueId,
  78967. //Oimo must have mass, also for static objects.
  78968. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  78969. size: [],
  78970. type: [],
  78971. pos: [],
  78972. rot: [],
  78973. move: impostor.getParam("mass") !== 0,
  78974. //Supporting older versions of Oimo
  78975. world: this.world
  78976. };
  78977. var impostors = [impostor];
  78978. var addToArray = function (parent) {
  78979. if (!parent.getChildMeshes)
  78980. return;
  78981. parent.getChildMeshes().forEach(function (m) {
  78982. if (m.physicsImpostor) {
  78983. impostors.push(m.physicsImpostor);
  78984. //m.physicsImpostor._init();
  78985. }
  78986. });
  78987. };
  78988. addToArray(impostor.object);
  78989. var checkWithEpsilon_1 = function (value) {
  78990. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  78991. };
  78992. impostors.forEach(function (i) {
  78993. if (!impostor.object.rotationQuaternion) {
  78994. return;
  78995. }
  78996. //get the correct bounding box
  78997. var oldQuaternion = i.object.rotationQuaternion;
  78998. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  78999. x: impostor.object.rotationQuaternion.x,
  79000. y: impostor.object.rotationQuaternion.y,
  79001. z: impostor.object.rotationQuaternion.z,
  79002. s: impostor.object.rotationQuaternion.w
  79003. });
  79004. var extendSize = i.getObjectExtendSize();
  79005. if (i === impostor) {
  79006. var center = impostor.getObjectCenter();
  79007. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  79008. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  79009. //Can also use Array.prototype.push.apply
  79010. bodyConfig.pos.push(center.x);
  79011. bodyConfig.pos.push(center.y);
  79012. bodyConfig.pos.push(center.z);
  79013. //tmp solution
  79014. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  79015. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  79016. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  79017. }
  79018. else {
  79019. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  79020. bodyConfig.pos.push(localPosition.x);
  79021. bodyConfig.pos.push(localPosition.y);
  79022. bodyConfig.pos.push(localPosition.z);
  79023. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  79024. bodyConfig.rot.push(0);
  79025. bodyConfig.rot.push(0);
  79026. bodyConfig.rot.push(0);
  79027. }
  79028. // register mesh
  79029. switch (i.type) {
  79030. case BABYLON.PhysicsImpostor.ParticleImpostor:
  79031. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  79032. case BABYLON.PhysicsImpostor.SphereImpostor:
  79033. var radiusX = extendSize.x;
  79034. var radiusY = extendSize.y;
  79035. var radiusZ = extendSize.z;
  79036. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  79037. bodyConfig.type.push('sphere');
  79038. //due to the way oimo works with compounds, add 3 times
  79039. bodyConfig.size.push(size);
  79040. bodyConfig.size.push(size);
  79041. bodyConfig.size.push(size);
  79042. break;
  79043. case BABYLON.PhysicsImpostor.CylinderImpostor:
  79044. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  79045. var sizeY = checkWithEpsilon_1(extendSize.y);
  79046. bodyConfig.type.push('cylinder');
  79047. bodyConfig.size.push(sizeX);
  79048. bodyConfig.size.push(sizeY);
  79049. //due to the way oimo works with compounds, add one more value.
  79050. bodyConfig.size.push(sizeY);
  79051. break;
  79052. case BABYLON.PhysicsImpostor.PlaneImpostor:
  79053. case BABYLON.PhysicsImpostor.BoxImpostor:
  79054. default:
  79055. var sizeX = checkWithEpsilon_1(extendSize.x);
  79056. var sizeY = checkWithEpsilon_1(extendSize.y);
  79057. var sizeZ = checkWithEpsilon_1(extendSize.z);
  79058. bodyConfig.type.push('box');
  79059. bodyConfig.size.push(sizeX);
  79060. bodyConfig.size.push(sizeY);
  79061. bodyConfig.size.push(sizeZ);
  79062. break;
  79063. }
  79064. //actually not needed, but hey...
  79065. i.object.rotationQuaternion = oldQuaternion;
  79066. });
  79067. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  79068. }
  79069. else {
  79070. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  79071. }
  79072. impostor.setDeltaPosition(this._tmpPositionVector);
  79073. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  79074. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  79075. };
  79076. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  79077. //impostor.physicsBody.dispose();
  79078. //Same as : (older oimo versions)
  79079. this.world.removeRigidBody(impostor.physicsBody);
  79080. };
  79081. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  79082. var mainBody = impostorJoint.mainImpostor.physicsBody;
  79083. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  79084. if (!mainBody || !connectedBody) {
  79085. return;
  79086. }
  79087. var jointData = impostorJoint.joint.jointData;
  79088. var options = jointData.nativeParams || {};
  79089. var type;
  79090. var nativeJointData = {
  79091. body1: mainBody,
  79092. body2: connectedBody,
  79093. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  79094. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  79095. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  79096. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  79097. min: options.min,
  79098. max: options.max,
  79099. collision: options.collision || jointData.collision,
  79100. spring: options.spring,
  79101. //supporting older version of Oimo
  79102. world: this.world
  79103. };
  79104. switch (impostorJoint.joint.type) {
  79105. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  79106. type = "jointBall";
  79107. break;
  79108. case BABYLON.PhysicsJoint.SpringJoint:
  79109. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  79110. var springData = jointData;
  79111. nativeJointData.min = springData.length || nativeJointData.min;
  79112. //Max should also be set, just make sure it is at least min
  79113. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  79114. case BABYLON.PhysicsJoint.DistanceJoint:
  79115. type = "jointDistance";
  79116. nativeJointData.max = jointData.maxDistance;
  79117. break;
  79118. case BABYLON.PhysicsJoint.PrismaticJoint:
  79119. type = "jointPrisme";
  79120. break;
  79121. case BABYLON.PhysicsJoint.SliderJoint:
  79122. type = "jointSlide";
  79123. break;
  79124. case BABYLON.PhysicsJoint.WheelJoint:
  79125. type = "jointWheel";
  79126. break;
  79127. case BABYLON.PhysicsJoint.HingeJoint:
  79128. default:
  79129. type = "jointHinge";
  79130. break;
  79131. }
  79132. nativeJointData.type = type;
  79133. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  79134. };
  79135. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  79136. //Bug in Oimo prevents us from disposing a joint in the playground
  79137. //joint.joint.physicsJoint.dispose();
  79138. //So we will bruteforce it!
  79139. try {
  79140. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  79141. }
  79142. catch (e) {
  79143. BABYLON.Tools.Warn(e);
  79144. }
  79145. };
  79146. OimoJSPlugin.prototype.isSupported = function () {
  79147. return this.BJSOIMO !== undefined;
  79148. };
  79149. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  79150. if (!impostor.physicsBody.sleeping) {
  79151. //TODO check that
  79152. if (impostor.physicsBody.shapes.next) {
  79153. var parentShape = this._getLastShape(impostor.physicsBody);
  79154. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  79155. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  79156. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  79157. }
  79158. else {
  79159. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  79160. }
  79161. if (impostor.object.rotationQuaternion) {
  79162. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  79163. impostor.object.rotationQuaternion.normalize();
  79164. }
  79165. }
  79166. };
  79167. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  79168. var body = impostor.physicsBody;
  79169. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  79170. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  79171. body.syncShapes();
  79172. body.awake();
  79173. };
  79174. OimoJSPlugin.prototype._getLastShape = function (body) {
  79175. var lastShape = body.shapes;
  79176. while (lastShape.next) {
  79177. lastShape = lastShape.next;
  79178. }
  79179. return lastShape;
  79180. };
  79181. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  79182. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  79183. };
  79184. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  79185. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  79186. };
  79187. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  79188. var v = impostor.physicsBody.linearVelocity;
  79189. if (!v) {
  79190. return null;
  79191. }
  79192. return new BABYLON.Vector3(v.x, v.y, v.z);
  79193. };
  79194. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  79195. var v = impostor.physicsBody.angularVelocity;
  79196. if (!v) {
  79197. return null;
  79198. }
  79199. return new BABYLON.Vector3(v.x, v.y, v.z);
  79200. };
  79201. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  79202. var staticBody = mass === 0;
  79203. //this will actually set the body's density and not its mass.
  79204. //But this is how oimo treats the mass variable.
  79205. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  79206. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  79207. };
  79208. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  79209. return impostor.physicsBody.shapes.density;
  79210. };
  79211. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  79212. return impostor.physicsBody.shapes.friction;
  79213. };
  79214. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  79215. impostor.physicsBody.shapes.friction = friction;
  79216. };
  79217. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  79218. return impostor.physicsBody.shapes.restitution;
  79219. };
  79220. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  79221. impostor.physicsBody.shapes.restitution = restitution;
  79222. };
  79223. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  79224. impostor.physicsBody.sleep();
  79225. };
  79226. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  79227. impostor.physicsBody.awake();
  79228. };
  79229. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  79230. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  79231. if (minDistance !== void 0) {
  79232. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  79233. }
  79234. };
  79235. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  79236. //TODO separate rotational and transational motors.
  79237. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  79238. if (motor) {
  79239. motor.setMotor(speed, maxForce);
  79240. }
  79241. };
  79242. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  79243. //TODO separate rotational and transational motors.
  79244. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  79245. if (motor) {
  79246. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  79247. }
  79248. };
  79249. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  79250. var body = impostor.physicsBody;
  79251. mesh.position.x = body.position.x;
  79252. mesh.position.y = body.position.y;
  79253. mesh.position.z = body.position.z;
  79254. if (mesh.rotationQuaternion) {
  79255. mesh.rotationQuaternion.x = body.orientation.x;
  79256. mesh.rotationQuaternion.y = body.orientation.y;
  79257. mesh.rotationQuaternion.z = body.orientation.z;
  79258. mesh.rotationQuaternion.w = body.orientation.s;
  79259. }
  79260. };
  79261. OimoJSPlugin.prototype.getRadius = function (impostor) {
  79262. return impostor.physicsBody.shapes.radius;
  79263. };
  79264. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  79265. var shape = impostor.physicsBody.shapes;
  79266. result.x = shape.halfWidth * 2;
  79267. result.y = shape.halfHeight * 2;
  79268. result.z = shape.halfDepth * 2;
  79269. };
  79270. OimoJSPlugin.prototype.dispose = function () {
  79271. this.world.clear();
  79272. };
  79273. return OimoJSPlugin;
  79274. }());
  79275. BABYLON.OimoJSPlugin = OimoJSPlugin;
  79276. })(BABYLON || (BABYLON = {}));
  79277. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  79278. "use strict";
  79279. var BABYLON;
  79280. (function (BABYLON) {
  79281. /*
  79282. * Based on jsTGALoader - Javascript loader for TGA file
  79283. * By Vincent Thibault
  79284. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  79285. */
  79286. var TGATools = /** @class */ (function () {
  79287. function TGATools() {
  79288. }
  79289. TGATools.GetTGAHeader = function (data) {
  79290. var offset = 0;
  79291. var header = {
  79292. id_length: data[offset++],
  79293. colormap_type: data[offset++],
  79294. image_type: data[offset++],
  79295. colormap_index: data[offset++] | data[offset++] << 8,
  79296. colormap_length: data[offset++] | data[offset++] << 8,
  79297. colormap_size: data[offset++],
  79298. origin: [
  79299. data[offset++] | data[offset++] << 8,
  79300. data[offset++] | data[offset++] << 8
  79301. ],
  79302. width: data[offset++] | data[offset++] << 8,
  79303. height: data[offset++] | data[offset++] << 8,
  79304. pixel_size: data[offset++],
  79305. flags: data[offset++]
  79306. };
  79307. return header;
  79308. };
  79309. TGATools.UploadContent = function (gl, data) {
  79310. // Not enough data to contain header ?
  79311. if (data.length < 19) {
  79312. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  79313. return;
  79314. }
  79315. // Read Header
  79316. var offset = 18;
  79317. var header = TGATools.GetTGAHeader(data);
  79318. // Assume it's a valid Targa file.
  79319. if (header.id_length + offset > data.length) {
  79320. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  79321. return;
  79322. }
  79323. // Skip not needed data
  79324. offset += header.id_length;
  79325. var use_rle = false;
  79326. var use_pal = false;
  79327. var use_grey = false;
  79328. // Get some informations.
  79329. switch (header.image_type) {
  79330. case TGATools._TYPE_RLE_INDEXED:
  79331. use_rle = true;
  79332. case TGATools._TYPE_INDEXED:
  79333. use_pal = true;
  79334. break;
  79335. case TGATools._TYPE_RLE_RGB:
  79336. use_rle = true;
  79337. case TGATools._TYPE_RGB:
  79338. // use_rgb = true;
  79339. break;
  79340. case TGATools._TYPE_RLE_GREY:
  79341. use_rle = true;
  79342. case TGATools._TYPE_GREY:
  79343. use_grey = true;
  79344. break;
  79345. }
  79346. var pixel_data;
  79347. // var numAlphaBits = header.flags & 0xf;
  79348. var pixel_size = header.pixel_size >> 3;
  79349. var pixel_total = header.width * header.height * pixel_size;
  79350. // Read palettes
  79351. var palettes;
  79352. if (use_pal) {
  79353. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  79354. }
  79355. // Read LRE
  79356. if (use_rle) {
  79357. pixel_data = new Uint8Array(pixel_total);
  79358. var c, count, i;
  79359. var localOffset = 0;
  79360. var pixels = new Uint8Array(pixel_size);
  79361. while (offset < pixel_total && localOffset < pixel_total) {
  79362. c = data[offset++];
  79363. count = (c & 0x7f) + 1;
  79364. // RLE pixels
  79365. if (c & 0x80) {
  79366. // Bind pixel tmp array
  79367. for (i = 0; i < pixel_size; ++i) {
  79368. pixels[i] = data[offset++];
  79369. }
  79370. // Copy pixel array
  79371. for (i = 0; i < count; ++i) {
  79372. pixel_data.set(pixels, localOffset + i * pixel_size);
  79373. }
  79374. localOffset += pixel_size * count;
  79375. }
  79376. else {
  79377. count *= pixel_size;
  79378. for (i = 0; i < count; ++i) {
  79379. pixel_data[localOffset + i] = data[offset++];
  79380. }
  79381. localOffset += count;
  79382. }
  79383. }
  79384. }
  79385. else {
  79386. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  79387. }
  79388. // Load to texture
  79389. var x_start, y_start, x_step, y_step, y_end, x_end;
  79390. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  79391. default:
  79392. case TGATools._ORIGIN_UL:
  79393. x_start = 0;
  79394. x_step = 1;
  79395. x_end = header.width;
  79396. y_start = 0;
  79397. y_step = 1;
  79398. y_end = header.height;
  79399. break;
  79400. case TGATools._ORIGIN_BL:
  79401. x_start = 0;
  79402. x_step = 1;
  79403. x_end = header.width;
  79404. y_start = header.height - 1;
  79405. y_step = -1;
  79406. y_end = -1;
  79407. break;
  79408. case TGATools._ORIGIN_UR:
  79409. x_start = header.width - 1;
  79410. x_step = -1;
  79411. x_end = -1;
  79412. y_start = 0;
  79413. y_step = 1;
  79414. y_end = header.height;
  79415. break;
  79416. case TGATools._ORIGIN_BR:
  79417. x_start = header.width - 1;
  79418. x_step = -1;
  79419. x_end = -1;
  79420. y_start = header.height - 1;
  79421. y_step = -1;
  79422. y_end = -1;
  79423. break;
  79424. }
  79425. // Load the specify method
  79426. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  79427. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  79428. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  79429. };
  79430. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79431. var image = pixel_data, colormap = palettes;
  79432. var width = header.width, height = header.height;
  79433. var color, i = 0, x, y;
  79434. var imageData = new Uint8Array(width * height * 4);
  79435. for (y = y_start; y !== y_end; y += y_step) {
  79436. for (x = x_start; x !== x_end; x += x_step, i++) {
  79437. color = image[i];
  79438. imageData[(x + width * y) * 4 + 3] = 255;
  79439. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  79440. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  79441. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  79442. }
  79443. }
  79444. return imageData;
  79445. };
  79446. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79447. var image = pixel_data;
  79448. var width = header.width, height = header.height;
  79449. var color, i = 0, x, y;
  79450. var imageData = new Uint8Array(width * height * 4);
  79451. for (y = y_start; y !== y_end; y += y_step) {
  79452. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  79453. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  79454. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  79455. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  79456. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  79457. imageData[(x + width * y) * 4 + 0] = r;
  79458. imageData[(x + width * y) * 4 + 1] = g;
  79459. imageData[(x + width * y) * 4 + 2] = b;
  79460. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  79461. }
  79462. }
  79463. return imageData;
  79464. };
  79465. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79466. var image = pixel_data;
  79467. var width = header.width, height = header.height;
  79468. var i = 0, x, y;
  79469. var imageData = new Uint8Array(width * height * 4);
  79470. for (y = y_start; y !== y_end; y += y_step) {
  79471. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  79472. imageData[(x + width * y) * 4 + 3] = 255;
  79473. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79474. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  79475. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  79476. }
  79477. }
  79478. return imageData;
  79479. };
  79480. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79481. var image = pixel_data;
  79482. var width = header.width, height = header.height;
  79483. var i = 0, x, y;
  79484. var imageData = new Uint8Array(width * height * 4);
  79485. for (y = y_start; y !== y_end; y += y_step) {
  79486. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  79487. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79488. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  79489. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  79490. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  79491. }
  79492. }
  79493. return imageData;
  79494. };
  79495. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79496. var image = pixel_data;
  79497. var width = header.width, height = header.height;
  79498. var color, i = 0, x, y;
  79499. var imageData = new Uint8Array(width * height * 4);
  79500. for (y = y_start; y !== y_end; y += y_step) {
  79501. for (x = x_start; x !== x_end; x += x_step, i++) {
  79502. color = image[i];
  79503. imageData[(x + width * y) * 4 + 0] = color;
  79504. imageData[(x + width * y) * 4 + 1] = color;
  79505. imageData[(x + width * y) * 4 + 2] = color;
  79506. imageData[(x + width * y) * 4 + 3] = 255;
  79507. }
  79508. }
  79509. return imageData;
  79510. };
  79511. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79512. var image = pixel_data;
  79513. var width = header.width, height = header.height;
  79514. var i = 0, x, y;
  79515. var imageData = new Uint8Array(width * height * 4);
  79516. for (y = y_start; y !== y_end; y += y_step) {
  79517. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  79518. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  79519. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  79520. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79521. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  79522. }
  79523. }
  79524. return imageData;
  79525. };
  79526. //private static _TYPE_NO_DATA = 0;
  79527. TGATools._TYPE_INDEXED = 1;
  79528. TGATools._TYPE_RGB = 2;
  79529. TGATools._TYPE_GREY = 3;
  79530. TGATools._TYPE_RLE_INDEXED = 9;
  79531. TGATools._TYPE_RLE_RGB = 10;
  79532. TGATools._TYPE_RLE_GREY = 11;
  79533. TGATools._ORIGIN_MASK = 0x30;
  79534. TGATools._ORIGIN_SHIFT = 0x04;
  79535. TGATools._ORIGIN_BL = 0x00;
  79536. TGATools._ORIGIN_BR = 0x01;
  79537. TGATools._ORIGIN_UL = 0x02;
  79538. TGATools._ORIGIN_UR = 0x03;
  79539. return TGATools;
  79540. }());
  79541. BABYLON.TGATools = TGATools;
  79542. })(BABYLON || (BABYLON = {}));
  79543. //# sourceMappingURL=babylon.tga.js.map
  79544. "use strict";
  79545. var BABYLON;
  79546. (function (BABYLON) {
  79547. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  79548. // All values and structures referenced from:
  79549. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  79550. var DDS_MAGIC = 0x20534444;
  79551. var
  79552. //DDSD_CAPS = 0x1,
  79553. //DDSD_HEIGHT = 0x2,
  79554. //DDSD_WIDTH = 0x4,
  79555. //DDSD_PITCH = 0x8,
  79556. //DDSD_PIXELFORMAT = 0x1000,
  79557. DDSD_MIPMAPCOUNT = 0x20000;
  79558. //DDSD_LINEARSIZE = 0x80000,
  79559. //DDSD_DEPTH = 0x800000;
  79560. // var DDSCAPS_COMPLEX = 0x8,
  79561. // DDSCAPS_MIPMAP = 0x400000,
  79562. // DDSCAPS_TEXTURE = 0x1000;
  79563. var DDSCAPS2_CUBEMAP = 0x200;
  79564. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  79565. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  79566. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  79567. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  79568. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  79569. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  79570. // DDSCAPS2_VOLUME = 0x200000;
  79571. var
  79572. //DDPF_ALPHAPIXELS = 0x1,
  79573. //DDPF_ALPHA = 0x2,
  79574. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  79575. //DDPF_YUV = 0x200,
  79576. DDPF_LUMINANCE = 0x20000;
  79577. function FourCCToInt32(value) {
  79578. return value.charCodeAt(0) +
  79579. (value.charCodeAt(1) << 8) +
  79580. (value.charCodeAt(2) << 16) +
  79581. (value.charCodeAt(3) << 24);
  79582. }
  79583. function Int32ToFourCC(value) {
  79584. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  79585. }
  79586. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  79587. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  79588. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  79589. var FOURCC_DX10 = FourCCToInt32("DX10");
  79590. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  79591. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  79592. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  79593. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  79594. var headerLengthInt = 31; // The header length in 32 bit ints
  79595. // Offsets into the header array
  79596. var off_magic = 0;
  79597. var off_size = 1;
  79598. var off_flags = 2;
  79599. var off_height = 3;
  79600. var off_width = 4;
  79601. var off_mipmapCount = 7;
  79602. var off_pfFlags = 20;
  79603. var off_pfFourCC = 21;
  79604. var off_RGBbpp = 22;
  79605. var off_RMask = 23;
  79606. var off_GMask = 24;
  79607. var off_BMask = 25;
  79608. var off_AMask = 26;
  79609. // var off_caps1 = 27;
  79610. var off_caps2 = 28;
  79611. // var off_caps3 = 29;
  79612. // var off_caps4 = 30;
  79613. var off_dxgiFormat = 32;
  79614. ;
  79615. var DDSTools = /** @class */ (function () {
  79616. function DDSTools() {
  79617. }
  79618. DDSTools.GetDDSInfo = function (arrayBuffer) {
  79619. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  79620. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  79621. var mipmapCount = 1;
  79622. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  79623. mipmapCount = Math.max(1, header[off_mipmapCount]);
  79624. }
  79625. var fourCC = header[off_pfFourCC];
  79626. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  79627. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79628. switch (fourCC) {
  79629. case FOURCC_D3DFMT_R16G16B16A16F:
  79630. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79631. break;
  79632. case FOURCC_D3DFMT_R32G32B32A32F:
  79633. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79634. break;
  79635. case FOURCC_DX10:
  79636. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  79637. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79638. break;
  79639. }
  79640. }
  79641. return {
  79642. width: header[off_width],
  79643. height: header[off_height],
  79644. mipmapCount: mipmapCount,
  79645. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  79646. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  79647. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  79648. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  79649. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  79650. dxgiFormat: dxgiFormat,
  79651. textureType: textureType
  79652. };
  79653. };
  79654. DDSTools._ToHalfFloat = function (value) {
  79655. if (!DDSTools._FloatView) {
  79656. DDSTools._FloatView = new Float32Array(1);
  79657. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  79658. }
  79659. DDSTools._FloatView[0] = value;
  79660. var x = DDSTools._Int32View[0];
  79661. var bits = (x >> 16) & 0x8000; /* Get the sign */
  79662. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  79663. var e = (x >> 23) & 0xff; /* Using int is faster here */
  79664. /* If zero, or denormal, or exponent underflows too much for a denormal
  79665. * half, return signed zero. */
  79666. if (e < 103) {
  79667. return bits;
  79668. }
  79669. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  79670. if (e > 142) {
  79671. bits |= 0x7c00;
  79672. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  79673. * not Inf, so make sure we set one mantissa bit too. */
  79674. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  79675. return bits;
  79676. }
  79677. /* If exponent underflows but not too much, return a denormal */
  79678. if (e < 113) {
  79679. m |= 0x0800;
  79680. /* Extra rounding may overflow and set mantissa to 0 and exponent
  79681. * to 1, which is OK. */
  79682. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  79683. return bits;
  79684. }
  79685. bits |= ((e - 112) << 10) | (m >> 1);
  79686. bits += m & 1;
  79687. return bits;
  79688. };
  79689. DDSTools._FromHalfFloat = function (value) {
  79690. var s = (value & 0x8000) >> 15;
  79691. var e = (value & 0x7C00) >> 10;
  79692. var f = value & 0x03FF;
  79693. if (e === 0) {
  79694. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  79695. }
  79696. else if (e == 0x1F) {
  79697. return f ? NaN : ((s ? -1 : 1) * Infinity);
  79698. }
  79699. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  79700. };
  79701. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79702. var destArray = new Float32Array(dataLength);
  79703. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79704. var index = 0;
  79705. for (var y = 0; y < height; y++) {
  79706. for (var x = 0; x < width; x++) {
  79707. var srcPos = (x + y * width) * 4;
  79708. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  79709. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  79710. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  79711. if (DDSTools.StoreLODInAlphaChannel) {
  79712. destArray[index + 3] = lod;
  79713. }
  79714. else {
  79715. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  79716. }
  79717. index += 4;
  79718. }
  79719. }
  79720. return destArray;
  79721. };
  79722. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79723. if (DDSTools.StoreLODInAlphaChannel) {
  79724. var destArray = new Uint16Array(dataLength);
  79725. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79726. var index = 0;
  79727. for (var y = 0; y < height; y++) {
  79728. for (var x = 0; x < width; x++) {
  79729. var srcPos = (x + y * width) * 4;
  79730. destArray[index] = srcData[srcPos];
  79731. destArray[index + 1] = srcData[srcPos + 1];
  79732. destArray[index + 2] = srcData[srcPos + 2];
  79733. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  79734. index += 4;
  79735. }
  79736. }
  79737. return destArray;
  79738. }
  79739. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  79740. };
  79741. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79742. if (DDSTools.StoreLODInAlphaChannel) {
  79743. var destArray = new Float32Array(dataLength);
  79744. var srcData = new Float32Array(arrayBuffer, dataOffset);
  79745. var index = 0;
  79746. for (var y = 0; y < height; y++) {
  79747. for (var x = 0; x < width; x++) {
  79748. var srcPos = (x + y * width) * 4;
  79749. destArray[index] = srcData[srcPos];
  79750. destArray[index + 1] = srcData[srcPos + 1];
  79751. destArray[index + 2] = srcData[srcPos + 2];
  79752. destArray[index + 3] = lod;
  79753. index += 4;
  79754. }
  79755. }
  79756. return destArray;
  79757. }
  79758. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  79759. };
  79760. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79761. var destArray = new Uint8Array(dataLength);
  79762. var srcData = new Float32Array(arrayBuffer, dataOffset);
  79763. var index = 0;
  79764. for (var y = 0; y < height; y++) {
  79765. for (var x = 0; x < width; x++) {
  79766. var srcPos = (x + y * width) * 4;
  79767. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  79768. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  79769. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  79770. if (DDSTools.StoreLODInAlphaChannel) {
  79771. destArray[index + 3] = lod;
  79772. }
  79773. else {
  79774. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  79775. }
  79776. index += 4;
  79777. }
  79778. }
  79779. return destArray;
  79780. };
  79781. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79782. var destArray = new Uint8Array(dataLength);
  79783. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79784. var index = 0;
  79785. for (var y = 0; y < height; y++) {
  79786. for (var x = 0; x < width; x++) {
  79787. var srcPos = (x + y * width) * 4;
  79788. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  79789. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  79790. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  79791. if (DDSTools.StoreLODInAlphaChannel) {
  79792. destArray[index + 3] = lod;
  79793. }
  79794. else {
  79795. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  79796. }
  79797. index += 4;
  79798. }
  79799. }
  79800. return destArray;
  79801. };
  79802. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  79803. var byteArray = new Uint8Array(dataLength);
  79804. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79805. var index = 0;
  79806. for (var y = 0; y < height; y++) {
  79807. for (var x = 0; x < width; x++) {
  79808. var srcPos = (x + y * width) * 4;
  79809. byteArray[index] = srcData[srcPos + rOffset];
  79810. byteArray[index + 1] = srcData[srcPos + gOffset];
  79811. byteArray[index + 2] = srcData[srcPos + bOffset];
  79812. byteArray[index + 3] = srcData[srcPos + aOffset];
  79813. index += 4;
  79814. }
  79815. }
  79816. return byteArray;
  79817. };
  79818. DDSTools._ExtractLongWordOrder = function (value) {
  79819. if (value === 0 || value === 255 || value === -16777216) {
  79820. return 0;
  79821. }
  79822. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  79823. };
  79824. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  79825. var byteArray = new Uint8Array(dataLength);
  79826. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79827. var index = 0;
  79828. for (var y = 0; y < height; y++) {
  79829. for (var x = 0; x < width; x++) {
  79830. var srcPos = (x + y * width) * 3;
  79831. byteArray[index] = srcData[srcPos + rOffset];
  79832. byteArray[index + 1] = srcData[srcPos + gOffset];
  79833. byteArray[index + 2] = srcData[srcPos + bOffset];
  79834. index += 3;
  79835. }
  79836. }
  79837. return byteArray;
  79838. };
  79839. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  79840. var byteArray = new Uint8Array(dataLength);
  79841. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79842. var index = 0;
  79843. for (var y = 0; y < height; y++) {
  79844. for (var x = 0; x < width; x++) {
  79845. var srcPos = (x + y * width);
  79846. byteArray[index] = srcData[srcPos];
  79847. index++;
  79848. }
  79849. }
  79850. return byteArray;
  79851. };
  79852. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  79853. if (lodIndex === void 0) { lodIndex = -1; }
  79854. var ext = engine.getCaps().s3tc;
  79855. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  79856. var fourCC, width, height, dataLength = 0, dataOffset;
  79857. var byteArray, mipmapCount, mip;
  79858. var internalFormat = 0;
  79859. var format = 0;
  79860. var blockBytes = 1;
  79861. if (header[off_magic] !== DDS_MAGIC) {
  79862. BABYLON.Tools.Error("Invalid magic number in DDS header");
  79863. return;
  79864. }
  79865. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  79866. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  79867. return;
  79868. }
  79869. if (info.isCompressed && !ext) {
  79870. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  79871. return;
  79872. }
  79873. var bpp = header[off_RGBbpp];
  79874. dataOffset = header[off_size] + 4;
  79875. var computeFormats = false;
  79876. if (info.isFourCC) {
  79877. fourCC = header[off_pfFourCC];
  79878. switch (fourCC) {
  79879. case FOURCC_DXT1:
  79880. blockBytes = 8;
  79881. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  79882. break;
  79883. case FOURCC_DXT3:
  79884. blockBytes = 16;
  79885. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  79886. break;
  79887. case FOURCC_DXT5:
  79888. blockBytes = 16;
  79889. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  79890. break;
  79891. case FOURCC_D3DFMT_R16G16B16A16F:
  79892. computeFormats = true;
  79893. break;
  79894. case FOURCC_D3DFMT_R32G32B32A32F:
  79895. computeFormats = true;
  79896. break;
  79897. case FOURCC_DX10:
  79898. // There is an additionnal header so dataOffset need to be changed
  79899. dataOffset += 5 * 4; // 5 uints
  79900. var supported = false;
  79901. switch (info.dxgiFormat) {
  79902. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  79903. computeFormats = true;
  79904. supported = true;
  79905. break;
  79906. case DXGI_FORMAT_B8G8R8X8_UNORM:
  79907. info.isRGB = true;
  79908. info.isFourCC = false;
  79909. bpp = 32;
  79910. supported = true;
  79911. break;
  79912. }
  79913. if (supported) {
  79914. break;
  79915. }
  79916. default:
  79917. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  79918. return;
  79919. }
  79920. }
  79921. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  79922. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  79923. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  79924. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  79925. if (computeFormats) {
  79926. format = engine._getWebGLTextureType(info.textureType);
  79927. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79928. }
  79929. mipmapCount = 1;
  79930. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  79931. mipmapCount = Math.max(1, header[off_mipmapCount]);
  79932. }
  79933. for (var face = 0; face < faces; face++) {
  79934. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  79935. width = header[off_width];
  79936. height = header[off_height];
  79937. for (mip = 0; mip < mipmapCount; ++mip) {
  79938. if (lodIndex === -1 || lodIndex === mip) {
  79939. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  79940. var i = (lodIndex === -1) ? mip : 0;
  79941. if (!info.isCompressed && info.isFourCC) {
  79942. dataLength = width * height * 4;
  79943. var floatArray = null;
  79944. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  79945. if (bpp === 128) {
  79946. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79947. }
  79948. else if (bpp === 64) {
  79949. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79950. }
  79951. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79952. format = engine._getWebGLTextureType(info.textureType);
  79953. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79954. }
  79955. else {
  79956. if (bpp === 128) {
  79957. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79958. }
  79959. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  79960. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79961. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79962. format = engine._getWebGLTextureType(info.textureType);
  79963. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79964. }
  79965. else {
  79966. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79967. }
  79968. }
  79969. if (floatArray) {
  79970. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  79971. }
  79972. }
  79973. else if (info.isRGB) {
  79974. if (bpp === 24) {
  79975. dataLength = width * height * 3;
  79976. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  79977. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  79978. }
  79979. else {
  79980. dataLength = width * height * 4;
  79981. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  79982. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  79983. }
  79984. }
  79985. else if (info.isLuminance) {
  79986. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  79987. var unpaddedRowSize = width;
  79988. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  79989. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  79990. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  79991. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  79992. }
  79993. else {
  79994. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  79995. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  79996. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  79997. }
  79998. }
  79999. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  80000. width *= 0.5;
  80001. height *= 0.5;
  80002. width = Math.max(1.0, width);
  80003. height = Math.max(1.0, height);
  80004. }
  80005. if (currentFace !== undefined) {
  80006. // Loading a single face
  80007. break;
  80008. }
  80009. }
  80010. };
  80011. DDSTools.StoreLODInAlphaChannel = false;
  80012. return DDSTools;
  80013. }());
  80014. BABYLON.DDSTools = DDSTools;
  80015. })(BABYLON || (BABYLON = {}));
  80016. //# sourceMappingURL=babylon.dds.js.map
  80017. "use strict";
  80018. var BABYLON;
  80019. (function (BABYLON) {
  80020. /**
  80021. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  80022. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  80023. */
  80024. var KhronosTextureContainer = /** @class */ (function () {
  80025. /**
  80026. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  80027. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  80028. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  80029. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  80030. */
  80031. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  80032. this.arrayBuffer = arrayBuffer;
  80033. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  80034. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  80035. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  80036. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  80037. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  80038. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  80039. BABYLON.Tools.Error("texture missing KTX identifier");
  80040. return;
  80041. }
  80042. // load the reset of the header in native 32 bit int
  80043. var header = new Int32Array(this.arrayBuffer, 12, 13);
  80044. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  80045. var oppositeEndianess = header[0] === 0x01020304;
  80046. // read all the header elements in order they exist in the file, without modification (sans endainness)
  80047. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  80048. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  80049. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  80050. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  80051. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  80052. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  80053. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  80054. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  80055. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  80056. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  80057. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  80058. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  80059. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  80060. if (this.glType !== 0) {
  80061. BABYLON.Tools.Error("only compressed formats currently supported");
  80062. return;
  80063. }
  80064. else {
  80065. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  80066. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  80067. }
  80068. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  80069. BABYLON.Tools.Error("only 2D textures currently supported");
  80070. return;
  80071. }
  80072. if (this.numberOfArrayElements !== 0) {
  80073. BABYLON.Tools.Error("texture arrays not currently supported");
  80074. return;
  80075. }
  80076. if (this.numberOfFaces !== facesExpected) {
  80077. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  80078. return;
  80079. }
  80080. // we now have a completely validated file, so could use existence of loadType as success
  80081. // would need to make this more elaborate & adjust checks above to support more than one load type
  80082. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  80083. }
  80084. // not as fast hardware based, but will probably never need to use
  80085. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  80086. return ((val & 0xFF) << 24)
  80087. | ((val & 0xFF00) << 8)
  80088. | ((val >> 8) & 0xFF00)
  80089. | ((val >> 24) & 0xFF);
  80090. };
  80091. /**
  80092. * It is assumed that the texture has already been created & is currently bound
  80093. */
  80094. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  80095. switch (this.loadType) {
  80096. case KhronosTextureContainer.COMPRESSED_2D:
  80097. this._upload2DCompressedLevels(gl, loadMipmaps);
  80098. break;
  80099. case KhronosTextureContainer.TEX_2D:
  80100. case KhronosTextureContainer.COMPRESSED_3D:
  80101. case KhronosTextureContainer.TEX_3D:
  80102. }
  80103. };
  80104. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  80105. // initialize width & height for level 1
  80106. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  80107. var width = this.pixelWidth;
  80108. var height = this.pixelHeight;
  80109. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  80110. for (var level = 0; level < mipmapCount; level++) {
  80111. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  80112. for (var face = 0; face < this.numberOfFaces; face++) {
  80113. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  80114. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  80115. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  80116. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  80117. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  80118. }
  80119. width = Math.max(1.0, width * 0.5);
  80120. height = Math.max(1.0, height * 0.5);
  80121. }
  80122. };
  80123. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  80124. // load types
  80125. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  80126. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  80127. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  80128. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  80129. return KhronosTextureContainer;
  80130. }());
  80131. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  80132. })(BABYLON || (BABYLON = {}));
  80133. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  80134. "use strict";
  80135. var BABYLON;
  80136. (function (BABYLON) {
  80137. var Debug = /** @class */ (function () {
  80138. function Debug() {
  80139. }
  80140. Debug.AxesViewer = /** @class */ (function () {
  80141. function AxesViewer(scene, scaleLines) {
  80142. if (scaleLines === void 0) { scaleLines = 1; }
  80143. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80144. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80145. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80146. this.scaleLines = 1;
  80147. this.scaleLines = scaleLines;
  80148. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  80149. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  80150. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  80151. this._xmesh.renderingGroupId = 2;
  80152. this._ymesh.renderingGroupId = 2;
  80153. this._zmesh.renderingGroupId = 2;
  80154. this._xmesh.material.checkReadyOnlyOnce = true;
  80155. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  80156. this._ymesh.material.checkReadyOnlyOnce = true;
  80157. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  80158. this._zmesh.material.checkReadyOnlyOnce = true;
  80159. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  80160. this.scene = scene;
  80161. }
  80162. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  80163. var scaleLines = this.scaleLines;
  80164. if (this._xmesh) {
  80165. this._xmesh.position.copyFrom(position);
  80166. }
  80167. if (this._ymesh) {
  80168. this._ymesh.position.copyFrom(position);
  80169. }
  80170. if (this._zmesh) {
  80171. this._zmesh.position.copyFrom(position);
  80172. }
  80173. var point2 = this._xline[1];
  80174. point2.x = xaxis.x * scaleLines;
  80175. point2.y = xaxis.y * scaleLines;
  80176. point2.z = xaxis.z * scaleLines;
  80177. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  80178. point2 = this._yline[1];
  80179. point2.x = yaxis.x * scaleLines;
  80180. point2.y = yaxis.y * scaleLines;
  80181. point2.z = yaxis.z * scaleLines;
  80182. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  80183. point2 = this._zline[1];
  80184. point2.x = zaxis.x * scaleLines;
  80185. point2.y = zaxis.y * scaleLines;
  80186. point2.z = zaxis.z * scaleLines;
  80187. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  80188. };
  80189. AxesViewer.prototype.dispose = function () {
  80190. if (this._xmesh) {
  80191. this._xmesh.dispose();
  80192. }
  80193. if (this._ymesh) {
  80194. this._ymesh.dispose();
  80195. }
  80196. if (this._zmesh) {
  80197. this._zmesh.dispose();
  80198. }
  80199. this._xmesh = null;
  80200. this._ymesh = null;
  80201. this._zmesh = null;
  80202. this.scene = null;
  80203. };
  80204. return AxesViewer;
  80205. }());
  80206. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  80207. __extends(BoneAxesViewer, _super);
  80208. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  80209. if (scaleLines === void 0) { scaleLines = 1; }
  80210. var _this = _super.call(this, scene, scaleLines) || this;
  80211. _this.pos = BABYLON.Vector3.Zero();
  80212. _this.xaxis = BABYLON.Vector3.Zero();
  80213. _this.yaxis = BABYLON.Vector3.Zero();
  80214. _this.zaxis = BABYLON.Vector3.Zero();
  80215. _this.mesh = mesh;
  80216. _this.bone = bone;
  80217. return _this;
  80218. }
  80219. BoneAxesViewer.prototype.update = function () {
  80220. if (!this.mesh || !this.bone) {
  80221. return;
  80222. }
  80223. var bone = this.bone;
  80224. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  80225. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  80226. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  80227. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  80228. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  80229. };
  80230. BoneAxesViewer.prototype.dispose = function () {
  80231. if (this.mesh) {
  80232. this.mesh = null;
  80233. this.bone = null;
  80234. _super.prototype.dispose.call(this);
  80235. }
  80236. };
  80237. return BoneAxesViewer;
  80238. }(Debug.AxesViewer));
  80239. Debug.PhysicsViewer = /** @class */ (function () {
  80240. function PhysicsViewer(scene) {
  80241. this._impostors = [];
  80242. this._meshes = [];
  80243. this._numMeshes = 0;
  80244. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80245. var physicEngine = this._scene.getPhysicsEngine();
  80246. if (physicEngine) {
  80247. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  80248. }
  80249. }
  80250. PhysicsViewer.prototype._updateDebugMeshes = function () {
  80251. var plugin = this._physicsEnginePlugin;
  80252. for (var i = 0; i < this._numMeshes; i++) {
  80253. var impostor = this._impostors[i];
  80254. if (!impostor) {
  80255. continue;
  80256. }
  80257. if (impostor.isDisposed) {
  80258. this.hideImpostor(this._impostors[i--]);
  80259. }
  80260. else {
  80261. var mesh = this._meshes[i];
  80262. if (mesh && plugin) {
  80263. plugin.syncMeshWithImpostor(mesh, impostor);
  80264. }
  80265. }
  80266. }
  80267. };
  80268. PhysicsViewer.prototype.showImpostor = function (impostor) {
  80269. if (!this._scene) {
  80270. return;
  80271. }
  80272. for (var i = 0; i < this._numMeshes; i++) {
  80273. if (this._impostors[i] == impostor) {
  80274. return;
  80275. }
  80276. }
  80277. var debugMesh = this._getDebugMesh(impostor, this._scene);
  80278. if (debugMesh) {
  80279. this._impostors[this._numMeshes] = impostor;
  80280. this._meshes[this._numMeshes] = debugMesh;
  80281. if (this._numMeshes === 0) {
  80282. this._renderFunction = this._updateDebugMeshes.bind(this);
  80283. this._scene.registerBeforeRender(this._renderFunction);
  80284. }
  80285. this._numMeshes++;
  80286. }
  80287. };
  80288. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  80289. if (!impostor || !this._scene) {
  80290. return;
  80291. }
  80292. var removed = false;
  80293. for (var i = 0; i < this._numMeshes; i++) {
  80294. if (this._impostors[i] == impostor) {
  80295. var mesh = this._meshes[i];
  80296. if (!mesh) {
  80297. continue;
  80298. }
  80299. this._scene.removeMesh(mesh);
  80300. mesh.dispose();
  80301. this._numMeshes--;
  80302. if (this._numMeshes > 0) {
  80303. this._meshes[i] = this._meshes[this._numMeshes];
  80304. this._impostors[i] = this._impostors[this._numMeshes];
  80305. this._meshes[this._numMeshes] = null;
  80306. this._impostors[this._numMeshes] = null;
  80307. }
  80308. else {
  80309. this._meshes[0] = null;
  80310. this._impostors[0] = null;
  80311. }
  80312. removed = true;
  80313. break;
  80314. }
  80315. }
  80316. if (removed && this._numMeshes === 0) {
  80317. this._scene.unregisterBeforeRender(this._renderFunction);
  80318. }
  80319. };
  80320. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  80321. if (!this._debugMaterial) {
  80322. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  80323. this._debugMaterial.wireframe = true;
  80324. }
  80325. return this._debugMaterial;
  80326. };
  80327. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  80328. if (!this._debugBoxMesh) {
  80329. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  80330. this._debugBoxMesh.renderingGroupId = 1;
  80331. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  80332. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  80333. scene.removeMesh(this._debugBoxMesh);
  80334. }
  80335. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  80336. };
  80337. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  80338. if (!this._debugSphereMesh) {
  80339. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  80340. this._debugSphereMesh.renderingGroupId = 1;
  80341. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  80342. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  80343. scene.removeMesh(this._debugSphereMesh);
  80344. }
  80345. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  80346. };
  80347. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  80348. var mesh = null;
  80349. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  80350. mesh = this._getDebugBoxMesh(scene);
  80351. impostor.getBoxSizeToRef(mesh.scaling);
  80352. }
  80353. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  80354. mesh = this._getDebugSphereMesh(scene);
  80355. var radius = impostor.getRadius();
  80356. mesh.scaling.x = radius * 2;
  80357. mesh.scaling.y = radius * 2;
  80358. mesh.scaling.z = radius * 2;
  80359. }
  80360. return mesh;
  80361. };
  80362. PhysicsViewer.prototype.dispose = function () {
  80363. for (var i = 0; i < this._numMeshes; i++) {
  80364. this.hideImpostor(this._impostors[i]);
  80365. }
  80366. if (this._debugBoxMesh) {
  80367. this._debugBoxMesh.dispose();
  80368. }
  80369. if (this._debugSphereMesh) {
  80370. this._debugSphereMesh.dispose();
  80371. }
  80372. if (this._debugMaterial) {
  80373. this._debugMaterial.dispose();
  80374. }
  80375. this._impostors.length = 0;
  80376. this._scene = null;
  80377. this._physicsEnginePlugin = null;
  80378. };
  80379. return PhysicsViewer;
  80380. }());
  80381. Debug.SkeletonViewer = /** @class */ (function () {
  80382. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  80383. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  80384. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  80385. this.skeleton = skeleton;
  80386. this.mesh = mesh;
  80387. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  80388. this.renderingGroupId = renderingGroupId;
  80389. this.color = BABYLON.Color3.White();
  80390. this._debugLines = new Array();
  80391. this._isEnabled = false;
  80392. this._scene = scene;
  80393. this.update();
  80394. this._renderFunction = this.update.bind(this);
  80395. }
  80396. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  80397. get: function () {
  80398. return this._isEnabled;
  80399. },
  80400. set: function (value) {
  80401. if (this._isEnabled === value) {
  80402. return;
  80403. }
  80404. this._isEnabled = value;
  80405. if (value) {
  80406. this._scene.registerBeforeRender(this._renderFunction);
  80407. }
  80408. else {
  80409. this._scene.unregisterBeforeRender(this._renderFunction);
  80410. }
  80411. },
  80412. enumerable: true,
  80413. configurable: true
  80414. });
  80415. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  80416. if (x === void 0) { x = 0; }
  80417. if (y === void 0) { y = 0; }
  80418. if (z === void 0) { z = 0; }
  80419. var tmat = BABYLON.Tmp.Matrix[0];
  80420. var parentBone = bone.getParent();
  80421. tmat.copyFrom(bone.getLocalMatrix());
  80422. if (x !== 0 || y !== 0 || z !== 0) {
  80423. var tmat2 = BABYLON.Tmp.Matrix[1];
  80424. BABYLON.Matrix.IdentityToRef(tmat2);
  80425. tmat2.m[12] = x;
  80426. tmat2.m[13] = y;
  80427. tmat2.m[14] = z;
  80428. tmat2.multiplyToRef(tmat, tmat);
  80429. }
  80430. if (parentBone) {
  80431. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  80432. }
  80433. tmat.multiplyToRef(meshMat, tmat);
  80434. position.x = tmat.m[12];
  80435. position.y = tmat.m[13];
  80436. position.z = tmat.m[14];
  80437. };
  80438. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  80439. var len = bones.length;
  80440. var meshPos = this.mesh.position;
  80441. for (var i = 0; i < len; i++) {
  80442. var bone = bones[i];
  80443. var points = this._debugLines[i];
  80444. if (!points) {
  80445. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80446. this._debugLines[i] = points;
  80447. }
  80448. this._getBonePosition(points[0], bone, meshMat);
  80449. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  80450. points[0].subtractInPlace(meshPos);
  80451. points[1].subtractInPlace(meshPos);
  80452. }
  80453. };
  80454. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  80455. var len = bones.length;
  80456. var boneNum = 0;
  80457. var meshPos = this.mesh.position;
  80458. for (var i = len - 1; i >= 0; i--) {
  80459. var childBone = bones[i];
  80460. var parentBone = childBone.getParent();
  80461. if (!parentBone) {
  80462. continue;
  80463. }
  80464. var points = this._debugLines[boneNum];
  80465. if (!points) {
  80466. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80467. this._debugLines[boneNum] = points;
  80468. }
  80469. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  80470. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  80471. points[0].subtractInPlace(meshPos);
  80472. points[1].subtractInPlace(meshPos);
  80473. boneNum++;
  80474. }
  80475. };
  80476. SkeletonViewer.prototype.update = function () {
  80477. if (this.autoUpdateBonesMatrices) {
  80478. this.skeleton.computeAbsoluteTransforms();
  80479. }
  80480. if (this.skeleton.bones[0].length === undefined) {
  80481. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  80482. }
  80483. else {
  80484. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  80485. }
  80486. if (!this._debugMesh) {
  80487. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  80488. this._debugMesh.renderingGroupId = this.renderingGroupId;
  80489. }
  80490. else {
  80491. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  80492. }
  80493. this._debugMesh.position.copyFrom(this.mesh.position);
  80494. this._debugMesh.color = this.color;
  80495. };
  80496. SkeletonViewer.prototype.dispose = function () {
  80497. if (this._debugMesh) {
  80498. this.isEnabled = false;
  80499. this._debugMesh.dispose();
  80500. this._debugMesh = null;
  80501. }
  80502. };
  80503. return SkeletonViewer;
  80504. }());
  80505. return Debug;
  80506. }());
  80507. BABYLON.Debug = Debug;
  80508. })(BABYLON || (BABYLON = {}));
  80509. //# sourceMappingURL=babylon.debugModules.js.map
  80510. "use strict";
  80511. var BABYLON;
  80512. (function (BABYLON) {
  80513. var RayHelper = /** @class */ (function () {
  80514. function RayHelper(ray) {
  80515. this.ray = ray;
  80516. }
  80517. RayHelper.CreateAndShow = function (ray, scene, color) {
  80518. var helper = new RayHelper(ray);
  80519. helper.show(scene, color);
  80520. return helper;
  80521. };
  80522. RayHelper.prototype.show = function (scene, color) {
  80523. if (!this._renderFunction && this.ray) {
  80524. var ray = this.ray;
  80525. this._renderFunction = this._render.bind(this);
  80526. this._scene = scene;
  80527. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  80528. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  80529. if (this._renderFunction) {
  80530. this._scene.registerBeforeRender(this._renderFunction);
  80531. }
  80532. }
  80533. if (color && this._renderLine) {
  80534. this._renderLine.color.copyFrom(color);
  80535. }
  80536. };
  80537. RayHelper.prototype.hide = function () {
  80538. if (this._renderFunction && this._scene) {
  80539. this._scene.unregisterBeforeRender(this._renderFunction);
  80540. this._scene = null;
  80541. this._renderFunction = null;
  80542. if (this._renderLine) {
  80543. this._renderLine.dispose();
  80544. this._renderLine = null;
  80545. }
  80546. this._renderPoints = [];
  80547. }
  80548. };
  80549. RayHelper.prototype._render = function () {
  80550. var ray = this.ray;
  80551. if (!ray) {
  80552. return;
  80553. }
  80554. var point = this._renderPoints[1];
  80555. var len = Math.min(ray.length, 1000000);
  80556. point.copyFrom(ray.direction);
  80557. point.scaleInPlace(len);
  80558. point.addInPlace(ray.origin);
  80559. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  80560. };
  80561. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  80562. this._attachedToMesh = mesh;
  80563. var ray = this.ray;
  80564. if (!ray) {
  80565. return;
  80566. }
  80567. if (!ray.direction) {
  80568. ray.direction = BABYLON.Vector3.Zero();
  80569. }
  80570. if (!ray.origin) {
  80571. ray.origin = BABYLON.Vector3.Zero();
  80572. }
  80573. if (length) {
  80574. ray.length = length;
  80575. }
  80576. if (!meshSpaceOrigin) {
  80577. meshSpaceOrigin = BABYLON.Vector3.Zero();
  80578. }
  80579. if (!meshSpaceDirection) {
  80580. // -1 so that this will work with Mesh.lookAt
  80581. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  80582. }
  80583. if (!this._meshSpaceDirection) {
  80584. this._meshSpaceDirection = meshSpaceDirection.clone();
  80585. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  80586. }
  80587. else {
  80588. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  80589. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  80590. }
  80591. if (!this._updateToMeshFunction) {
  80592. this._updateToMeshFunction = this._updateToMesh.bind(this);
  80593. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  80594. }
  80595. this._updateToMesh();
  80596. };
  80597. RayHelper.prototype.detachFromMesh = function () {
  80598. if (this._attachedToMesh) {
  80599. if (this._updateToMeshFunction) {
  80600. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  80601. }
  80602. this._attachedToMesh = null;
  80603. this._updateToMeshFunction = null;
  80604. }
  80605. };
  80606. RayHelper.prototype._updateToMesh = function () {
  80607. var ray = this.ray;
  80608. if (!this._attachedToMesh || !ray) {
  80609. return;
  80610. }
  80611. if (this._attachedToMesh._isDisposed) {
  80612. this.detachFromMesh();
  80613. return;
  80614. }
  80615. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  80616. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  80617. };
  80618. RayHelper.prototype.dispose = function () {
  80619. this.hide();
  80620. this.detachFromMesh();
  80621. this.ray = null;
  80622. };
  80623. return RayHelper;
  80624. }());
  80625. BABYLON.RayHelper = RayHelper;
  80626. })(BABYLON || (BABYLON = {}));
  80627. //# sourceMappingURL=babylon.rayHelper.js.map
  80628. "use strict";
  80629. var BABYLON;
  80630. (function (BABYLON) {
  80631. // load the inspector using require, if not present in the global namespace.
  80632. var DebugLayer = /** @class */ (function () {
  80633. function DebugLayer(scene) {
  80634. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  80635. this._scene = scene;
  80636. // load inspector using require, if it doesn't exist on the global namespace.
  80637. }
  80638. /** Creates the inspector window. */
  80639. DebugLayer.prototype._createInspector = function (config) {
  80640. if (config === void 0) { config = {}; }
  80641. var popup = config.popup || false;
  80642. var initialTab = config.initialTab || 0;
  80643. var parentElement = config.parentElement || null;
  80644. if (!this._inspector) {
  80645. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  80646. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  80647. } // else nothing to do,; instance is already existing
  80648. };
  80649. DebugLayer.prototype.isVisible = function () {
  80650. if (!this._inspector) {
  80651. return false;
  80652. }
  80653. return true;
  80654. };
  80655. DebugLayer.prototype.hide = function () {
  80656. if (this._inspector) {
  80657. try {
  80658. this._inspector.dispose();
  80659. }
  80660. catch (e) {
  80661. // If the inspector has been removed directly from the inspector tool
  80662. }
  80663. this._inspector = null;
  80664. }
  80665. };
  80666. DebugLayer.prototype.show = function (config) {
  80667. if (config === void 0) { config = {}; }
  80668. if (typeof this.BJSINSPECTOR == 'undefined') {
  80669. // Load inspector and add it to the DOM
  80670. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  80671. }
  80672. else {
  80673. // Otherwise creates the inspector
  80674. this._createInspector(config);
  80675. }
  80676. };
  80677. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  80678. return DebugLayer;
  80679. }());
  80680. BABYLON.DebugLayer = DebugLayer;
  80681. })(BABYLON || (BABYLON = {}));
  80682. //# sourceMappingURL=babylon.debugLayer.js.map
  80683. "use strict";
  80684. var BABYLON;
  80685. (function (BABYLON) {
  80686. var BoundingBoxRenderer = /** @class */ (function () {
  80687. function BoundingBoxRenderer(scene) {
  80688. this.frontColor = new BABYLON.Color3(1, 1, 1);
  80689. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  80690. this.showBackLines = true;
  80691. this.renderList = new BABYLON.SmartArray(32);
  80692. this._vertexBuffers = {};
  80693. this._scene = scene;
  80694. }
  80695. BoundingBoxRenderer.prototype._prepareRessources = function () {
  80696. if (this._colorShader) {
  80697. return;
  80698. }
  80699. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  80700. attributes: [BABYLON.VertexBuffer.PositionKind],
  80701. uniforms: ["world", "viewProjection", "color"]
  80702. });
  80703. var engine = this._scene.getEngine();
  80704. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  80705. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  80706. this._createIndexBuffer();
  80707. };
  80708. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  80709. var engine = this._scene.getEngine();
  80710. 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]);
  80711. };
  80712. BoundingBoxRenderer.prototype._rebuild = function () {
  80713. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80714. if (vb) {
  80715. vb._rebuild();
  80716. }
  80717. this._createIndexBuffer();
  80718. };
  80719. BoundingBoxRenderer.prototype.reset = function () {
  80720. this.renderList.reset();
  80721. };
  80722. BoundingBoxRenderer.prototype.render = function () {
  80723. if (this.renderList.length === 0) {
  80724. return;
  80725. }
  80726. this._prepareRessources();
  80727. if (!this._colorShader.isReady()) {
  80728. return;
  80729. }
  80730. var engine = this._scene.getEngine();
  80731. engine.setDepthWrite(false);
  80732. this._colorShader._preBind();
  80733. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  80734. var boundingBox = this.renderList.data[boundingBoxIndex];
  80735. var min = boundingBox.minimum;
  80736. var max = boundingBox.maximum;
  80737. var diff = max.subtract(min);
  80738. var median = min.add(diff.scale(0.5));
  80739. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  80740. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  80741. .multiply(boundingBox.getWorldMatrix());
  80742. // VBOs
  80743. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  80744. if (this.showBackLines) {
  80745. // Back
  80746. engine.setDepthFunctionToGreaterOrEqual();
  80747. this._scene.resetCachedMaterial();
  80748. this._colorShader.setColor4("color", this.backColor.toColor4());
  80749. this._colorShader.bind(worldMatrix);
  80750. // Draw order
  80751. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80752. }
  80753. // Front
  80754. engine.setDepthFunctionToLess();
  80755. this._scene.resetCachedMaterial();
  80756. this._colorShader.setColor4("color", this.frontColor.toColor4());
  80757. this._colorShader.bind(worldMatrix);
  80758. // Draw order
  80759. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80760. }
  80761. this._colorShader.unbind();
  80762. engine.setDepthFunctionToLessOrEqual();
  80763. engine.setDepthWrite(true);
  80764. };
  80765. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  80766. this._prepareRessources();
  80767. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  80768. return;
  80769. }
  80770. var engine = this._scene.getEngine();
  80771. engine.setDepthWrite(false);
  80772. engine.setColorWrite(false);
  80773. this._colorShader._preBind();
  80774. var boundingBox = mesh._boundingInfo.boundingBox;
  80775. var min = boundingBox.minimum;
  80776. var max = boundingBox.maximum;
  80777. var diff = max.subtract(min);
  80778. var median = min.add(diff.scale(0.5));
  80779. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  80780. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  80781. .multiply(boundingBox.getWorldMatrix());
  80782. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  80783. engine.setDepthFunctionToLess();
  80784. this._scene.resetCachedMaterial();
  80785. this._colorShader.bind(worldMatrix);
  80786. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80787. this._colorShader.unbind();
  80788. engine.setDepthFunctionToLessOrEqual();
  80789. engine.setDepthWrite(true);
  80790. engine.setColorWrite(true);
  80791. };
  80792. BoundingBoxRenderer.prototype.dispose = function () {
  80793. if (!this._colorShader) {
  80794. return;
  80795. }
  80796. this.renderList.dispose();
  80797. this._colorShader.dispose();
  80798. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80799. if (buffer) {
  80800. buffer.dispose();
  80801. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  80802. }
  80803. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  80804. };
  80805. return BoundingBoxRenderer;
  80806. }());
  80807. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  80808. })(BABYLON || (BABYLON = {}));
  80809. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  80810. "use strict";
  80811. var BABYLON;
  80812. (function (BABYLON) {
  80813. var MorphTarget = /** @class */ (function () {
  80814. function MorphTarget(name, influence) {
  80815. if (influence === void 0) { influence = 0; }
  80816. this.name = name;
  80817. this.animations = new Array();
  80818. this._positions = null;
  80819. this._normals = null;
  80820. this._tangents = null;
  80821. this.onInfluenceChanged = new BABYLON.Observable();
  80822. this.influence = influence;
  80823. }
  80824. Object.defineProperty(MorphTarget.prototype, "influence", {
  80825. get: function () {
  80826. return this._influence;
  80827. },
  80828. set: function (influence) {
  80829. if (this._influence === influence) {
  80830. return;
  80831. }
  80832. var previous = this._influence;
  80833. this._influence = influence;
  80834. if (this.onInfluenceChanged.hasObservers) {
  80835. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  80836. }
  80837. },
  80838. enumerable: true,
  80839. configurable: true
  80840. });
  80841. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  80842. get: function () {
  80843. return !!this._positions;
  80844. },
  80845. enumerable: true,
  80846. configurable: true
  80847. });
  80848. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  80849. get: function () {
  80850. return !!this._normals;
  80851. },
  80852. enumerable: true,
  80853. configurable: true
  80854. });
  80855. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  80856. get: function () {
  80857. return !!this._tangents;
  80858. },
  80859. enumerable: true,
  80860. configurable: true
  80861. });
  80862. MorphTarget.prototype.setPositions = function (data) {
  80863. this._positions = data;
  80864. };
  80865. MorphTarget.prototype.getPositions = function () {
  80866. return this._positions;
  80867. };
  80868. MorphTarget.prototype.setNormals = function (data) {
  80869. this._normals = data;
  80870. };
  80871. MorphTarget.prototype.getNormals = function () {
  80872. return this._normals;
  80873. };
  80874. MorphTarget.prototype.setTangents = function (data) {
  80875. this._tangents = data;
  80876. };
  80877. MorphTarget.prototype.getTangents = function () {
  80878. return this._tangents;
  80879. };
  80880. /**
  80881. * Serializes the current target into a Serialization object.
  80882. * Returns the serialized object.
  80883. */
  80884. MorphTarget.prototype.serialize = function () {
  80885. var serializationObject = {};
  80886. serializationObject.name = this.name;
  80887. serializationObject.influence = this.influence;
  80888. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  80889. if (this.hasNormals) {
  80890. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  80891. }
  80892. if (this.hasTangents) {
  80893. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  80894. }
  80895. // Animations
  80896. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  80897. return serializationObject;
  80898. };
  80899. // Statics
  80900. MorphTarget.Parse = function (serializationObject) {
  80901. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  80902. result.setPositions(serializationObject.positions);
  80903. if (serializationObject.normals) {
  80904. result.setNormals(serializationObject.normals);
  80905. }
  80906. if (serializationObject.tangents) {
  80907. result.setTangents(serializationObject.tangents);
  80908. }
  80909. // Animations
  80910. if (serializationObject.animations) {
  80911. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  80912. var parsedAnimation = serializationObject.animations[animationIndex];
  80913. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  80914. }
  80915. }
  80916. return result;
  80917. };
  80918. MorphTarget.FromMesh = function (mesh, name, influence) {
  80919. if (!name) {
  80920. name = mesh.name;
  80921. }
  80922. var result = new MorphTarget(name, influence);
  80923. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  80924. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  80925. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  80926. }
  80927. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  80928. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  80929. }
  80930. return result;
  80931. };
  80932. return MorphTarget;
  80933. }());
  80934. BABYLON.MorphTarget = MorphTarget;
  80935. })(BABYLON || (BABYLON = {}));
  80936. //# sourceMappingURL=babylon.morphTarget.js.map
  80937. "use strict";
  80938. var BABYLON;
  80939. (function (BABYLON) {
  80940. var MorphTargetManager = /** @class */ (function () {
  80941. function MorphTargetManager(scene) {
  80942. if (scene === void 0) { scene = null; }
  80943. this._targets = new Array();
  80944. this._targetObservable = new Array();
  80945. this._activeTargets = new BABYLON.SmartArray(16);
  80946. this._supportsNormals = false;
  80947. this._supportsTangents = false;
  80948. this._vertexCount = 0;
  80949. this._uniqueId = 0;
  80950. this._tempInfluences = new Array();
  80951. if (!scene) {
  80952. scene = BABYLON.Engine.LastCreatedScene;
  80953. }
  80954. this._scene = scene;
  80955. if (this._scene) {
  80956. this._scene.morphTargetManagers.push(this);
  80957. this._uniqueId = this._scene.getUniqueId();
  80958. }
  80959. }
  80960. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  80961. get: function () {
  80962. return this._uniqueId;
  80963. },
  80964. enumerable: true,
  80965. configurable: true
  80966. });
  80967. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  80968. get: function () {
  80969. return this._vertexCount;
  80970. },
  80971. enumerable: true,
  80972. configurable: true
  80973. });
  80974. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  80975. get: function () {
  80976. return this._supportsNormals;
  80977. },
  80978. enumerable: true,
  80979. configurable: true
  80980. });
  80981. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  80982. get: function () {
  80983. return this._supportsTangents;
  80984. },
  80985. enumerable: true,
  80986. configurable: true
  80987. });
  80988. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  80989. get: function () {
  80990. return this._targets.length;
  80991. },
  80992. enumerable: true,
  80993. configurable: true
  80994. });
  80995. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  80996. get: function () {
  80997. return this._activeTargets.length;
  80998. },
  80999. enumerable: true,
  81000. configurable: true
  81001. });
  81002. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  81003. get: function () {
  81004. return this._influences;
  81005. },
  81006. enumerable: true,
  81007. configurable: true
  81008. });
  81009. MorphTargetManager.prototype.getActiveTarget = function (index) {
  81010. return this._activeTargets.data[index];
  81011. };
  81012. MorphTargetManager.prototype.getTarget = function (index) {
  81013. return this._targets[index];
  81014. };
  81015. MorphTargetManager.prototype.addTarget = function (target) {
  81016. var _this = this;
  81017. this._targets.push(target);
  81018. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  81019. _this._syncActiveTargets(needUpdate);
  81020. }));
  81021. this._syncActiveTargets(true);
  81022. };
  81023. MorphTargetManager.prototype.removeTarget = function (target) {
  81024. var index = this._targets.indexOf(target);
  81025. if (index >= 0) {
  81026. this._targets.splice(index, 1);
  81027. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  81028. this._syncActiveTargets(true);
  81029. }
  81030. };
  81031. /**
  81032. * Serializes the current manager into a Serialization object.
  81033. * Returns the serialized object.
  81034. */
  81035. MorphTargetManager.prototype.serialize = function () {
  81036. var serializationObject = {};
  81037. serializationObject.id = this.uniqueId;
  81038. serializationObject.targets = [];
  81039. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  81040. var target = _a[_i];
  81041. serializationObject.targets.push(target.serialize());
  81042. }
  81043. return serializationObject;
  81044. };
  81045. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  81046. var influenceCount = 0;
  81047. this._activeTargets.reset();
  81048. this._supportsNormals = true;
  81049. this._supportsTangents = true;
  81050. this._vertexCount = 0;
  81051. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  81052. var target = _a[_i];
  81053. this._activeTargets.push(target);
  81054. this._tempInfluences[influenceCount++] = target.influence;
  81055. var positions = target.getPositions();
  81056. if (positions) {
  81057. this._supportsNormals = this._supportsNormals && target.hasNormals;
  81058. this._supportsTangents = this._supportsTangents && target.hasTangents;
  81059. var vertexCount = positions.length / 3;
  81060. if (this._vertexCount === 0) {
  81061. this._vertexCount = vertexCount;
  81062. }
  81063. else if (this._vertexCount !== vertexCount) {
  81064. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  81065. return;
  81066. }
  81067. }
  81068. }
  81069. if (!this._influences || this._influences.length !== influenceCount) {
  81070. this._influences = new Float32Array(influenceCount);
  81071. }
  81072. for (var index = 0; index < influenceCount; index++) {
  81073. this._influences[index] = this._tempInfluences[index];
  81074. }
  81075. if (needUpdate && this._scene) {
  81076. // Flag meshes as dirty to resync with the active targets
  81077. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  81078. var mesh = _c[_b];
  81079. if (mesh.morphTargetManager === this) {
  81080. mesh._syncGeometryWithMorphTargetManager();
  81081. }
  81082. }
  81083. }
  81084. };
  81085. // Statics
  81086. MorphTargetManager.Parse = function (serializationObject, scene) {
  81087. var result = new MorphTargetManager(scene);
  81088. result._uniqueId = serializationObject.id;
  81089. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  81090. var targetData = _a[_i];
  81091. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  81092. }
  81093. return result;
  81094. };
  81095. return MorphTargetManager;
  81096. }());
  81097. BABYLON.MorphTargetManager = MorphTargetManager;
  81098. })(BABYLON || (BABYLON = {}));
  81099. //# sourceMappingURL=babylon.morphTargetManager.js.map
  81100. "use strict";
  81101. var BABYLON;
  81102. (function (BABYLON) {
  81103. var Octree = /** @class */ (function () {
  81104. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  81105. if (maxDepth === void 0) { maxDepth = 2; }
  81106. this.maxDepth = maxDepth;
  81107. this.dynamicContent = new Array();
  81108. this._maxBlockCapacity = maxBlockCapacity || 64;
  81109. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  81110. this._creationFunc = creationFunc;
  81111. }
  81112. // Methods
  81113. Octree.prototype.update = function (worldMin, worldMax, entries) {
  81114. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  81115. };
  81116. Octree.prototype.addMesh = function (entry) {
  81117. for (var index = 0; index < this.blocks.length; index++) {
  81118. var block = this.blocks[index];
  81119. block.addEntry(entry);
  81120. }
  81121. };
  81122. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  81123. this._selectionContent.reset();
  81124. for (var index = 0; index < this.blocks.length; index++) {
  81125. var block = this.blocks[index];
  81126. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  81127. }
  81128. if (allowDuplicate) {
  81129. this._selectionContent.concat(this.dynamicContent);
  81130. }
  81131. else {
  81132. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81133. }
  81134. return this._selectionContent;
  81135. };
  81136. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  81137. this._selectionContent.reset();
  81138. for (var index = 0; index < this.blocks.length; index++) {
  81139. var block = this.blocks[index];
  81140. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  81141. }
  81142. if (allowDuplicate) {
  81143. this._selectionContent.concat(this.dynamicContent);
  81144. }
  81145. else {
  81146. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81147. }
  81148. return this._selectionContent;
  81149. };
  81150. Octree.prototype.intersectsRay = function (ray) {
  81151. this._selectionContent.reset();
  81152. for (var index = 0; index < this.blocks.length; index++) {
  81153. var block = this.blocks[index];
  81154. block.intersectsRay(ray, this._selectionContent);
  81155. }
  81156. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81157. return this._selectionContent;
  81158. };
  81159. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  81160. target.blocks = new Array();
  81161. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  81162. // Segmenting space
  81163. for (var x = 0; x < 2; x++) {
  81164. for (var y = 0; y < 2; y++) {
  81165. for (var z = 0; z < 2; z++) {
  81166. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  81167. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  81168. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  81169. block.addEntries(entries);
  81170. target.blocks.push(block);
  81171. }
  81172. }
  81173. }
  81174. };
  81175. Octree.CreationFuncForMeshes = function (entry, block) {
  81176. var boundingInfo = entry.getBoundingInfo();
  81177. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  81178. block.entries.push(entry);
  81179. }
  81180. };
  81181. Octree.CreationFuncForSubMeshes = function (entry, block) {
  81182. var boundingInfo = entry.getBoundingInfo();
  81183. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  81184. block.entries.push(entry);
  81185. }
  81186. };
  81187. return Octree;
  81188. }());
  81189. BABYLON.Octree = Octree;
  81190. })(BABYLON || (BABYLON = {}));
  81191. //# sourceMappingURL=babylon.octree.js.map
  81192. "use strict";
  81193. var BABYLON;
  81194. (function (BABYLON) {
  81195. var OctreeBlock = /** @class */ (function () {
  81196. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  81197. this.entries = new Array();
  81198. this._boundingVectors = new Array();
  81199. this._capacity = capacity;
  81200. this._depth = depth;
  81201. this._maxDepth = maxDepth;
  81202. this._creationFunc = creationFunc;
  81203. this._minPoint = minPoint;
  81204. this._maxPoint = maxPoint;
  81205. this._boundingVectors.push(minPoint.clone());
  81206. this._boundingVectors.push(maxPoint.clone());
  81207. this._boundingVectors.push(minPoint.clone());
  81208. this._boundingVectors[2].x = maxPoint.x;
  81209. this._boundingVectors.push(minPoint.clone());
  81210. this._boundingVectors[3].y = maxPoint.y;
  81211. this._boundingVectors.push(minPoint.clone());
  81212. this._boundingVectors[4].z = maxPoint.z;
  81213. this._boundingVectors.push(maxPoint.clone());
  81214. this._boundingVectors[5].z = minPoint.z;
  81215. this._boundingVectors.push(maxPoint.clone());
  81216. this._boundingVectors[6].x = minPoint.x;
  81217. this._boundingVectors.push(maxPoint.clone());
  81218. this._boundingVectors[7].y = minPoint.y;
  81219. }
  81220. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  81221. // Property
  81222. get: function () {
  81223. return this._capacity;
  81224. },
  81225. enumerable: true,
  81226. configurable: true
  81227. });
  81228. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  81229. get: function () {
  81230. return this._minPoint;
  81231. },
  81232. enumerable: true,
  81233. configurable: true
  81234. });
  81235. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  81236. get: function () {
  81237. return this._maxPoint;
  81238. },
  81239. enumerable: true,
  81240. configurable: true
  81241. });
  81242. // Methods
  81243. OctreeBlock.prototype.addEntry = function (entry) {
  81244. if (this.blocks) {
  81245. for (var index = 0; index < this.blocks.length; index++) {
  81246. var block = this.blocks[index];
  81247. block.addEntry(entry);
  81248. }
  81249. return;
  81250. }
  81251. this._creationFunc(entry, this);
  81252. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  81253. this.createInnerBlocks();
  81254. }
  81255. };
  81256. OctreeBlock.prototype.addEntries = function (entries) {
  81257. for (var index = 0; index < entries.length; index++) {
  81258. var mesh = entries[index];
  81259. this.addEntry(mesh);
  81260. }
  81261. };
  81262. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  81263. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  81264. if (this.blocks) {
  81265. for (var index = 0; index < this.blocks.length; index++) {
  81266. var block = this.blocks[index];
  81267. block.select(frustumPlanes, selection, allowDuplicate);
  81268. }
  81269. return;
  81270. }
  81271. if (allowDuplicate) {
  81272. selection.concat(this.entries);
  81273. }
  81274. else {
  81275. selection.concatWithNoDuplicate(this.entries);
  81276. }
  81277. }
  81278. };
  81279. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  81280. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  81281. if (this.blocks) {
  81282. for (var index = 0; index < this.blocks.length; index++) {
  81283. var block = this.blocks[index];
  81284. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  81285. }
  81286. return;
  81287. }
  81288. if (allowDuplicate) {
  81289. selection.concat(this.entries);
  81290. }
  81291. else {
  81292. selection.concatWithNoDuplicate(this.entries);
  81293. }
  81294. }
  81295. };
  81296. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  81297. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  81298. if (this.blocks) {
  81299. for (var index = 0; index < this.blocks.length; index++) {
  81300. var block = this.blocks[index];
  81301. block.intersectsRay(ray, selection);
  81302. }
  81303. return;
  81304. }
  81305. selection.concatWithNoDuplicate(this.entries);
  81306. }
  81307. };
  81308. OctreeBlock.prototype.createInnerBlocks = function () {
  81309. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  81310. };
  81311. return OctreeBlock;
  81312. }());
  81313. BABYLON.OctreeBlock = OctreeBlock;
  81314. })(BABYLON || (BABYLON = {}));
  81315. //# sourceMappingURL=babylon.octreeBlock.js.map
  81316. "use strict";
  81317. var BABYLON;
  81318. (function (BABYLON) {
  81319. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  81320. __extends(VRDistortionCorrectionPostProcess, _super);
  81321. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  81322. var _this = _super.call(this, name, "vrDistortionCorrection", [
  81323. 'LensCenter',
  81324. 'Scale',
  81325. 'ScaleIn',
  81326. 'HmdWarpParam'
  81327. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  81328. _this._isRightEye = isRightEye;
  81329. _this._distortionFactors = vrMetrics.distortionK;
  81330. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  81331. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  81332. _this.adaptScaleToCurrentViewport = true;
  81333. _this.onSizeChangedObservable.add(function () {
  81334. _this.aspectRatio = _this.width * .5 / _this.height;
  81335. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  81336. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  81337. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  81338. });
  81339. _this.onApplyObservable.add(function (effect) {
  81340. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  81341. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  81342. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  81343. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  81344. });
  81345. return _this;
  81346. }
  81347. return VRDistortionCorrectionPostProcess;
  81348. }(BABYLON.PostProcess));
  81349. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  81350. })(BABYLON || (BABYLON = {}));
  81351. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  81352. "use strict";
  81353. var BABYLON;
  81354. (function (BABYLON) {
  81355. var AnaglyphPostProcess = /** @class */ (function (_super) {
  81356. __extends(AnaglyphPostProcess, _super);
  81357. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  81358. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  81359. _this._passedProcess = rigCameras[0]._rigPostProcess;
  81360. _this.onApplyObservable.add(function (effect) {
  81361. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  81362. });
  81363. return _this;
  81364. }
  81365. return AnaglyphPostProcess;
  81366. }(BABYLON.PostProcess));
  81367. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  81368. })(BABYLON || (BABYLON = {}));
  81369. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  81370. "use strict";
  81371. var BABYLON;
  81372. (function (BABYLON) {
  81373. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  81374. __extends(StereoscopicInterlacePostProcess, _super);
  81375. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  81376. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  81377. _this._passedProcess = rigCameras[0]._rigPostProcess;
  81378. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  81379. _this.onSizeChangedObservable.add(function () {
  81380. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  81381. });
  81382. _this.onApplyObservable.add(function (effect) {
  81383. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  81384. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  81385. });
  81386. return _this;
  81387. }
  81388. return StereoscopicInterlacePostProcess;
  81389. }(BABYLON.PostProcess));
  81390. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  81391. })(BABYLON || (BABYLON = {}));
  81392. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  81393. "use strict";
  81394. var BABYLON;
  81395. (function (BABYLON) {
  81396. /**
  81397. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  81398. * Screen rotation is taken into account.
  81399. */
  81400. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  81401. function FreeCameraDeviceOrientationInput() {
  81402. var _this = this;
  81403. this._screenOrientationAngle = 0;
  81404. this._screenQuaternion = new BABYLON.Quaternion();
  81405. this._alpha = 0;
  81406. this._beta = 0;
  81407. this._gamma = 0;
  81408. this._orientationChanged = function () {
  81409. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  81410. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  81411. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  81412. };
  81413. this._deviceOrientation = function (evt) {
  81414. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  81415. _this._beta = evt.beta !== null ? evt.beta : 0;
  81416. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  81417. };
  81418. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  81419. this._orientationChanged();
  81420. }
  81421. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  81422. get: function () {
  81423. return this._camera;
  81424. },
  81425. set: function (camera) {
  81426. this._camera = camera;
  81427. if (this._camera != null && !this._camera.rotationQuaternion) {
  81428. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  81429. }
  81430. },
  81431. enumerable: true,
  81432. configurable: true
  81433. });
  81434. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  81435. window.addEventListener("orientationchange", this._orientationChanged);
  81436. window.addEventListener("deviceorientation", this._deviceOrientation);
  81437. //In certain cases, the attach control is called AFTER orientation was changed,
  81438. //So this is needed.
  81439. this._orientationChanged();
  81440. };
  81441. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  81442. window.removeEventListener("orientationchange", this._orientationChanged);
  81443. window.removeEventListener("deviceorientation", this._deviceOrientation);
  81444. };
  81445. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  81446. //if no device orientation provided, don't update the rotation.
  81447. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  81448. if (!this._alpha)
  81449. return;
  81450. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  81451. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  81452. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  81453. //Mirror on XY Plane
  81454. this._camera.rotationQuaternion.z *= -1;
  81455. this._camera.rotationQuaternion.w *= -1;
  81456. };
  81457. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  81458. return "FreeCameraDeviceOrientationInput";
  81459. };
  81460. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  81461. return "deviceOrientation";
  81462. };
  81463. return FreeCameraDeviceOrientationInput;
  81464. }());
  81465. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  81466. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  81467. })(BABYLON || (BABYLON = {}));
  81468. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  81469. "use strict";
  81470. var BABYLON;
  81471. (function (BABYLON) {
  81472. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  81473. function ArcRotateCameraVRDeviceOrientationInput() {
  81474. this.alphaCorrection = 1;
  81475. this.betaCorrection = 1;
  81476. this.gammaCorrection = 1;
  81477. this._alpha = 0;
  81478. this._gamma = 0;
  81479. this._dirty = false;
  81480. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  81481. }
  81482. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  81483. this.camera.attachControl(element, noPreventDefault);
  81484. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  81485. };
  81486. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  81487. if (evt.alpha !== null) {
  81488. this._alpha = +evt.alpha | 0;
  81489. }
  81490. if (evt.gamma !== null) {
  81491. this._gamma = +evt.gamma | 0;
  81492. }
  81493. this._dirty = true;
  81494. };
  81495. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  81496. if (this._dirty) {
  81497. this._dirty = false;
  81498. if (this._gamma < 0) {
  81499. this._gamma = 180 + this._gamma;
  81500. }
  81501. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  81502. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  81503. }
  81504. };
  81505. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  81506. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  81507. };
  81508. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  81509. return "ArcRotateCameraVRDeviceOrientationInput";
  81510. };
  81511. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  81512. return "VRDeviceOrientation";
  81513. };
  81514. return ArcRotateCameraVRDeviceOrientationInput;
  81515. }());
  81516. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  81517. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  81518. })(BABYLON || (BABYLON = {}));
  81519. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  81520. "use strict";
  81521. var BABYLON;
  81522. (function (BABYLON) {
  81523. var VRCameraMetrics = /** @class */ (function () {
  81524. function VRCameraMetrics() {
  81525. this.compensateDistortion = true;
  81526. }
  81527. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  81528. get: function () {
  81529. return this.hResolution / (2 * this.vResolution);
  81530. },
  81531. enumerable: true,
  81532. configurable: true
  81533. });
  81534. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  81535. get: function () {
  81536. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  81537. },
  81538. enumerable: true,
  81539. configurable: true
  81540. });
  81541. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  81542. get: function () {
  81543. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  81544. var h = (4 * meters) / this.hScreenSize;
  81545. return BABYLON.Matrix.Translation(h, 0, 0);
  81546. },
  81547. enumerable: true,
  81548. configurable: true
  81549. });
  81550. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  81551. get: function () {
  81552. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  81553. var h = (4 * meters) / this.hScreenSize;
  81554. return BABYLON.Matrix.Translation(-h, 0, 0);
  81555. },
  81556. enumerable: true,
  81557. configurable: true
  81558. });
  81559. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  81560. get: function () {
  81561. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  81562. },
  81563. enumerable: true,
  81564. configurable: true
  81565. });
  81566. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  81567. get: function () {
  81568. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  81569. },
  81570. enumerable: true,
  81571. configurable: true
  81572. });
  81573. VRCameraMetrics.GetDefault = function () {
  81574. var result = new VRCameraMetrics();
  81575. result.hResolution = 1280;
  81576. result.vResolution = 800;
  81577. result.hScreenSize = 0.149759993;
  81578. result.vScreenSize = 0.0935999975;
  81579. result.vScreenCenter = 0.0467999987;
  81580. result.eyeToScreenDistance = 0.0410000011;
  81581. result.lensSeparationDistance = 0.0635000020;
  81582. result.interpupillaryDistance = 0.0640000030;
  81583. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  81584. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  81585. result.postProcessScaleFactor = 1.714605507808412;
  81586. result.lensCenterOffset = 0.151976421;
  81587. return result;
  81588. };
  81589. return VRCameraMetrics;
  81590. }());
  81591. BABYLON.VRCameraMetrics = VRCameraMetrics;
  81592. })(BABYLON || (BABYLON = {}));
  81593. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  81594. "use strict";
  81595. var BABYLON;
  81596. (function (BABYLON) {
  81597. /**
  81598. * This represents a WebVR camera.
  81599. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  81600. * @example http://doc.babylonjs.com/how_to/webvr_camera
  81601. */
  81602. var WebVRFreeCamera = /** @class */ (function (_super) {
  81603. __extends(WebVRFreeCamera, _super);
  81604. /**
  81605. * Instantiates a WebVRFreeCamera.
  81606. * @param name The name of the WebVRFreeCamera
  81607. * @param position The starting anchor position for the camera
  81608. * @param scene The scene the camera belongs to
  81609. * @param webVROptions a set of customizable options for the webVRCamera
  81610. */
  81611. function WebVRFreeCamera(name, position, scene, webVROptions) {
  81612. if (webVROptions === void 0) { webVROptions = {}; }
  81613. var _this = _super.call(this, name, position, scene) || this;
  81614. _this.webVROptions = webVROptions;
  81615. /**
  81616. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  81617. */
  81618. _this._vrDevice = null;
  81619. /**
  81620. * The rawPose of the vrDevice.
  81621. */
  81622. _this.rawPose = null;
  81623. _this._specsVersion = "1.1";
  81624. _this._attached = false;
  81625. _this._descendants = [];
  81626. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  81627. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  81628. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  81629. _this._standingMatrix = null;
  81630. /**
  81631. * Represents device position in babylon space.
  81632. */
  81633. _this.devicePosition = BABYLON.Vector3.Zero();
  81634. /**
  81635. * Represents device rotation in babylon space.
  81636. */
  81637. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  81638. /**
  81639. * The scale of the device to be used when translating from device space to babylon space.
  81640. */
  81641. _this.deviceScaleFactor = 1;
  81642. _this._deviceToWorld = BABYLON.Matrix.Identity();
  81643. _this._worldToDevice = BABYLON.Matrix.Identity();
  81644. /**
  81645. * References to the webVR controllers for the vrDevice.
  81646. */
  81647. _this.controllers = [];
  81648. /**
  81649. * Emits an event when a controller is attached.
  81650. */
  81651. _this.onControllersAttachedObservable = new BABYLON.Observable();
  81652. /**
  81653. * Emits an event when a controller's mesh has been loaded;
  81654. */
  81655. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  81656. /**
  81657. * If the rig cameras be used as parent instead of this camera.
  81658. */
  81659. _this.rigParenting = true;
  81660. _this._defaultHeight = undefined;
  81661. _this._workingVector = BABYLON.Vector3.Zero();
  81662. _this._oneVector = BABYLON.Vector3.One();
  81663. _this._workingMatrix = BABYLON.Matrix.Identity();
  81664. _this._cache.position = BABYLON.Vector3.Zero();
  81665. if (webVROptions.defaultHeight) {
  81666. _this._defaultHeight = webVROptions.defaultHeight;
  81667. _this.position.y = _this._defaultHeight;
  81668. }
  81669. _this.minZ = 0.1;
  81670. //legacy support - the compensation boolean was removed.
  81671. if (arguments.length === 5) {
  81672. _this.webVROptions = arguments[4];
  81673. }
  81674. // default webVR options
  81675. if (_this.webVROptions.trackPosition == undefined) {
  81676. _this.webVROptions.trackPosition = true;
  81677. }
  81678. if (_this.webVROptions.controllerMeshes == undefined) {
  81679. _this.webVROptions.controllerMeshes = true;
  81680. }
  81681. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  81682. _this.webVROptions.defaultLightingOnControllers = true;
  81683. }
  81684. _this.rotationQuaternion = new BABYLON.Quaternion();
  81685. if (_this.webVROptions && _this.webVROptions.positionScale) {
  81686. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  81687. }
  81688. //enable VR
  81689. var engine = _this.getEngine();
  81690. _this._onVREnabled = function (success) { if (success) {
  81691. _this.initControllers();
  81692. } };
  81693. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  81694. engine.initWebVR().add(function (event) {
  81695. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  81696. return;
  81697. }
  81698. _this._vrDevice = event.vrDisplay;
  81699. //reset the rig parameters.
  81700. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  81701. if (_this._attached) {
  81702. _this.getEngine().enableVR();
  81703. }
  81704. });
  81705. if (typeof (VRFrameData) !== "undefined")
  81706. _this._frameData = new VRFrameData();
  81707. /**
  81708. * The idea behind the following lines:
  81709. * objects that have the camera as parent should actually have the rig cameras as a parent.
  81710. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  81711. * the second will not show it correctly.
  81712. *
  81713. * To solve this - each object that has the camera as parent will be added to a protected array.
  81714. * When the rig camera renders, it will take this array and set all of those to be its children.
  81715. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  81716. * Amazing!
  81717. */
  81718. scene.onBeforeCameraRenderObservable.add(function (camera) {
  81719. if (camera.parent === _this && _this.rigParenting) {
  81720. _this._descendants = _this.getDescendants(true, function (n) {
  81721. // don't take the cameras or the controllers!
  81722. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  81723. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  81724. return !isController && !isRigCamera;
  81725. });
  81726. _this._descendants.forEach(function (node) {
  81727. node.parent = camera;
  81728. });
  81729. }
  81730. });
  81731. scene.onAfterCameraRenderObservable.add(function (camera) {
  81732. if (camera.parent === _this && _this.rigParenting) {
  81733. _this._descendants.forEach(function (node) {
  81734. node.parent = _this;
  81735. });
  81736. }
  81737. });
  81738. return _this;
  81739. }
  81740. /**
  81741. * Gets the device distance from the ground in meters.
  81742. * @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.
  81743. */
  81744. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  81745. if (this._standingMatrix) {
  81746. // Add standing matrix offset to get real offset from ground in room
  81747. this._standingMatrix.getTranslationToRef(this._workingVector);
  81748. return this._deviceRoomPosition.y + this._workingVector.y;
  81749. }
  81750. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  81751. return this._defaultHeight || 0;
  81752. };
  81753. /**
  81754. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  81755. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  81756. */
  81757. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  81758. var _this = this;
  81759. if (callback === void 0) { callback = function (bool) { }; }
  81760. // Use standing matrix if available
  81761. this.getEngine().initWebVRAsync().then(function (result) {
  81762. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  81763. callback(false);
  81764. }
  81765. else {
  81766. _this._standingMatrix = new BABYLON.Matrix();
  81767. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  81768. if (!_this.getScene().useRightHandedSystem) {
  81769. [2, 6, 8, 9, 14].forEach(function (num) {
  81770. if (_this._standingMatrix) {
  81771. _this._standingMatrix.m[num] *= -1;
  81772. }
  81773. });
  81774. }
  81775. callback(true);
  81776. }
  81777. });
  81778. };
  81779. /**
  81780. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  81781. * @returns A promise with a boolean set to if the standing matrix is supported.
  81782. */
  81783. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  81784. var _this = this;
  81785. return new Promise(function (res, rej) {
  81786. _this.useStandingMatrix(function (supported) {
  81787. res(supported);
  81788. });
  81789. });
  81790. };
  81791. /**
  81792. * Disposes the camera
  81793. */
  81794. WebVRFreeCamera.prototype.dispose = function () {
  81795. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  81796. _super.prototype.dispose.call(this);
  81797. };
  81798. /**
  81799. * Gets a vrController by name.
  81800. * @param name The name of the controller to retreive
  81801. * @returns the controller matching the name specified or null if not found
  81802. */
  81803. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  81804. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  81805. var gp = _a[_i];
  81806. if (gp.hand === name) {
  81807. return gp;
  81808. }
  81809. }
  81810. return null;
  81811. };
  81812. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  81813. /**
  81814. * The controller corrisponding to the users left hand.
  81815. */
  81816. get: function () {
  81817. if (!this._leftController) {
  81818. this._leftController = this.getControllerByName("left");
  81819. }
  81820. return this._leftController;
  81821. },
  81822. enumerable: true,
  81823. configurable: true
  81824. });
  81825. ;
  81826. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  81827. /**
  81828. * The controller corrisponding to the users right hand.
  81829. */
  81830. get: function () {
  81831. if (!this._rightController) {
  81832. this._rightController = this.getControllerByName("right");
  81833. }
  81834. return this._rightController;
  81835. },
  81836. enumerable: true,
  81837. configurable: true
  81838. });
  81839. ;
  81840. /**
  81841. * Casts a ray forward from the vrCamera's gaze.
  81842. * @param length Length of the ray (default: 100)
  81843. * @returns the ray corrisponding to the gaze
  81844. */
  81845. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  81846. if (length === void 0) { length = 100; }
  81847. if (this.leftCamera) {
  81848. // Use left eye to avoid computation to compute center on every call
  81849. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  81850. }
  81851. else {
  81852. return _super.prototype.getForwardRay.call(this, length);
  81853. }
  81854. };
  81855. /**
  81856. * Updates the camera based on device's frame data
  81857. */
  81858. WebVRFreeCamera.prototype._checkInputs = function () {
  81859. if (this._vrDevice && this._vrDevice.isPresenting) {
  81860. this._vrDevice.getFrameData(this._frameData);
  81861. this.updateFromDevice(this._frameData.pose);
  81862. }
  81863. _super.prototype._checkInputs.call(this);
  81864. };
  81865. /**
  81866. * Updates the poseControlled values based on the input device pose.
  81867. * @param poseData Pose coming from the device
  81868. */
  81869. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  81870. if (poseData && poseData.orientation) {
  81871. this.rawPose = poseData;
  81872. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  81873. if (this.getScene().useRightHandedSystem) {
  81874. this._deviceRoomRotationQuaternion.z *= -1;
  81875. this._deviceRoomRotationQuaternion.w *= -1;
  81876. }
  81877. if (this.webVROptions.trackPosition && this.rawPose.position) {
  81878. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  81879. if (this.getScene().useRightHandedSystem) {
  81880. this._deviceRoomPosition.z *= -1;
  81881. }
  81882. }
  81883. }
  81884. };
  81885. /**
  81886. * WebVR's attach control will start broadcasting frames to the device.
  81887. * Note that in certain browsers (chrome for example) this function must be called
  81888. * within a user-interaction callback. Example:
  81889. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  81890. *
  81891. * @param element html element to attach the vrDevice to
  81892. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  81893. */
  81894. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  81895. _super.prototype.attachControl.call(this, element, noPreventDefault);
  81896. this._attached = true;
  81897. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  81898. if (this._vrDevice) {
  81899. this.getEngine().enableVR();
  81900. }
  81901. };
  81902. /**
  81903. * Detaches the camera from the html element and disables VR
  81904. *
  81905. * @param element html element to detach from
  81906. */
  81907. WebVRFreeCamera.prototype.detachControl = function (element) {
  81908. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  81909. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  81910. _super.prototype.detachControl.call(this, element);
  81911. this._attached = false;
  81912. this.getEngine().disableVR();
  81913. };
  81914. /**
  81915. * @returns the name of this class
  81916. */
  81917. WebVRFreeCamera.prototype.getClassName = function () {
  81918. return "WebVRFreeCamera";
  81919. };
  81920. /**
  81921. * Calls resetPose on the vrDisplay
  81922. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  81923. */
  81924. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  81925. //uses the vrDisplay's "resetPose()".
  81926. //pitch and roll won't be affected.
  81927. this._vrDevice.resetPose();
  81928. };
  81929. /**
  81930. * Updates the rig cameras (left and right eye)
  81931. */
  81932. WebVRFreeCamera.prototype._updateRigCameras = function () {
  81933. var camLeft = this._rigCameras[0];
  81934. var camRight = this._rigCameras[1];
  81935. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  81936. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  81937. camLeft.position.copyFrom(this._deviceRoomPosition);
  81938. camRight.position.copyFrom(this._deviceRoomPosition);
  81939. };
  81940. /**
  81941. * Updates the cached values of the camera
  81942. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  81943. */
  81944. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  81945. var _this = this;
  81946. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  81947. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  81948. if (!this.updateCacheCalled) {
  81949. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  81950. this.updateCacheCalled = true;
  81951. this.update();
  81952. }
  81953. // Set working vector to the device position in room space rotated by the new rotation
  81954. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  81955. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  81956. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  81957. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  81958. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  81959. // Add translation from anchor position
  81960. this._deviceToWorld.getTranslationToRef(this._workingVector);
  81961. this._workingVector.addInPlace(this.position);
  81962. this._workingVector.subtractInPlace(this._cache.position);
  81963. this._deviceToWorld.setTranslation(this._workingVector);
  81964. // Set an inverted matrix to be used when updating the camera
  81965. this._deviceToWorld.invertToRef(this._worldToDevice);
  81966. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  81967. this.controllers.forEach(function (controller) {
  81968. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  81969. controller.update();
  81970. });
  81971. }
  81972. if (!ignoreParentClass) {
  81973. _super.prototype._updateCache.call(this);
  81974. }
  81975. this.updateCacheCalled = false;
  81976. };
  81977. /**
  81978. * Updates the current device position and rotation in the babylon world
  81979. */
  81980. WebVRFreeCamera.prototype.update = function () {
  81981. // Get current device position in babylon world
  81982. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  81983. // Get current device rotation in babylon world
  81984. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  81985. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  81986. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  81987. _super.prototype.update.call(this);
  81988. };
  81989. /**
  81990. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  81991. * @returns an identity matrix
  81992. */
  81993. WebVRFreeCamera.prototype._getViewMatrix = function () {
  81994. return BABYLON.Matrix.Identity();
  81995. };
  81996. /**
  81997. * This function is called by the two RIG cameras.
  81998. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  81999. */
  82000. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  82001. var _this = this;
  82002. // Update the parent camera prior to using a child camera to avoid desynchronization
  82003. var parentCamera = this._cameraRigParams["parentCamera"];
  82004. parentCamera._updateCache();
  82005. //WebVR 1.1
  82006. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  82007. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  82008. if (!this.getScene().useRightHandedSystem) {
  82009. [2, 6, 8, 9, 14].forEach(function (num) {
  82010. _this._webvrViewMatrix.m[num] *= -1;
  82011. });
  82012. }
  82013. // update the camera rotation matrix
  82014. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  82015. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  82016. // Computing target and final matrix
  82017. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  82018. // should the view matrix be updated with scale and position offset?
  82019. if (parentCamera.deviceScaleFactor !== 1) {
  82020. this._webvrViewMatrix.invert();
  82021. // scale the position, if set
  82022. if (parentCamera.deviceScaleFactor) {
  82023. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  82024. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  82025. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  82026. }
  82027. this._webvrViewMatrix.invert();
  82028. }
  82029. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  82030. return this._webvrViewMatrix;
  82031. };
  82032. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  82033. var _this = this;
  82034. var parentCamera = this.parent;
  82035. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  82036. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  82037. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  82038. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  82039. //babylon compatible matrix
  82040. if (!this.getScene().useRightHandedSystem) {
  82041. [8, 9, 10, 11].forEach(function (num) {
  82042. _this._projectionMatrix.m[num] *= -1;
  82043. });
  82044. }
  82045. return this._projectionMatrix;
  82046. };
  82047. /**
  82048. * Initializes the controllers and their meshes
  82049. */
  82050. WebVRFreeCamera.prototype.initControllers = function () {
  82051. var _this = this;
  82052. this.controllers = [];
  82053. var manager = this.getScene().gamepadManager;
  82054. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  82055. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  82056. var webVrController = gamepad;
  82057. if (webVrController.defaultModel) {
  82058. webVrController.defaultModel.setEnabled(false);
  82059. }
  82060. if (webVrController.hand === "right") {
  82061. _this._rightController = null;
  82062. }
  82063. if (webVrController.hand === "left") {
  82064. _this._leftController = null;
  82065. }
  82066. var controllerIndex = _this.controllers.indexOf(webVrController);
  82067. if (controllerIndex !== -1) {
  82068. _this.controllers.splice(controllerIndex, 1);
  82069. }
  82070. }
  82071. });
  82072. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  82073. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  82074. var webVrController_1 = gamepad;
  82075. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  82076. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  82077. if (_this.webVROptions.controllerMeshes) {
  82078. if (webVrController_1.defaultModel) {
  82079. webVrController_1.defaultModel.setEnabled(true);
  82080. }
  82081. else {
  82082. // Load the meshes
  82083. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  82084. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  82085. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  82086. if (_this.webVROptions.defaultLightingOnControllers) {
  82087. if (!_this._lightOnControllers) {
  82088. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  82089. }
  82090. var activateLightOnSubMeshes_1 = function (mesh, light) {
  82091. var children = mesh.getChildren();
  82092. if (children.length !== 0) {
  82093. children.forEach(function (mesh) {
  82094. light.includedOnlyMeshes.push(mesh);
  82095. activateLightOnSubMeshes_1(mesh, light);
  82096. });
  82097. }
  82098. };
  82099. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  82100. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  82101. }
  82102. });
  82103. }
  82104. }
  82105. webVrController_1.attachToPoseControlledCamera(_this);
  82106. // since this is async - sanity check. Is the controller already stored?
  82107. if (_this.controllers.indexOf(webVrController_1) === -1) {
  82108. //add to the controllers array
  82109. _this.controllers.push(webVrController_1);
  82110. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  82111. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  82112. // So we're overriding setting left & right manually to be sure
  82113. var firstViveWandDetected = false;
  82114. for (var i = 0; i < _this.controllers.length; i++) {
  82115. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  82116. if (!firstViveWandDetected) {
  82117. firstViveWandDetected = true;
  82118. _this.controllers[i].hand = "left";
  82119. }
  82120. else {
  82121. _this.controllers[i].hand = "right";
  82122. }
  82123. }
  82124. }
  82125. //did we find enough controllers? Great! let the developer know.
  82126. if (_this.controllers.length >= 2) {
  82127. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  82128. }
  82129. }
  82130. }
  82131. });
  82132. };
  82133. return WebVRFreeCamera;
  82134. }(BABYLON.FreeCamera));
  82135. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  82136. })(BABYLON || (BABYLON = {}));
  82137. //# sourceMappingURL=babylon.webVRCamera.js.map
  82138. "use strict";
  82139. var BABYLON;
  82140. (function (BABYLON) {
  82141. // We're mainly based on the logic defined into the FreeCamera code
  82142. /**
  82143. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  82144. * being tilted forward or back and left or right.
  82145. */
  82146. var DeviceOrientationCamera = /** @class */ (function (_super) {
  82147. __extends(DeviceOrientationCamera, _super);
  82148. /**
  82149. * Creates a new device orientation camera. @see DeviceOrientationCamera
  82150. * @param name The name of the camera
  82151. * @param position The start position camera
  82152. * @param scene The scene the camera belongs to
  82153. */
  82154. function DeviceOrientationCamera(name, position, scene) {
  82155. var _this = _super.call(this, name, position, scene) || this;
  82156. _this._quaternionCache = new BABYLON.Quaternion();
  82157. _this.inputs.addDeviceOrientation();
  82158. return _this;
  82159. }
  82160. /**
  82161. * Gets the current instance class name ("DeviceOrientationCamera").
  82162. * This helps avoiding instanceof at run time.
  82163. * @returns the class name
  82164. */
  82165. DeviceOrientationCamera.prototype.getClassName = function () {
  82166. return "DeviceOrientationCamera";
  82167. };
  82168. /**
  82169. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  82170. */
  82171. DeviceOrientationCamera.prototype._checkInputs = function () {
  82172. _super.prototype._checkInputs.call(this);
  82173. this._quaternionCache.copyFrom(this.rotationQuaternion);
  82174. if (this._initialQuaternion) {
  82175. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  82176. }
  82177. };
  82178. /**
  82179. * Reset the camera to its default orientation on the specified axis only.
  82180. * @param axis The axis to reset
  82181. */
  82182. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  82183. var _this = this;
  82184. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  82185. //can only work if this camera has a rotation quaternion already.
  82186. if (!this.rotationQuaternion)
  82187. return;
  82188. if (!this._initialQuaternion) {
  82189. this._initialQuaternion = new BABYLON.Quaternion();
  82190. }
  82191. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  82192. ['x', 'y', 'z'].forEach(function (axisName) {
  82193. if (!axis[axisName]) {
  82194. _this._initialQuaternion[axisName] = 0;
  82195. }
  82196. else {
  82197. _this._initialQuaternion[axisName] *= -1;
  82198. }
  82199. });
  82200. this._initialQuaternion.normalize();
  82201. //force rotation update
  82202. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  82203. };
  82204. return DeviceOrientationCamera;
  82205. }(BABYLON.FreeCamera));
  82206. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  82207. })(BABYLON || (BABYLON = {}));
  82208. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  82209. "use strict";
  82210. var BABYLON;
  82211. (function (BABYLON) {
  82212. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  82213. __extends(VRDeviceOrientationFreeCamera, _super);
  82214. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  82215. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82216. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82217. var _this = _super.call(this, name, position, scene) || this;
  82218. vrCameraMetrics.compensateDistortion = compensateDistortion;
  82219. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  82220. return _this;
  82221. }
  82222. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  82223. return "VRDeviceOrientationFreeCamera";
  82224. };
  82225. return VRDeviceOrientationFreeCamera;
  82226. }(BABYLON.DeviceOrientationCamera));
  82227. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  82228. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  82229. __extends(VRDeviceOrientationGamepadCamera, _super);
  82230. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  82231. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82232. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82233. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  82234. _this.inputs.addGamepad();
  82235. return _this;
  82236. }
  82237. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  82238. return "VRDeviceOrientationGamepadCamera";
  82239. };
  82240. return VRDeviceOrientationGamepadCamera;
  82241. }(VRDeviceOrientationFreeCamera));
  82242. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  82243. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  82244. __extends(VRDeviceOrientationArcRotateCamera, _super);
  82245. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  82246. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82247. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82248. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82249. vrCameraMetrics.compensateDistortion = compensateDistortion;
  82250. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  82251. _this.inputs.addVRDeviceOrientation();
  82252. return _this;
  82253. }
  82254. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  82255. return "VRDeviceOrientationArcRotateCamera";
  82256. };
  82257. return VRDeviceOrientationArcRotateCamera;
  82258. }(BABYLON.ArcRotateCamera));
  82259. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  82260. })(BABYLON || (BABYLON = {}));
  82261. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  82262. "use strict";
  82263. var BABYLON;
  82264. (function (BABYLON) {
  82265. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  82266. __extends(AnaglyphFreeCamera, _super);
  82267. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  82268. var _this = _super.call(this, name, position, scene) || this;
  82269. _this.interaxialDistance = interaxialDistance;
  82270. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82271. return _this;
  82272. }
  82273. AnaglyphFreeCamera.prototype.getClassName = function () {
  82274. return "AnaglyphFreeCamera";
  82275. };
  82276. return AnaglyphFreeCamera;
  82277. }(BABYLON.FreeCamera));
  82278. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  82279. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  82280. __extends(AnaglyphArcRotateCamera, _super);
  82281. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  82282. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82283. _this.interaxialDistance = interaxialDistance;
  82284. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82285. return _this;
  82286. }
  82287. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  82288. return "AnaglyphArcRotateCamera";
  82289. };
  82290. return AnaglyphArcRotateCamera;
  82291. }(BABYLON.ArcRotateCamera));
  82292. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  82293. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  82294. __extends(AnaglyphGamepadCamera, _super);
  82295. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  82296. var _this = _super.call(this, name, position, scene) || this;
  82297. _this.interaxialDistance = interaxialDistance;
  82298. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82299. return _this;
  82300. }
  82301. AnaglyphGamepadCamera.prototype.getClassName = function () {
  82302. return "AnaglyphGamepadCamera";
  82303. };
  82304. return AnaglyphGamepadCamera;
  82305. }(BABYLON.GamepadCamera));
  82306. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  82307. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  82308. __extends(AnaglyphUniversalCamera, _super);
  82309. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  82310. var _this = _super.call(this, name, position, scene) || this;
  82311. _this.interaxialDistance = interaxialDistance;
  82312. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82313. return _this;
  82314. }
  82315. AnaglyphUniversalCamera.prototype.getClassName = function () {
  82316. return "AnaglyphUniversalCamera";
  82317. };
  82318. return AnaglyphUniversalCamera;
  82319. }(BABYLON.UniversalCamera));
  82320. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  82321. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  82322. __extends(StereoscopicFreeCamera, _super);
  82323. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82324. var _this = _super.call(this, name, position, scene) || this;
  82325. _this.interaxialDistance = interaxialDistance;
  82326. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82327. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82328. return _this;
  82329. }
  82330. StereoscopicFreeCamera.prototype.getClassName = function () {
  82331. return "StereoscopicFreeCamera";
  82332. };
  82333. return StereoscopicFreeCamera;
  82334. }(BABYLON.FreeCamera));
  82335. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  82336. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  82337. __extends(StereoscopicArcRotateCamera, _super);
  82338. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  82339. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82340. _this.interaxialDistance = interaxialDistance;
  82341. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82342. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82343. return _this;
  82344. }
  82345. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  82346. return "StereoscopicArcRotateCamera";
  82347. };
  82348. return StereoscopicArcRotateCamera;
  82349. }(BABYLON.ArcRotateCamera));
  82350. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  82351. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  82352. __extends(StereoscopicGamepadCamera, _super);
  82353. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82354. var _this = _super.call(this, name, position, scene) || this;
  82355. _this.interaxialDistance = interaxialDistance;
  82356. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82357. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82358. return _this;
  82359. }
  82360. StereoscopicGamepadCamera.prototype.getClassName = function () {
  82361. return "StereoscopicGamepadCamera";
  82362. };
  82363. return StereoscopicGamepadCamera;
  82364. }(BABYLON.GamepadCamera));
  82365. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  82366. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  82367. __extends(StereoscopicUniversalCamera, _super);
  82368. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82369. var _this = _super.call(this, name, position, scene) || this;
  82370. _this.interaxialDistance = interaxialDistance;
  82371. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82372. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82373. return _this;
  82374. }
  82375. StereoscopicUniversalCamera.prototype.getClassName = function () {
  82376. return "StereoscopicUniversalCamera";
  82377. };
  82378. return StereoscopicUniversalCamera;
  82379. }(BABYLON.UniversalCamera));
  82380. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  82381. })(BABYLON || (BABYLON = {}));
  82382. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  82383. "use strict";
  82384. var BABYLON;
  82385. (function (BABYLON) {
  82386. var VRExperienceHelperGazer = /** @class */ (function () {
  82387. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  82388. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  82389. this.scene = scene;
  82390. this._pointerDownOnMeshAsked = false;
  82391. this._isActionableMesh = false;
  82392. this._teleportationRequestInitiated = false;
  82393. this._teleportationBackRequestInitiated = false;
  82394. this._dpadPressed = true;
  82395. this._activePointer = false;
  82396. this._id = VRExperienceHelperGazer._idCounter++;
  82397. // Gaze tracker
  82398. if (!gazeTrackerToClone) {
  82399. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  82400. this._gazeTracker.bakeCurrentTransformIntoVertices();
  82401. this._gazeTracker.isPickable = false;
  82402. this._gazeTracker.isVisible = false;
  82403. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  82404. targetMat.specularColor = BABYLON.Color3.Black();
  82405. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  82406. targetMat.backFaceCulling = false;
  82407. this._gazeTracker.material = targetMat;
  82408. }
  82409. else {
  82410. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  82411. }
  82412. }
  82413. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  82414. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  82415. };
  82416. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  82417. this._pointerDownOnMeshAsked = true;
  82418. if (this._currentMeshSelected && this._currentHit) {
  82419. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  82420. }
  82421. };
  82422. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  82423. if (this._currentMeshSelected && this._currentHit) {
  82424. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  82425. }
  82426. this._pointerDownOnMeshAsked = false;
  82427. };
  82428. VRExperienceHelperGazer.prototype._activatePointer = function () {
  82429. this._activePointer = true;
  82430. };
  82431. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  82432. this._activePointer = false;
  82433. };
  82434. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  82435. };
  82436. VRExperienceHelperGazer.prototype.dispose = function () {
  82437. this._interactionsEnabled = false;
  82438. this._teleportationEnabled = false;
  82439. };
  82440. VRExperienceHelperGazer._idCounter = 0;
  82441. return VRExperienceHelperGazer;
  82442. }());
  82443. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  82444. __extends(VRExperienceHelperControllerGazer, _super);
  82445. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  82446. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  82447. _this.webVRController = webVRController;
  82448. // Laser pointer
  82449. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  82450. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  82451. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  82452. laserPointerMaterial.alpha = 0.6;
  82453. _this._laserPointer.material = laserPointerMaterial;
  82454. _this._laserPointer.rotation.x = Math.PI / 2;
  82455. _this._laserPointer.position.z = -0.5;
  82456. _this._laserPointer.isVisible = false;
  82457. if (!webVRController.mesh) {
  82458. // Create an empty mesh that is used prior to loading the high quality model
  82459. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  82460. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  82461. preloadPointerPose.rotation.x = -0.7;
  82462. preloadMesh.addChild(preloadPointerPose);
  82463. webVRController.attachToMesh(preloadMesh);
  82464. }
  82465. _this._setLaserPointerParent(webVRController.mesh);
  82466. return _this;
  82467. }
  82468. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  82469. return this.webVRController.getForwardRay(length);
  82470. };
  82471. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  82472. _super.prototype._activatePointer.call(this);
  82473. this._laserPointer.isVisible = true;
  82474. };
  82475. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  82476. _super.prototype._deactivatePointer.call(this);
  82477. this._laserPointer.isVisible = false;
  82478. };
  82479. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  82480. this._laserPointer.material.emissiveColor = color;
  82481. };
  82482. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  82483. var makeNotPick = function (root) {
  82484. root.name += " laserPointer";
  82485. root.getChildMeshes().forEach(function (c) {
  82486. makeNotPick(c);
  82487. });
  82488. };
  82489. makeNotPick(mesh);
  82490. var childMeshes = mesh.getChildMeshes();
  82491. this.webVRController._pointingPoseNode = null;
  82492. for (var i = 0; i < childMeshes.length; i++) {
  82493. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  82494. mesh = childMeshes[i];
  82495. this.webVRController._pointingPoseNode = mesh;
  82496. break;
  82497. }
  82498. }
  82499. this._laserPointer.parent = mesh;
  82500. };
  82501. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  82502. this._laserPointer.scaling.y = distance;
  82503. this._laserPointer.position.z = -distance / 2;
  82504. };
  82505. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  82506. _super.prototype.dispose.call(this);
  82507. this._laserPointer.dispose();
  82508. };
  82509. return VRExperienceHelperControllerGazer;
  82510. }(VRExperienceHelperGazer));
  82511. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  82512. __extends(VRExperienceHelperCameraGazer, _super);
  82513. function VRExperienceHelperCameraGazer(getCamera, scene) {
  82514. var _this = _super.call(this, scene) || this;
  82515. _this.getCamera = getCamera;
  82516. return _this;
  82517. }
  82518. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  82519. var camera = this.getCamera();
  82520. if (camera) {
  82521. return camera.getForwardRay(length);
  82522. }
  82523. else {
  82524. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  82525. }
  82526. };
  82527. return VRExperienceHelperCameraGazer;
  82528. }(VRExperienceHelperGazer));
  82529. /**
  82530. * Helps to quickly add VR support to an existing scene.
  82531. * See http://doc.babylonjs.com/how_to/webvr_helper
  82532. */
  82533. var VRExperienceHelper = /** @class */ (function () {
  82534. /**
  82535. * Instantiates a VRExperienceHelper.
  82536. * Helps to quickly add VR support to an existing scene.
  82537. * @param scene The scene the VRExperienceHelper belongs to.
  82538. * @param webVROptions Options to modify the vr experience helper's behavior.
  82539. */
  82540. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  82541. if (webVROptions === void 0) { webVROptions = {}; }
  82542. var _this = this;
  82543. this.webVROptions = webVROptions;
  82544. // Can the system support WebVR, even if a headset isn't plugged in?
  82545. this._webVRsupported = false;
  82546. // If WebVR is supported, is a headset plugged in and are we ready to present?
  82547. this._webVRready = false;
  82548. // Are we waiting for the requestPresent callback to complete?
  82549. this._webVRrequesting = false;
  82550. // Are we presenting to the headset right now?
  82551. this._webVRpresenting = false;
  82552. // Are we presenting in the fullscreen fallback?
  82553. this._fullscreenVRpresenting = false;
  82554. /**
  82555. * Observable raised when entering VR.
  82556. */
  82557. this.onEnteringVRObservable = new BABYLON.Observable();
  82558. /**
  82559. * Observable raised when exiting VR.
  82560. */
  82561. this.onExitingVRObservable = new BABYLON.Observable();
  82562. /**
  82563. * Observable raised when controller mesh is loaded.
  82564. */
  82565. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  82566. this._useCustomVRButton = false;
  82567. this._teleportationRequested = false;
  82568. this._teleportActive = false;
  82569. this._floorMeshesCollection = [];
  82570. this._rotationAllowed = true;
  82571. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  82572. this._rotationRightAsked = false;
  82573. this._rotationLeftAsked = false;
  82574. this._isDefaultTeleportationTarget = true;
  82575. this._teleportationFillColor = "#444444";
  82576. this._teleportationBorderColor = "#FFFFFF";
  82577. this._rotationAngle = 0;
  82578. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  82579. this._padSensibilityUp = 0.65;
  82580. this._padSensibilityDown = 0.35;
  82581. this.leftController = null;
  82582. this.rightController = null;
  82583. /**
  82584. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  82585. */
  82586. this.onNewMeshSelected = new BABYLON.Observable();
  82587. /**
  82588. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  82589. */
  82590. this.onNewMeshPicked = new BABYLON.Observable();
  82591. /**
  82592. * Observable raised before camera teleportation
  82593. */
  82594. this.onBeforeCameraTeleport = new BABYLON.Observable();
  82595. /**
  82596. * Observable raised after camera teleportation
  82597. */
  82598. this.onAfterCameraTeleport = new BABYLON.Observable();
  82599. /**
  82600. * Observable raised when current selected mesh gets unselected
  82601. */
  82602. this.onSelectedMeshUnselected = new BABYLON.Observable();
  82603. /**
  82604. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  82605. */
  82606. this.teleportationEnabled = true;
  82607. this._teleportationInitialized = false;
  82608. this._interactionsEnabled = false;
  82609. this._interactionsRequested = false;
  82610. this._displayGaze = true;
  82611. this._displayLaserPointer = true;
  82612. this._onResize = function () {
  82613. _this.moveButtonToBottomRight();
  82614. if (_this._fullscreenVRpresenting && _this._webVRready) {
  82615. _this.exitVR();
  82616. }
  82617. };
  82618. this._onFullscreenChange = function () {
  82619. if (document.fullscreen !== undefined) {
  82620. _this._fullscreenVRpresenting = document.fullscreen;
  82621. }
  82622. else if (document.mozFullScreen !== undefined) {
  82623. _this._fullscreenVRpresenting = document.mozFullScreen;
  82624. }
  82625. else if (document.webkitIsFullScreen !== undefined) {
  82626. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  82627. }
  82628. else if (document.msIsFullScreen !== undefined) {
  82629. _this._fullscreenVRpresenting = document.msIsFullScreen;
  82630. }
  82631. if (!_this._fullscreenVRpresenting && _this._canvas) {
  82632. _this.exitVR();
  82633. if (!_this._useCustomVRButton) {
  82634. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  82635. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  82636. }
  82637. }
  82638. };
  82639. this.beforeRender = function () {
  82640. if (_this.leftController && _this.leftController._activePointer) {
  82641. _this._castRayAndSelectObject(_this.leftController);
  82642. }
  82643. if (_this.rightController && _this.rightController._activePointer) {
  82644. _this._castRayAndSelectObject(_this.rightController);
  82645. }
  82646. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  82647. _this._castRayAndSelectObject(_this._cameraGazer);
  82648. }
  82649. else {
  82650. _this._cameraGazer._gazeTracker.isVisible = false;
  82651. }
  82652. };
  82653. this._onNewGamepadConnected = function (gamepad) {
  82654. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  82655. if (gamepad.leftStick) {
  82656. gamepad.onleftstickchanged(function (stickValues) {
  82657. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  82658. // Listening to classic/xbox gamepad only if no VR controller is active
  82659. if ((!_this.leftController && !_this.rightController) ||
  82660. ((_this.leftController && !_this.leftController._activePointer) &&
  82661. (_this.rightController && !_this.rightController._activePointer))) {
  82662. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  82663. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  82664. }
  82665. }
  82666. });
  82667. }
  82668. if (gamepad.rightStick) {
  82669. gamepad.onrightstickchanged(function (stickValues) {
  82670. if (_this._teleportationInitialized) {
  82671. _this._checkRotate(stickValues, _this._cameraGazer);
  82672. }
  82673. });
  82674. }
  82675. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  82676. gamepad.onbuttondown(function (buttonPressed) {
  82677. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  82678. _this._cameraGazer._selectionPointerDown();
  82679. }
  82680. });
  82681. gamepad.onbuttonup(function (buttonPressed) {
  82682. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  82683. _this._cameraGazer._selectionPointerUp();
  82684. }
  82685. });
  82686. }
  82687. }
  82688. else {
  82689. var webVRController = gamepad;
  82690. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  82691. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  82692. _this.rightController = controller;
  82693. }
  82694. else {
  82695. _this.leftController = controller;
  82696. }
  82697. _this._tryEnableInteractionOnController(controller);
  82698. }
  82699. };
  82700. // 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
  82701. this._tryEnableInteractionOnController = function (controller) {
  82702. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  82703. _this._enableInteractionOnController(controller);
  82704. }
  82705. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  82706. _this._enableTeleportationOnController(controller);
  82707. }
  82708. };
  82709. this._onNewGamepadDisconnected = function (gamepad) {
  82710. if (gamepad instanceof BABYLON.WebVRController) {
  82711. if (gamepad.hand === "left" && _this.leftController != null) {
  82712. _this.leftController.dispose();
  82713. _this.leftController = null;
  82714. }
  82715. if (gamepad.hand === "right" && _this.rightController != null) {
  82716. _this.rightController.dispose();
  82717. _this.rightController = null;
  82718. }
  82719. }
  82720. };
  82721. this._workingVector = BABYLON.Vector3.Zero();
  82722. this._workingQuaternion = BABYLON.Quaternion.Identity();
  82723. this._workingMatrix = BABYLON.Matrix.Identity();
  82724. this._scene = scene;
  82725. this._canvas = scene.getEngine().getRenderingCanvas();
  82726. // Parse options
  82727. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  82728. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  82729. }
  82730. if (webVROptions.createDeviceOrientationCamera === undefined) {
  82731. webVROptions.createDeviceOrientationCamera = true;
  82732. }
  82733. if (webVROptions.defaultHeight === undefined) {
  82734. webVROptions.defaultHeight = 1.7;
  82735. }
  82736. if (webVROptions.useCustomVRButton) {
  82737. this._useCustomVRButton = true;
  82738. if (webVROptions.customVRButton) {
  82739. this._btnVR = webVROptions.customVRButton;
  82740. }
  82741. }
  82742. if (webVROptions.rayLength) {
  82743. this._rayLength = webVROptions.rayLength;
  82744. }
  82745. this._defaultHeight = webVROptions.defaultHeight;
  82746. if (webVROptions.positionScale) {
  82747. this._rayLength *= webVROptions.positionScale;
  82748. this._defaultHeight *= webVROptions.positionScale;
  82749. }
  82750. // Set position
  82751. if (this._scene.activeCamera) {
  82752. this._position = this._scene.activeCamera.position.clone();
  82753. }
  82754. else {
  82755. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  82756. }
  82757. // Set non-vr camera
  82758. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  82759. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  82760. // Copy data from existing camera
  82761. if (this._scene.activeCamera) {
  82762. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  82763. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  82764. // Set rotation from previous camera
  82765. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  82766. var targetCamera = this._scene.activeCamera;
  82767. if (targetCamera.rotationQuaternion) {
  82768. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  82769. }
  82770. else {
  82771. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  82772. }
  82773. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  82774. }
  82775. }
  82776. this._scene.activeCamera = this._deviceOrientationCamera;
  82777. if (this._canvas) {
  82778. this._scene.activeCamera.attachControl(this._canvas);
  82779. }
  82780. }
  82781. else {
  82782. this._existingCamera = this._scene.activeCamera;
  82783. }
  82784. // Create VR cameras
  82785. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  82786. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  82787. }
  82788. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  82789. this._webVRCamera.useStandingMatrix();
  82790. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  82791. // Create default button
  82792. if (!this._useCustomVRButton) {
  82793. this._btnVR = document.createElement("BUTTON");
  82794. this._btnVR.className = "babylonVRicon";
  82795. this._btnVR.id = "babylonVRiconbtn";
  82796. this._btnVR.title = "Click to switch to VR";
  82797. 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) }";
  82798. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  82799. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  82800. // css += ".babylonVRicon.vrdisplaysupported { }";
  82801. // css += ".babylonVRicon.vrdisplayready { }";
  82802. // css += ".babylonVRicon.vrdisplayrequesting { }";
  82803. var style = document.createElement('style');
  82804. style.appendChild(document.createTextNode(css));
  82805. document.getElementsByTagName('head')[0].appendChild(style);
  82806. this.moveButtonToBottomRight();
  82807. }
  82808. // VR button click event
  82809. if (this._btnVR) {
  82810. this._btnVR.addEventListener("click", function () {
  82811. if (!_this.isInVRMode) {
  82812. _this.enterVR();
  82813. }
  82814. else {
  82815. _this.exitVR();
  82816. }
  82817. });
  82818. }
  82819. // Window events
  82820. window.addEventListener("resize", this._onResize);
  82821. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  82822. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  82823. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  82824. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  82825. // Display vr button when headset is connected
  82826. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  82827. this.displayVRButton();
  82828. }
  82829. else {
  82830. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  82831. if (e.vrDisplay) {
  82832. _this.displayVRButton();
  82833. }
  82834. });
  82835. }
  82836. // Exiting VR mode using 'ESC' key on desktop
  82837. this._onKeyDown = function (event) {
  82838. if (event.keyCode === 27 && _this.isInVRMode) {
  82839. _this.exitVR();
  82840. }
  82841. };
  82842. document.addEventListener("keydown", this._onKeyDown);
  82843. // Exiting VR mode double tapping the touch screen
  82844. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  82845. if (_this.isInVRMode) {
  82846. _this.exitVR();
  82847. if (_this._fullscreenVRpresenting) {
  82848. _this._scene.getEngine().switchFullscreen(true);
  82849. }
  82850. }
  82851. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  82852. // Listen for WebVR display changes
  82853. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  82854. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  82855. this._onVRRequestPresentStart = function () {
  82856. _this._webVRrequesting = true;
  82857. _this.updateButtonVisibility();
  82858. };
  82859. this._onVRRequestPresentComplete = function (success) {
  82860. _this._webVRrequesting = false;
  82861. _this.updateButtonVisibility();
  82862. };
  82863. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  82864. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  82865. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  82866. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82867. scene.onDisposeObservable.add(function () {
  82868. _this.dispose();
  82869. });
  82870. // Gamepad connection events
  82871. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  82872. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  82873. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  82874. this.updateButtonVisibility();
  82875. //create easing functions
  82876. this._circleEase = new BABYLON.CircleEase();
  82877. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  82878. }
  82879. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  82880. /** Return this.onEnteringVRObservable
  82881. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  82882. */
  82883. get: function () {
  82884. return this.onEnteringVRObservable;
  82885. },
  82886. enumerable: true,
  82887. configurable: true
  82888. });
  82889. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  82890. /** Return this.onExitingVRObservable
  82891. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  82892. */
  82893. get: function () {
  82894. return this.onExitingVRObservable;
  82895. },
  82896. enumerable: true,
  82897. configurable: true
  82898. });
  82899. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  82900. /** Return this.onControllerMeshLoadedObservable
  82901. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  82902. */
  82903. get: function () {
  82904. return this.onControllerMeshLoadedObservable;
  82905. },
  82906. enumerable: true,
  82907. configurable: true
  82908. });
  82909. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  82910. /**
  82911. * The mesh used to display where the user is going to teleport.
  82912. */
  82913. get: function () {
  82914. return this._teleportationTarget;
  82915. },
  82916. /**
  82917. * Sets the mesh to be used to display where the user is going to teleport.
  82918. */
  82919. set: function (value) {
  82920. if (value) {
  82921. value.name = "teleportationTarget";
  82922. this._isDefaultTeleportationTarget = false;
  82923. this._teleportationTarget = value;
  82924. }
  82925. },
  82926. enumerable: true,
  82927. configurable: true
  82928. });
  82929. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  82930. /**
  82931. * The mesh used to display where the user is selecting,
  82932. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  82933. * See http://doc.babylonjs.com/resources/baking_transformations
  82934. */
  82935. get: function () {
  82936. return this._cameraGazer._gazeTracker;
  82937. },
  82938. set: function (value) {
  82939. if (value) {
  82940. this._cameraGazer._gazeTracker = value;
  82941. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  82942. this._cameraGazer._gazeTracker.isPickable = false;
  82943. this._cameraGazer._gazeTracker.isVisible = false;
  82944. this._cameraGazer._gazeTracker.name = "gazeTracker";
  82945. if (this.leftController) {
  82946. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  82947. }
  82948. if (this.rightController) {
  82949. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  82950. }
  82951. }
  82952. },
  82953. enumerable: true,
  82954. configurable: true
  82955. });
  82956. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  82957. /**
  82958. * If the ray of the gaze should be displayed.
  82959. */
  82960. get: function () {
  82961. return this._displayGaze;
  82962. },
  82963. /**
  82964. * Sets if the ray of the gaze should be displayed.
  82965. */
  82966. set: function (value) {
  82967. this._displayGaze = value;
  82968. if (!value) {
  82969. this._cameraGazer._gazeTracker.isVisible = false;
  82970. if (this.leftController) {
  82971. this.leftController._gazeTracker.isVisible = false;
  82972. }
  82973. if (this.rightController) {
  82974. this.rightController._gazeTracker.isVisible = false;
  82975. }
  82976. }
  82977. },
  82978. enumerable: true,
  82979. configurable: true
  82980. });
  82981. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  82982. /**
  82983. * If the ray of the LaserPointer should be displayed.
  82984. */
  82985. get: function () {
  82986. return this._displayLaserPointer;
  82987. },
  82988. /**
  82989. * Sets if the ray of the LaserPointer should be displayed.
  82990. */
  82991. set: function (value) {
  82992. this._displayLaserPointer = value;
  82993. if (!value) {
  82994. if (this.rightController) {
  82995. this.rightController._deactivatePointer();
  82996. this.rightController._gazeTracker.isVisible = false;
  82997. }
  82998. if (this.leftController) {
  82999. this.leftController._deactivatePointer();
  83000. this.leftController._gazeTracker.isVisible = false;
  83001. }
  83002. }
  83003. else {
  83004. if (this.rightController) {
  83005. this.rightController._activatePointer();
  83006. }
  83007. else if (this.leftController) {
  83008. this.leftController._activatePointer();
  83009. }
  83010. }
  83011. },
  83012. enumerable: true,
  83013. configurable: true
  83014. });
  83015. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  83016. /**
  83017. * The deviceOrientationCamera used as the camera when not in VR.
  83018. */
  83019. get: function () {
  83020. return this._deviceOrientationCamera;
  83021. },
  83022. enumerable: true,
  83023. configurable: true
  83024. });
  83025. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  83026. /**
  83027. * Based on the current WebVR support, returns the current VR camera used.
  83028. */
  83029. get: function () {
  83030. if (this._webVRready) {
  83031. return this._webVRCamera;
  83032. }
  83033. else {
  83034. return this._scene.activeCamera;
  83035. }
  83036. },
  83037. enumerable: true,
  83038. configurable: true
  83039. });
  83040. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  83041. /**
  83042. * The webVRCamera which is used when in VR.
  83043. */
  83044. get: function () {
  83045. return this._webVRCamera;
  83046. },
  83047. enumerable: true,
  83048. configurable: true
  83049. });
  83050. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  83051. /**
  83052. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  83053. */
  83054. get: function () {
  83055. return this._vrDeviceOrientationCamera;
  83056. },
  83057. enumerable: true,
  83058. configurable: true
  83059. });
  83060. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  83061. get: function () {
  83062. var result = this._cameraGazer._teleportationRequestInitiated
  83063. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  83064. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  83065. return result;
  83066. },
  83067. enumerable: true,
  83068. configurable: true
  83069. });
  83070. // Raised when one of the controller has loaded successfully its associated default mesh
  83071. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  83072. if (this.leftController && this.leftController.webVRController == webVRController) {
  83073. if (webVRController.mesh) {
  83074. this.leftController._setLaserPointerParent(webVRController.mesh);
  83075. }
  83076. }
  83077. if (this.rightController && this.rightController.webVRController == webVRController) {
  83078. if (webVRController.mesh) {
  83079. this.rightController._setLaserPointerParent(webVRController.mesh);
  83080. }
  83081. }
  83082. try {
  83083. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  83084. }
  83085. catch (err) {
  83086. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  83087. }
  83088. };
  83089. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  83090. /**
  83091. * Gets a value indicating if we are currently in VR mode.
  83092. */
  83093. get: function () {
  83094. return this._webVRpresenting || this._fullscreenVRpresenting;
  83095. },
  83096. enumerable: true,
  83097. configurable: true
  83098. });
  83099. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  83100. var vrDisplay = this._scene.getEngine().getVRDevice();
  83101. if (vrDisplay) {
  83102. var wasPresenting = this._webVRpresenting;
  83103. // A VR display is connected
  83104. this._webVRpresenting = vrDisplay.isPresenting;
  83105. if (wasPresenting && !this._webVRpresenting)
  83106. this.exitVR();
  83107. }
  83108. else {
  83109. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  83110. }
  83111. this.updateButtonVisibility();
  83112. };
  83113. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  83114. this._webVRsupported = eventArgs.vrSupported;
  83115. this._webVRready = !!eventArgs.vrDisplay;
  83116. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  83117. this.updateButtonVisibility();
  83118. };
  83119. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  83120. if (this._canvas && !this._useCustomVRButton) {
  83121. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  83122. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  83123. }
  83124. };
  83125. VRExperienceHelper.prototype.displayVRButton = function () {
  83126. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  83127. document.body.appendChild(this._btnVR);
  83128. this._btnVRDisplayed = true;
  83129. }
  83130. };
  83131. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  83132. if (!this._btnVR || this._useCustomVRButton) {
  83133. return;
  83134. }
  83135. this._btnVR.className = "babylonVRicon";
  83136. if (this.isInVRMode) {
  83137. this._btnVR.className += " vrdisplaypresenting";
  83138. }
  83139. else {
  83140. if (this._webVRready)
  83141. this._btnVR.className += " vrdisplayready";
  83142. if (this._webVRsupported)
  83143. this._btnVR.className += " vrdisplaysupported";
  83144. if (this._webVRrequesting)
  83145. this._btnVR.className += " vrdisplayrequesting";
  83146. }
  83147. };
  83148. /**
  83149. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  83150. * Otherwise, will use the fullscreen API.
  83151. */
  83152. VRExperienceHelper.prototype.enterVR = function () {
  83153. if (this.onEnteringVRObservable) {
  83154. try {
  83155. this.onEnteringVRObservable.notifyObservers(this);
  83156. }
  83157. catch (err) {
  83158. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  83159. }
  83160. }
  83161. if (this._scene.activeCamera) {
  83162. this._position = this._scene.activeCamera.position.clone();
  83163. // make sure that we return to the last active camera
  83164. this._existingCamera = this._scene.activeCamera;
  83165. }
  83166. if (this._webVRrequesting)
  83167. return;
  83168. // If WebVR is supported and a headset is connected
  83169. if (this._webVRready) {
  83170. if (!this._webVRpresenting) {
  83171. this._webVRCamera.position = this._position;
  83172. this._scene.activeCamera = this._webVRCamera;
  83173. }
  83174. }
  83175. else if (this._vrDeviceOrientationCamera) {
  83176. this._vrDeviceOrientationCamera.position = this._position;
  83177. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  83178. this._scene.getEngine().switchFullscreen(true);
  83179. this.updateButtonVisibility();
  83180. }
  83181. if (this._scene.activeCamera && this._canvas) {
  83182. this._scene.activeCamera.attachControl(this._canvas);
  83183. }
  83184. if (this._interactionsEnabled) {
  83185. this._scene.registerBeforeRender(this.beforeRender);
  83186. }
  83187. };
  83188. /**
  83189. * Attempt to exit VR, or fullscreen.
  83190. */
  83191. VRExperienceHelper.prototype.exitVR = function () {
  83192. if (this.onExitingVRObservable) {
  83193. try {
  83194. this.onExitingVRObservable.notifyObservers(this);
  83195. }
  83196. catch (err) {
  83197. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  83198. }
  83199. }
  83200. if (this._webVRpresenting) {
  83201. this._scene.getEngine().disableVR();
  83202. }
  83203. if (this._scene.activeCamera) {
  83204. this._position = this._scene.activeCamera.position.clone();
  83205. }
  83206. if (this._deviceOrientationCamera) {
  83207. this._deviceOrientationCamera.position = this._position;
  83208. this._scene.activeCamera = this._deviceOrientationCamera;
  83209. if (this._canvas) {
  83210. this._scene.activeCamera.attachControl(this._canvas);
  83211. }
  83212. }
  83213. else if (this._existingCamera) {
  83214. this._existingCamera.position = this._position;
  83215. this._scene.activeCamera = this._existingCamera;
  83216. }
  83217. this.updateButtonVisibility();
  83218. if (this._interactionsEnabled) {
  83219. this._scene.unregisterBeforeRender(this.beforeRender);
  83220. }
  83221. };
  83222. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  83223. /**
  83224. * The position of the vr experience helper.
  83225. */
  83226. get: function () {
  83227. return this._position;
  83228. },
  83229. /**
  83230. * Sets the position of the vr experience helper.
  83231. */
  83232. set: function (value) {
  83233. this._position = value;
  83234. if (this._scene.activeCamera) {
  83235. this._scene.activeCamera.position = value;
  83236. }
  83237. },
  83238. enumerable: true,
  83239. configurable: true
  83240. });
  83241. /**
  83242. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  83243. */
  83244. VRExperienceHelper.prototype.enableInteractions = function () {
  83245. var _this = this;
  83246. if (!this._interactionsEnabled) {
  83247. this._interactionsRequested = true;
  83248. if (this.leftController) {
  83249. this._enableInteractionOnController(this.leftController);
  83250. }
  83251. if (this.rightController) {
  83252. this._enableInteractionOnController(this.rightController);
  83253. }
  83254. this.raySelectionPredicate = function (mesh) {
  83255. return mesh.isVisible;
  83256. };
  83257. this.meshSelectionPredicate = function (mesh) {
  83258. return true;
  83259. };
  83260. this._raySelectionPredicate = function (mesh) {
  83261. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  83262. && mesh.name.indexOf("teleportationTarget") === -1
  83263. && mesh.name.indexOf("torusTeleportation") === -1
  83264. && mesh.name.indexOf("laserPointer") === -1)) {
  83265. return _this.raySelectionPredicate(mesh);
  83266. }
  83267. return false;
  83268. };
  83269. this._interactionsEnabled = true;
  83270. }
  83271. };
  83272. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  83273. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  83274. if (this._floorMeshesCollection[i].id === mesh.id) {
  83275. return true;
  83276. }
  83277. }
  83278. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  83279. return true;
  83280. }
  83281. return false;
  83282. };
  83283. /**
  83284. * Adds a floor mesh to be used for teleportation.
  83285. * @param floorMesh the mesh to be used for teleportation.
  83286. */
  83287. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  83288. if (!this._floorMeshesCollection) {
  83289. return;
  83290. }
  83291. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  83292. return;
  83293. }
  83294. this._floorMeshesCollection.push(floorMesh);
  83295. };
  83296. /**
  83297. * Removes a floor mesh from being used for teleportation.
  83298. * @param floorMesh the mesh to be removed.
  83299. */
  83300. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  83301. if (!this._floorMeshesCollection) {
  83302. return;
  83303. }
  83304. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  83305. if (meshIndex !== -1) {
  83306. this._floorMeshesCollection.splice(meshIndex, 1);
  83307. }
  83308. };
  83309. /**
  83310. * Enables interactions and teleportation using the VR controllers and gaze.
  83311. * @param vrTeleportationOptions options to modify teleportation behavior.
  83312. */
  83313. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  83314. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  83315. if (!this._teleportationInitialized) {
  83316. this._teleportationRequested = true;
  83317. this.enableInteractions();
  83318. if (vrTeleportationOptions.floorMeshName) {
  83319. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  83320. }
  83321. if (vrTeleportationOptions.floorMeshes) {
  83322. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  83323. }
  83324. if (this.leftController != null) {
  83325. this._enableTeleportationOnController(this.leftController);
  83326. }
  83327. if (this.rightController != null) {
  83328. this._enableTeleportationOnController(this.rightController);
  83329. }
  83330. // Creates an image processing post process for the vignette not relying
  83331. // on the main scene configuration for image processing to reduce setup and spaces
  83332. // (gamma/linear) conflicts.
  83333. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  83334. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  83335. imageProcessingConfiguration.vignetteEnabled = true;
  83336. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  83337. this._webVRCamera.detachPostProcess(this._postProcessMove);
  83338. this._teleportationInitialized = true;
  83339. if (this._isDefaultTeleportationTarget) {
  83340. this._createTeleportationCircles();
  83341. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  83342. }
  83343. }
  83344. };
  83345. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  83346. var _this = this;
  83347. var controllerMesh = controller.webVRController.mesh;
  83348. if (controllerMesh) {
  83349. controller._interactionsEnabled = true;
  83350. controller._activatePointer();
  83351. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  83352. // Enabling / disabling laserPointer
  83353. if (_this._displayLaserPointer && stateObject.value === 1) {
  83354. if (controller._activePointer) {
  83355. controller._deactivatePointer();
  83356. }
  83357. else {
  83358. controller._activatePointer();
  83359. }
  83360. if (_this.displayGaze) {
  83361. controller._gazeTracker.isVisible = controller._activePointer;
  83362. }
  83363. }
  83364. });
  83365. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  83366. if (!controller._pointerDownOnMeshAsked) {
  83367. if (stateObject.value > _this._padSensibilityUp) {
  83368. controller._selectionPointerDown();
  83369. }
  83370. }
  83371. else if (stateObject.value < _this._padSensibilityDown) {
  83372. controller._selectionPointerUp();
  83373. }
  83374. });
  83375. }
  83376. };
  83377. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  83378. // Dont teleport if another gaze already requested teleportation
  83379. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  83380. return;
  83381. }
  83382. if (!gazer._teleportationRequestInitiated) {
  83383. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  83384. gazer._activatePointer();
  83385. gazer._teleportationRequestInitiated = true;
  83386. }
  83387. }
  83388. else {
  83389. // Listening to the proper controller values changes to confirm teleportation
  83390. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  83391. if (this._teleportActive) {
  83392. this._teleportCamera(this._haloCenter);
  83393. }
  83394. gazer._teleportationRequestInitiated = false;
  83395. }
  83396. }
  83397. };
  83398. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  83399. // Only rotate when user is not currently selecting a teleportation location
  83400. if (gazer._teleportationRequestInitiated) {
  83401. return;
  83402. }
  83403. if (!this._rotationLeftAsked) {
  83404. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  83405. this._rotationLeftAsked = true;
  83406. if (this._rotationAllowed) {
  83407. this._rotateCamera(false);
  83408. }
  83409. }
  83410. }
  83411. else {
  83412. if (stateObject.x > -this._padSensibilityDown) {
  83413. this._rotationLeftAsked = false;
  83414. }
  83415. }
  83416. if (!this._rotationRightAsked) {
  83417. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  83418. this._rotationRightAsked = true;
  83419. if (this._rotationAllowed) {
  83420. this._rotateCamera(true);
  83421. }
  83422. }
  83423. }
  83424. else {
  83425. if (stateObject.x < this._padSensibilityDown) {
  83426. this._rotationRightAsked = false;
  83427. }
  83428. }
  83429. };
  83430. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  83431. // Only teleport backwards when user is not currently selecting a teleportation location
  83432. if (gazer._teleportationRequestInitiated) {
  83433. return;
  83434. }
  83435. // Teleport backwards
  83436. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  83437. if (!gazer._teleportationBackRequestInitiated) {
  83438. if (!this.currentVRCamera) {
  83439. return;
  83440. }
  83441. // Get rotation and position of the current camera
  83442. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  83443. var position = this.currentVRCamera.position;
  83444. // If the camera has device position, use that instead
  83445. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  83446. rotation = this.currentVRCamera.deviceRotationQuaternion;
  83447. position = this.currentVRCamera.devicePosition;
  83448. }
  83449. // Get matrix with only the y rotation of the device rotation
  83450. rotation.toEulerAnglesToRef(this._workingVector);
  83451. this._workingVector.z = 0;
  83452. this._workingVector.x = 0;
  83453. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  83454. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  83455. // Rotate backwards ray by device rotation to cast at the ground behind the user
  83456. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  83457. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  83458. var ray = new BABYLON.Ray(position, this._workingVector);
  83459. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  83460. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  83461. this._teleportCamera(hit.pickedPoint);
  83462. }
  83463. gazer._teleportationBackRequestInitiated = true;
  83464. }
  83465. }
  83466. else {
  83467. gazer._teleportationBackRequestInitiated = false;
  83468. }
  83469. };
  83470. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  83471. var _this = this;
  83472. var controllerMesh = controller.webVRController.mesh;
  83473. if (controllerMesh) {
  83474. if (!controller._interactionsEnabled) {
  83475. this._enableInteractionOnController(controller);
  83476. }
  83477. controller._interactionsEnabled = true;
  83478. controller._teleportationEnabled = true;
  83479. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  83480. controller._dpadPressed = false;
  83481. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  83482. controller._dpadPressed = stateObject.pressed;
  83483. if (!controller._dpadPressed) {
  83484. _this._rotationLeftAsked = false;
  83485. _this._rotationRightAsked = false;
  83486. controller._teleportationBackRequestInitiated = false;
  83487. }
  83488. });
  83489. }
  83490. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  83491. if (_this.teleportationEnabled) {
  83492. _this._checkTeleportBackwards(stateObject, controller);
  83493. _this._checkTeleportWithRay(stateObject, controller);
  83494. }
  83495. _this._checkRotate(stateObject, controller);
  83496. });
  83497. }
  83498. };
  83499. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  83500. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  83501. this._teleportationTarget.isPickable = false;
  83502. var length = 512;
  83503. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  83504. dynamicTexture.hasAlpha = true;
  83505. var context = dynamicTexture.getContext();
  83506. var centerX = length / 2;
  83507. var centerY = length / 2;
  83508. var radius = 200;
  83509. context.beginPath();
  83510. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  83511. context.fillStyle = this._teleportationFillColor;
  83512. context.fill();
  83513. context.lineWidth = 10;
  83514. context.strokeStyle = this._teleportationBorderColor;
  83515. context.stroke();
  83516. context.closePath();
  83517. dynamicTexture.update();
  83518. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  83519. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  83520. this._teleportationTarget.material = teleportationCircleMaterial;
  83521. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  83522. torus.isPickable = false;
  83523. torus.parent = this._teleportationTarget;
  83524. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  83525. var keys = [];
  83526. keys.push({
  83527. frame: 0,
  83528. value: 0
  83529. });
  83530. keys.push({
  83531. frame: 30,
  83532. value: 0.4
  83533. });
  83534. keys.push({
  83535. frame: 60,
  83536. value: 0
  83537. });
  83538. animationInnerCircle.setKeys(keys);
  83539. var easingFunction = new BABYLON.SineEase();
  83540. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  83541. animationInnerCircle.setEasingFunction(easingFunction);
  83542. torus.animations = [];
  83543. torus.animations.push(animationInnerCircle);
  83544. this._scene.beginAnimation(torus, 0, 60, true);
  83545. this._hideTeleportationTarget();
  83546. };
  83547. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  83548. this._teleportActive = true;
  83549. if (this._teleportationInitialized) {
  83550. this._teleportationTarget.isVisible = true;
  83551. if (this._isDefaultTeleportationTarget) {
  83552. this._teleportationTarget.getChildren()[0].isVisible = true;
  83553. }
  83554. }
  83555. };
  83556. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  83557. this._teleportActive = false;
  83558. if (this._teleportationInitialized) {
  83559. this._teleportationTarget.isVisible = false;
  83560. if (this._isDefaultTeleportationTarget) {
  83561. this._teleportationTarget.getChildren()[0].isVisible = false;
  83562. }
  83563. }
  83564. };
  83565. VRExperienceHelper.prototype._rotateCamera = function (right) {
  83566. var _this = this;
  83567. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83568. return;
  83569. }
  83570. if (right) {
  83571. this._rotationAngle++;
  83572. }
  83573. else {
  83574. this._rotationAngle--;
  83575. }
  83576. this.currentVRCamera.animations = [];
  83577. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  83578. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83579. var animationRotationKeys = [];
  83580. animationRotationKeys.push({
  83581. frame: 0,
  83582. value: this.currentVRCamera.rotationQuaternion
  83583. });
  83584. animationRotationKeys.push({
  83585. frame: 6,
  83586. value: target
  83587. });
  83588. animationRotation.setKeys(animationRotationKeys);
  83589. animationRotation.setEasingFunction(this._circleEase);
  83590. this.currentVRCamera.animations.push(animationRotation);
  83591. this._postProcessMove.animations = [];
  83592. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83593. var vignetteWeightKeys = [];
  83594. vignetteWeightKeys.push({
  83595. frame: 0,
  83596. value: 0
  83597. });
  83598. vignetteWeightKeys.push({
  83599. frame: 3,
  83600. value: 4
  83601. });
  83602. vignetteWeightKeys.push({
  83603. frame: 6,
  83604. value: 0
  83605. });
  83606. animationPP.setKeys(vignetteWeightKeys);
  83607. animationPP.setEasingFunction(this._circleEase);
  83608. this._postProcessMove.animations.push(animationPP);
  83609. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83610. var vignetteStretchKeys = [];
  83611. vignetteStretchKeys.push({
  83612. frame: 0,
  83613. value: 0
  83614. });
  83615. vignetteStretchKeys.push({
  83616. frame: 3,
  83617. value: 10
  83618. });
  83619. vignetteStretchKeys.push({
  83620. frame: 6,
  83621. value: 0
  83622. });
  83623. animationPP2.setKeys(vignetteStretchKeys);
  83624. animationPP2.setEasingFunction(this._circleEase);
  83625. this._postProcessMove.animations.push(animationPP2);
  83626. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  83627. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  83628. this._postProcessMove.samples = 4;
  83629. this._webVRCamera.attachPostProcess(this._postProcessMove);
  83630. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  83631. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  83632. });
  83633. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  83634. };
  83635. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  83636. if (hit.pickedPoint) {
  83637. if (gazer._teleportationRequestInitiated) {
  83638. this._displayTeleportationTarget();
  83639. this._haloCenter.copyFrom(hit.pickedPoint);
  83640. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  83641. }
  83642. var pickNormal = hit.getNormal(true, false);
  83643. if (pickNormal) {
  83644. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  83645. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  83646. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  83647. }
  83648. this._teleportationTarget.position.y += 0.1;
  83649. }
  83650. };
  83651. VRExperienceHelper.prototype._teleportCamera = function (location) {
  83652. var _this = this;
  83653. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83654. return;
  83655. }
  83656. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  83657. // offset of the headset from the anchor.
  83658. if (this.webVRCamera.leftCamera) {
  83659. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  83660. this._workingVector.subtractInPlace(this.webVRCamera.position);
  83661. location.subtractToRef(this._workingVector, this._workingVector);
  83662. }
  83663. else {
  83664. this._workingVector.copyFrom(location);
  83665. }
  83666. // Add height to account for user's height offset
  83667. if (this.isInVRMode) {
  83668. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  83669. }
  83670. else {
  83671. this._workingVector.y += this._defaultHeight;
  83672. }
  83673. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  83674. // Create animation from the camera's position to the new location
  83675. this.currentVRCamera.animations = [];
  83676. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83677. var animationCameraTeleportationKeys = [{
  83678. frame: 0,
  83679. value: this.currentVRCamera.position
  83680. },
  83681. {
  83682. frame: 11,
  83683. value: this._workingVector
  83684. }
  83685. ];
  83686. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  83687. animationCameraTeleportation.setEasingFunction(this._circleEase);
  83688. this.currentVRCamera.animations.push(animationCameraTeleportation);
  83689. this._postProcessMove.animations = [];
  83690. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83691. var vignetteWeightKeys = [];
  83692. vignetteWeightKeys.push({
  83693. frame: 0,
  83694. value: 0
  83695. });
  83696. vignetteWeightKeys.push({
  83697. frame: 5,
  83698. value: 8
  83699. });
  83700. vignetteWeightKeys.push({
  83701. frame: 11,
  83702. value: 0
  83703. });
  83704. animationPP.setKeys(vignetteWeightKeys);
  83705. this._postProcessMove.animations.push(animationPP);
  83706. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83707. var vignetteStretchKeys = [];
  83708. vignetteStretchKeys.push({
  83709. frame: 0,
  83710. value: 0
  83711. });
  83712. vignetteStretchKeys.push({
  83713. frame: 5,
  83714. value: 10
  83715. });
  83716. vignetteStretchKeys.push({
  83717. frame: 11,
  83718. value: 0
  83719. });
  83720. animationPP2.setKeys(vignetteStretchKeys);
  83721. this._postProcessMove.animations.push(animationPP2);
  83722. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  83723. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  83724. this._webVRCamera.attachPostProcess(this._postProcessMove);
  83725. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  83726. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  83727. });
  83728. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  83729. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  83730. });
  83731. this._hideTeleportationTarget();
  83732. };
  83733. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  83734. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83735. return;
  83736. }
  83737. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  83738. // Moving the gazeTracker on the mesh face targetted
  83739. if (hit && hit.pickedPoint) {
  83740. if (this._displayGaze) {
  83741. var multiplier = 1;
  83742. gazer._gazeTracker.isVisible = true;
  83743. if (gazer._isActionableMesh) {
  83744. multiplier = 3;
  83745. }
  83746. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  83747. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  83748. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  83749. var pickNormal = hit.getNormal();
  83750. // To avoid z-fighting
  83751. var deltaFighting = 0.002;
  83752. if (pickNormal) {
  83753. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  83754. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  83755. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  83756. }
  83757. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  83758. if (gazer._gazeTracker.position.x < 0) {
  83759. gazer._gazeTracker.position.x += deltaFighting;
  83760. }
  83761. else {
  83762. gazer._gazeTracker.position.x -= deltaFighting;
  83763. }
  83764. if (gazer._gazeTracker.position.y < 0) {
  83765. gazer._gazeTracker.position.y += deltaFighting;
  83766. }
  83767. else {
  83768. gazer._gazeTracker.position.y -= deltaFighting;
  83769. }
  83770. if (gazer._gazeTracker.position.z < 0) {
  83771. gazer._gazeTracker.position.z += deltaFighting;
  83772. }
  83773. else {
  83774. gazer._gazeTracker.position.z -= deltaFighting;
  83775. }
  83776. }
  83777. // Changing the size of the laser pointer based on the distance from the targetted point
  83778. gazer._updatePointerDistance(hit.distance);
  83779. }
  83780. else {
  83781. gazer._gazeTracker.isVisible = false;
  83782. }
  83783. if (hit && hit.pickedMesh) {
  83784. gazer._currentHit = hit;
  83785. if (gazer._pointerDownOnMeshAsked) {
  83786. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  83787. }
  83788. // The object selected is the floor, we're in a teleportation scenario
  83789. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  83790. // Moving the teleportation area to this targetted point
  83791. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  83792. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  83793. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83794. }
  83795. gazer._currentMeshSelected = null;
  83796. if (gazer._teleportationRequestInitiated) {
  83797. this._moveTeleportationSelectorTo(hit, gazer);
  83798. }
  83799. return;
  83800. }
  83801. // If not, we're in a selection scenario
  83802. //this._teleportationAllowed = false;
  83803. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  83804. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  83805. this.onNewMeshPicked.notifyObservers(hit);
  83806. gazer._currentMeshSelected = hit.pickedMesh;
  83807. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  83808. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  83809. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  83810. gazer._isActionableMesh = true;
  83811. }
  83812. else {
  83813. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83814. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83815. gazer._isActionableMesh = false;
  83816. }
  83817. try {
  83818. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  83819. }
  83820. catch (err) {
  83821. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  83822. }
  83823. }
  83824. else {
  83825. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83826. gazer._currentMeshSelected = null;
  83827. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83828. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83829. }
  83830. }
  83831. }
  83832. else {
  83833. gazer._currentHit = null;
  83834. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83835. gazer._currentMeshSelected = null;
  83836. //this._teleportationAllowed = false;
  83837. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83838. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83839. }
  83840. };
  83841. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  83842. if (mesh) {
  83843. this.onSelectedMeshUnselected.notifyObservers(mesh);
  83844. }
  83845. };
  83846. /**
  83847. * Sets the color of the laser ray from the vr controllers.
  83848. * @param color new color for the ray.
  83849. */
  83850. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  83851. if (this.leftController) {
  83852. this.leftController._setLaserPointerColor(color);
  83853. }
  83854. if (this.rightController) {
  83855. this.rightController._setLaserPointerColor(color);
  83856. }
  83857. };
  83858. /**
  83859. * Sets the color of the ray from the vr headsets gaze.
  83860. * @param color new color for the ray.
  83861. */
  83862. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  83863. if (!this._cameraGazer._gazeTracker.material) {
  83864. return;
  83865. }
  83866. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  83867. if (this.leftController) {
  83868. this.leftController._gazeTracker.material.emissiveColor = color;
  83869. }
  83870. if (this.rightController) {
  83871. this.rightController._gazeTracker.material.emissiveColor = color;
  83872. }
  83873. };
  83874. /**
  83875. * Exits VR and disposes of the vr experience helper
  83876. */
  83877. VRExperienceHelper.prototype.dispose = function () {
  83878. if (this.isInVRMode) {
  83879. this.exitVR();
  83880. }
  83881. if (this._postProcessMove) {
  83882. this._postProcessMove.dispose();
  83883. }
  83884. if (this._webVRCamera) {
  83885. this._webVRCamera.dispose();
  83886. }
  83887. if (this._vrDeviceOrientationCamera) {
  83888. this._vrDeviceOrientationCamera.dispose();
  83889. }
  83890. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  83891. document.body.removeChild(this._btnVR);
  83892. }
  83893. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  83894. this._deviceOrientationCamera.dispose();
  83895. }
  83896. if (this._cameraGazer) {
  83897. this._cameraGazer.dispose();
  83898. }
  83899. if (this.leftController) {
  83900. this.leftController.dispose();
  83901. }
  83902. if (this.rightController) {
  83903. this.rightController.dispose();
  83904. }
  83905. if (this._teleportationTarget) {
  83906. this._teleportationTarget.dispose();
  83907. }
  83908. this._floorMeshesCollection = [];
  83909. document.removeEventListener("keydown", this._onKeyDown);
  83910. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  83911. window.removeEventListener("resize", this._onResize);
  83912. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  83913. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  83914. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  83915. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  83916. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  83917. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  83918. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  83919. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  83920. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  83921. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  83922. this._scene.unregisterBeforeRender(this.beforeRender);
  83923. };
  83924. /**
  83925. * Gets the name of the VRExperienceHelper class
  83926. * @returns "VRExperienceHelper"
  83927. */
  83928. VRExperienceHelper.prototype.getClassName = function () {
  83929. return "VRExperienceHelper";
  83930. };
  83931. return VRExperienceHelper;
  83932. }());
  83933. BABYLON.VRExperienceHelper = VRExperienceHelper;
  83934. })(BABYLON || (BABYLON = {}));
  83935. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  83936. "use strict";
  83937. // Mainly based on these 2 articles :
  83938. // 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
  83939. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  83940. var BABYLON;
  83941. (function (BABYLON) {
  83942. var JoystickAxis;
  83943. (function (JoystickAxis) {
  83944. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  83945. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  83946. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  83947. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  83948. var VirtualJoystick = /** @class */ (function () {
  83949. function VirtualJoystick(leftJoystick) {
  83950. var _this = this;
  83951. if (leftJoystick) {
  83952. this._leftJoystick = true;
  83953. }
  83954. else {
  83955. this._leftJoystick = false;
  83956. }
  83957. VirtualJoystick._globalJoystickIndex++;
  83958. // By default left & right arrow keys are moving the X
  83959. // and up & down keys are moving the Y
  83960. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  83961. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  83962. this.reverseLeftRight = false;
  83963. this.reverseUpDown = false;
  83964. // collections of pointers
  83965. this._touches = new BABYLON.StringDictionary();
  83966. this.deltaPosition = BABYLON.Vector3.Zero();
  83967. this._joystickSensibility = 25;
  83968. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  83969. this._onResize = function (evt) {
  83970. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  83971. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  83972. if (VirtualJoystick.vjCanvas) {
  83973. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  83974. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  83975. }
  83976. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  83977. };
  83978. // injecting a canvas element on top of the canvas 3D game
  83979. if (!VirtualJoystick.vjCanvas) {
  83980. window.addEventListener("resize", this._onResize, false);
  83981. VirtualJoystick.vjCanvas = document.createElement("canvas");
  83982. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  83983. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  83984. VirtualJoystick.vjCanvas.width = window.innerWidth;
  83985. VirtualJoystick.vjCanvas.height = window.innerHeight;
  83986. VirtualJoystick.vjCanvas.style.width = "100%";
  83987. VirtualJoystick.vjCanvas.style.height = "100%";
  83988. VirtualJoystick.vjCanvas.style.position = "absolute";
  83989. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  83990. VirtualJoystick.vjCanvas.style.top = "0px";
  83991. VirtualJoystick.vjCanvas.style.left = "0px";
  83992. VirtualJoystick.vjCanvas.style.zIndex = "5";
  83993. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  83994. // Support for jQuery PEP polyfill
  83995. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  83996. var context = VirtualJoystick.vjCanvas.getContext('2d');
  83997. if (!context) {
  83998. throw new Error("Unable to create canvas for virtual joystick");
  83999. }
  84000. VirtualJoystick.vjCanvasContext = context;
  84001. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  84002. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  84003. document.body.appendChild(VirtualJoystick.vjCanvas);
  84004. }
  84005. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  84006. this.pressed = false;
  84007. // default joystick color
  84008. this._joystickColor = "cyan";
  84009. this._joystickPointerID = -1;
  84010. // current joystick position
  84011. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  84012. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  84013. // origin joystick position
  84014. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  84015. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  84016. this._onPointerDownHandlerRef = function (evt) {
  84017. _this._onPointerDown(evt);
  84018. };
  84019. this._onPointerMoveHandlerRef = function (evt) {
  84020. _this._onPointerMove(evt);
  84021. };
  84022. this._onPointerUpHandlerRef = function (evt) {
  84023. _this._onPointerUp(evt);
  84024. };
  84025. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  84026. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  84027. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  84028. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  84029. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  84030. evt.preventDefault(); // Disables system menu
  84031. }, false);
  84032. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  84033. }
  84034. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  84035. this._joystickSensibility = newJoystickSensibility;
  84036. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  84037. };
  84038. VirtualJoystick.prototype._onPointerDown = function (e) {
  84039. var positionOnScreenCondition;
  84040. e.preventDefault();
  84041. if (this._leftJoystick === true) {
  84042. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  84043. }
  84044. else {
  84045. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  84046. }
  84047. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  84048. // First contact will be dedicated to the virtual joystick
  84049. this._joystickPointerID = e.pointerId;
  84050. this._joystickPointerStartPos.x = e.clientX;
  84051. this._joystickPointerStartPos.y = e.clientY;
  84052. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  84053. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  84054. this._deltaJoystickVector.x = 0;
  84055. this._deltaJoystickVector.y = 0;
  84056. this.pressed = true;
  84057. this._touches.add(e.pointerId.toString(), e);
  84058. }
  84059. else {
  84060. // You can only trigger the action buttons with a joystick declared
  84061. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  84062. this._action();
  84063. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  84064. }
  84065. }
  84066. };
  84067. VirtualJoystick.prototype._onPointerMove = function (e) {
  84068. // If the current pointer is the one associated to the joystick (first touch contact)
  84069. if (this._joystickPointerID == e.pointerId) {
  84070. this._joystickPointerPos.x = e.clientX;
  84071. this._joystickPointerPos.y = e.clientY;
  84072. this._deltaJoystickVector = this._joystickPointerPos.clone();
  84073. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  84074. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  84075. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  84076. switch (this._axisTargetedByLeftAndRight) {
  84077. case JoystickAxis.X:
  84078. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  84079. break;
  84080. case JoystickAxis.Y:
  84081. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  84082. break;
  84083. case JoystickAxis.Z:
  84084. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  84085. break;
  84086. }
  84087. var directionUpDown = this.reverseUpDown ? 1 : -1;
  84088. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  84089. switch (this._axisTargetedByUpAndDown) {
  84090. case JoystickAxis.X:
  84091. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  84092. break;
  84093. case JoystickAxis.Y:
  84094. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  84095. break;
  84096. case JoystickAxis.Z:
  84097. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  84098. break;
  84099. }
  84100. }
  84101. else {
  84102. var data = this._touches.get(e.pointerId.toString());
  84103. if (data) {
  84104. data.x = e.clientX;
  84105. data.y = e.clientY;
  84106. }
  84107. }
  84108. };
  84109. VirtualJoystick.prototype._onPointerUp = function (e) {
  84110. if (this._joystickPointerID == e.pointerId) {
  84111. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  84112. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  84113. this._joystickPointerID = -1;
  84114. this.pressed = false;
  84115. }
  84116. else {
  84117. var touch = this._touches.get(e.pointerId.toString());
  84118. if (touch) {
  84119. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  84120. }
  84121. }
  84122. this._deltaJoystickVector.x = 0;
  84123. this._deltaJoystickVector.y = 0;
  84124. this._touches.remove(e.pointerId.toString());
  84125. };
  84126. /**
  84127. * Change the color of the virtual joystick
  84128. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  84129. */
  84130. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  84131. this._joystickColor = newColor;
  84132. };
  84133. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  84134. this._action = action;
  84135. };
  84136. // Define which axis you'd like to control for left & right
  84137. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  84138. switch (axis) {
  84139. case JoystickAxis.X:
  84140. case JoystickAxis.Y:
  84141. case JoystickAxis.Z:
  84142. this._axisTargetedByLeftAndRight = axis;
  84143. break;
  84144. default:
  84145. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  84146. break;
  84147. }
  84148. };
  84149. // Define which axis you'd like to control for up & down
  84150. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  84151. switch (axis) {
  84152. case JoystickAxis.X:
  84153. case JoystickAxis.Y:
  84154. case JoystickAxis.Z:
  84155. this._axisTargetedByUpAndDown = axis;
  84156. break;
  84157. default:
  84158. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  84159. break;
  84160. }
  84161. };
  84162. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  84163. var _this = this;
  84164. if (this.pressed) {
  84165. this._touches.forEach(function (key, touch) {
  84166. if (touch.pointerId === _this._joystickPointerID) {
  84167. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  84168. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  84169. VirtualJoystick.vjCanvasContext.beginPath();
  84170. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  84171. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84172. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  84173. VirtualJoystick.vjCanvasContext.stroke();
  84174. VirtualJoystick.vjCanvasContext.closePath();
  84175. VirtualJoystick.vjCanvasContext.beginPath();
  84176. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84177. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  84178. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  84179. VirtualJoystick.vjCanvasContext.stroke();
  84180. VirtualJoystick.vjCanvasContext.closePath();
  84181. VirtualJoystick.vjCanvasContext.beginPath();
  84182. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84183. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  84184. VirtualJoystick.vjCanvasContext.stroke();
  84185. VirtualJoystick.vjCanvasContext.closePath();
  84186. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  84187. }
  84188. else {
  84189. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  84190. VirtualJoystick.vjCanvasContext.beginPath();
  84191. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  84192. VirtualJoystick.vjCanvasContext.beginPath();
  84193. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  84194. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  84195. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  84196. VirtualJoystick.vjCanvasContext.stroke();
  84197. VirtualJoystick.vjCanvasContext.closePath();
  84198. touch.prevX = touch.x;
  84199. touch.prevY = touch.y;
  84200. }
  84201. ;
  84202. });
  84203. }
  84204. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  84205. };
  84206. VirtualJoystick.prototype.releaseCanvas = function () {
  84207. if (VirtualJoystick.vjCanvas) {
  84208. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  84209. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  84210. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  84211. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  84212. window.removeEventListener("resize", this._onResize);
  84213. document.body.removeChild(VirtualJoystick.vjCanvas);
  84214. VirtualJoystick.vjCanvas = null;
  84215. }
  84216. };
  84217. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  84218. VirtualJoystick._globalJoystickIndex = 0;
  84219. return VirtualJoystick;
  84220. }());
  84221. BABYLON.VirtualJoystick = VirtualJoystick;
  84222. })(BABYLON || (BABYLON = {}));
  84223. //# sourceMappingURL=babylon.virtualJoystick.js.map
  84224. "use strict";
  84225. var BABYLON;
  84226. (function (BABYLON) {
  84227. // We're mainly based on the logic defined into the FreeCamera code
  84228. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  84229. __extends(VirtualJoysticksCamera, _super);
  84230. function VirtualJoysticksCamera(name, position, scene) {
  84231. var _this = _super.call(this, name, position, scene) || this;
  84232. _this.inputs.addVirtualJoystick();
  84233. return _this;
  84234. }
  84235. VirtualJoysticksCamera.prototype.getClassName = function () {
  84236. return "VirtualJoysticksCamera";
  84237. };
  84238. return VirtualJoysticksCamera;
  84239. }(BABYLON.FreeCamera));
  84240. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  84241. })(BABYLON || (BABYLON = {}));
  84242. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  84243. "use strict";
  84244. var BABYLON;
  84245. (function (BABYLON) {
  84246. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  84247. function FreeCameraVirtualJoystickInput() {
  84248. }
  84249. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  84250. return this._leftjoystick;
  84251. };
  84252. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  84253. return this._rightjoystick;
  84254. };
  84255. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  84256. if (this._leftjoystick) {
  84257. var camera = this.camera;
  84258. var speed = camera._computeLocalCameraSpeed() * 50;
  84259. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  84260. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  84261. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  84262. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  84263. if (!this._leftjoystick.pressed) {
  84264. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  84265. }
  84266. if (!this._rightjoystick.pressed) {
  84267. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  84268. }
  84269. }
  84270. };
  84271. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  84272. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  84273. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  84274. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  84275. this._leftjoystick.setJoystickSensibility(0.15);
  84276. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  84277. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  84278. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  84279. this._rightjoystick.reverseUpDown = true;
  84280. this._rightjoystick.setJoystickSensibility(0.05);
  84281. this._rightjoystick.setJoystickColor("yellow");
  84282. };
  84283. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  84284. this._leftjoystick.releaseCanvas();
  84285. this._rightjoystick.releaseCanvas();
  84286. };
  84287. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  84288. return "FreeCameraVirtualJoystickInput";
  84289. };
  84290. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  84291. return "virtualJoystick";
  84292. };
  84293. return FreeCameraVirtualJoystickInput;
  84294. }());
  84295. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  84296. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  84297. })(BABYLON || (BABYLON = {}));
  84298. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  84299. "use strict";
  84300. var BABYLON;
  84301. (function (BABYLON) {
  84302. var SimplificationSettings = /** @class */ (function () {
  84303. function SimplificationSettings(quality, distance, optimizeMesh) {
  84304. this.quality = quality;
  84305. this.distance = distance;
  84306. this.optimizeMesh = optimizeMesh;
  84307. }
  84308. return SimplificationSettings;
  84309. }());
  84310. BABYLON.SimplificationSettings = SimplificationSettings;
  84311. var SimplificationQueue = /** @class */ (function () {
  84312. function SimplificationQueue() {
  84313. this.running = false;
  84314. this._simplificationArray = [];
  84315. }
  84316. SimplificationQueue.prototype.addTask = function (task) {
  84317. this._simplificationArray.push(task);
  84318. };
  84319. SimplificationQueue.prototype.executeNext = function () {
  84320. var task = this._simplificationArray.pop();
  84321. if (task) {
  84322. this.running = true;
  84323. this.runSimplification(task);
  84324. }
  84325. else {
  84326. this.running = false;
  84327. }
  84328. };
  84329. SimplificationQueue.prototype.runSimplification = function (task) {
  84330. var _this = this;
  84331. if (task.parallelProcessing) {
  84332. //parallel simplifier
  84333. task.settings.forEach(function (setting) {
  84334. var simplifier = _this.getSimplifier(task);
  84335. simplifier.simplify(setting, function (newMesh) {
  84336. task.mesh.addLODLevel(setting.distance, newMesh);
  84337. newMesh.isVisible = true;
  84338. //check if it is the last
  84339. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  84340. //all done, run the success callback.
  84341. task.successCallback();
  84342. }
  84343. _this.executeNext();
  84344. });
  84345. });
  84346. }
  84347. else {
  84348. //single simplifier.
  84349. var simplifier = this.getSimplifier(task);
  84350. var runDecimation = function (setting, callback) {
  84351. simplifier.simplify(setting, function (newMesh) {
  84352. task.mesh.addLODLevel(setting.distance, newMesh);
  84353. newMesh.isVisible = true;
  84354. //run the next quality level
  84355. callback();
  84356. });
  84357. };
  84358. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  84359. runDecimation(task.settings[loop.index], function () {
  84360. loop.executeNext();
  84361. });
  84362. }, function () {
  84363. //execution ended, run the success callback.
  84364. if (task.successCallback) {
  84365. task.successCallback();
  84366. }
  84367. _this.executeNext();
  84368. });
  84369. }
  84370. };
  84371. SimplificationQueue.prototype.getSimplifier = function (task) {
  84372. switch (task.simplificationType) {
  84373. case SimplificationType.QUADRATIC:
  84374. default:
  84375. return new QuadraticErrorSimplification(task.mesh);
  84376. }
  84377. };
  84378. return SimplificationQueue;
  84379. }());
  84380. BABYLON.SimplificationQueue = SimplificationQueue;
  84381. /**
  84382. * The implemented types of simplification.
  84383. * At the moment only Quadratic Error Decimation is implemented.
  84384. */
  84385. var SimplificationType;
  84386. (function (SimplificationType) {
  84387. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  84388. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  84389. var DecimationTriangle = /** @class */ (function () {
  84390. function DecimationTriangle(vertices) {
  84391. this.vertices = vertices;
  84392. this.error = new Array(4);
  84393. this.deleted = false;
  84394. this.isDirty = false;
  84395. this.deletePending = false;
  84396. this.borderFactor = 0;
  84397. }
  84398. return DecimationTriangle;
  84399. }());
  84400. BABYLON.DecimationTriangle = DecimationTriangle;
  84401. var DecimationVertex = /** @class */ (function () {
  84402. function DecimationVertex(position, id) {
  84403. this.position = position;
  84404. this.id = id;
  84405. this.isBorder = true;
  84406. this.q = new QuadraticMatrix();
  84407. this.triangleCount = 0;
  84408. this.triangleStart = 0;
  84409. this.originalOffsets = [];
  84410. }
  84411. DecimationVertex.prototype.updatePosition = function (newPosition) {
  84412. this.position.copyFrom(newPosition);
  84413. };
  84414. return DecimationVertex;
  84415. }());
  84416. BABYLON.DecimationVertex = DecimationVertex;
  84417. var QuadraticMatrix = /** @class */ (function () {
  84418. function QuadraticMatrix(data) {
  84419. this.data = new Array(10);
  84420. for (var i = 0; i < 10; ++i) {
  84421. if (data && data[i]) {
  84422. this.data[i] = data[i];
  84423. }
  84424. else {
  84425. this.data[i] = 0;
  84426. }
  84427. }
  84428. }
  84429. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  84430. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  84431. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  84432. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  84433. return det;
  84434. };
  84435. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  84436. for (var i = 0; i < 10; ++i) {
  84437. this.data[i] += matrix.data[i];
  84438. }
  84439. };
  84440. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  84441. for (var i = 0; i < 10; ++i) {
  84442. this.data[i] += data[i];
  84443. }
  84444. };
  84445. QuadraticMatrix.prototype.add = function (matrix) {
  84446. var m = new QuadraticMatrix();
  84447. for (var i = 0; i < 10; ++i) {
  84448. m.data[i] = this.data[i] + matrix.data[i];
  84449. }
  84450. return m;
  84451. };
  84452. QuadraticMatrix.FromData = function (a, b, c, d) {
  84453. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  84454. };
  84455. //returning an array to avoid garbage collection
  84456. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  84457. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  84458. };
  84459. return QuadraticMatrix;
  84460. }());
  84461. BABYLON.QuadraticMatrix = QuadraticMatrix;
  84462. var Reference = /** @class */ (function () {
  84463. function Reference(vertexId, triangleId) {
  84464. this.vertexId = vertexId;
  84465. this.triangleId = triangleId;
  84466. }
  84467. return Reference;
  84468. }());
  84469. BABYLON.Reference = Reference;
  84470. /**
  84471. * An implementation of the Quadratic Error simplification algorithm.
  84472. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  84473. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  84474. * @author RaananW
  84475. */
  84476. var QuadraticErrorSimplification = /** @class */ (function () {
  84477. function QuadraticErrorSimplification(_mesh) {
  84478. this._mesh = _mesh;
  84479. this.syncIterations = 5000;
  84480. this.aggressiveness = 7;
  84481. this.decimationIterations = 100;
  84482. this.boundingBoxEpsilon = BABYLON.Epsilon;
  84483. }
  84484. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  84485. var _this = this;
  84486. this.initDecimatedMesh();
  84487. //iterating through the submeshes array, one after the other.
  84488. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  84489. _this.initWithMesh(loop.index, function () {
  84490. _this.runDecimation(settings, loop.index, function () {
  84491. loop.executeNext();
  84492. });
  84493. }, settings.optimizeMesh);
  84494. }, function () {
  84495. setTimeout(function () {
  84496. successCallback(_this._reconstructedMesh);
  84497. }, 0);
  84498. });
  84499. };
  84500. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  84501. var _this = this;
  84502. var targetCount = ~~(this.triangles.length * settings.quality);
  84503. var deletedTriangles = 0;
  84504. var triangleCount = this.triangles.length;
  84505. var iterationFunction = function (iteration, callback) {
  84506. setTimeout(function () {
  84507. if (iteration % 5 === 0) {
  84508. _this.updateMesh(iteration === 0);
  84509. }
  84510. for (var i = 0; i < _this.triangles.length; ++i) {
  84511. _this.triangles[i].isDirty = false;
  84512. }
  84513. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  84514. var trianglesIterator = function (i) {
  84515. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  84516. var t = _this.triangles[tIdx];
  84517. if (!t)
  84518. return;
  84519. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  84520. return;
  84521. }
  84522. for (var j = 0; j < 3; ++j) {
  84523. if (t.error[j] < threshold) {
  84524. var deleted0 = [];
  84525. var deleted1 = [];
  84526. var v0 = t.vertices[j];
  84527. var v1 = t.vertices[(j + 1) % 3];
  84528. if (v0.isBorder || v1.isBorder)
  84529. continue;
  84530. var p = BABYLON.Vector3.Zero();
  84531. var n = BABYLON.Vector3.Zero();
  84532. var uv = BABYLON.Vector2.Zero();
  84533. var color = new BABYLON.Color4(0, 0, 0, 1);
  84534. _this.calculateError(v0, v1, p, n, uv, color);
  84535. var delTr = new Array();
  84536. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  84537. continue;
  84538. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  84539. continue;
  84540. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  84541. continue;
  84542. var uniqueArray = new Array();
  84543. delTr.forEach(function (deletedT) {
  84544. if (uniqueArray.indexOf(deletedT) === -1) {
  84545. deletedT.deletePending = true;
  84546. uniqueArray.push(deletedT);
  84547. }
  84548. });
  84549. if (uniqueArray.length % 2 !== 0) {
  84550. continue;
  84551. }
  84552. v0.q = v1.q.add(v0.q);
  84553. v0.updatePosition(p);
  84554. var tStart = _this.references.length;
  84555. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  84556. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  84557. var tCount = _this.references.length - tStart;
  84558. if (tCount <= v0.triangleCount) {
  84559. if (tCount) {
  84560. for (var c = 0; c < tCount; c++) {
  84561. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  84562. }
  84563. }
  84564. }
  84565. else {
  84566. v0.triangleStart = tStart;
  84567. }
  84568. v0.triangleCount = tCount;
  84569. break;
  84570. }
  84571. }
  84572. };
  84573. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  84574. }, 0);
  84575. };
  84576. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  84577. if (triangleCount - deletedTriangles <= targetCount)
  84578. loop.breakLoop();
  84579. else {
  84580. iterationFunction(loop.index, function () {
  84581. loop.executeNext();
  84582. });
  84583. }
  84584. }, function () {
  84585. setTimeout(function () {
  84586. //reconstruct this part of the mesh
  84587. _this.reconstructMesh(submeshIndex);
  84588. successCallback();
  84589. }, 0);
  84590. });
  84591. };
  84592. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  84593. var _this = this;
  84594. this.vertices = [];
  84595. this.triangles = [];
  84596. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  84597. var indices = this._mesh.getIndices();
  84598. var submesh = this._mesh.subMeshes[submeshIndex];
  84599. var findInVertices = function (positionToSearch) {
  84600. if (optimizeMesh) {
  84601. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  84602. if (_this.vertices[ii].position.equals(positionToSearch)) {
  84603. return _this.vertices[ii];
  84604. }
  84605. }
  84606. }
  84607. return null;
  84608. };
  84609. var vertexReferences = [];
  84610. var vertexInit = function (i) {
  84611. if (!positionData) {
  84612. return;
  84613. }
  84614. var offset = i + submesh.verticesStart;
  84615. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  84616. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  84617. vertex.originalOffsets.push(offset);
  84618. if (vertex.id === _this.vertices.length) {
  84619. _this.vertices.push(vertex);
  84620. }
  84621. vertexReferences.push(vertex.id);
  84622. };
  84623. //var totalVertices = mesh.getTotalVertices();
  84624. var totalVertices = submesh.verticesCount;
  84625. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  84626. var indicesInit = function (i) {
  84627. if (!indices) {
  84628. return;
  84629. }
  84630. var offset = (submesh.indexStart / 3) + i;
  84631. var pos = (offset * 3);
  84632. var i0 = indices[pos + 0];
  84633. var i1 = indices[pos + 1];
  84634. var i2 = indices[pos + 2];
  84635. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  84636. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  84637. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  84638. var triangle = new DecimationTriangle([v0, v1, v2]);
  84639. triangle.originalOffset = pos;
  84640. _this.triangles.push(triangle);
  84641. };
  84642. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  84643. _this.init(callback);
  84644. });
  84645. });
  84646. };
  84647. QuadraticErrorSimplification.prototype.init = function (callback) {
  84648. var _this = this;
  84649. var triangleInit1 = function (i) {
  84650. var t = _this.triangles[i];
  84651. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  84652. for (var j = 0; j < 3; j++) {
  84653. 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))));
  84654. }
  84655. };
  84656. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  84657. var triangleInit2 = function (i) {
  84658. var t = _this.triangles[i];
  84659. for (var j = 0; j < 3; ++j) {
  84660. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  84661. }
  84662. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  84663. };
  84664. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  84665. callback();
  84666. });
  84667. });
  84668. };
  84669. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  84670. var newTriangles = [];
  84671. var i;
  84672. for (i = 0; i < this.vertices.length; ++i) {
  84673. this.vertices[i].triangleCount = 0;
  84674. }
  84675. var t;
  84676. var j;
  84677. for (i = 0; i < this.triangles.length; ++i) {
  84678. if (!this.triangles[i].deleted) {
  84679. t = this.triangles[i];
  84680. for (j = 0; j < 3; ++j) {
  84681. t.vertices[j].triangleCount = 1;
  84682. }
  84683. newTriangles.push(t);
  84684. }
  84685. }
  84686. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  84687. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  84688. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  84689. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  84690. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  84691. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  84692. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  84693. var vertexCount = 0;
  84694. for (i = 0; i < this.vertices.length; ++i) {
  84695. var vertex = this.vertices[i];
  84696. vertex.id = vertexCount;
  84697. if (vertex.triangleCount) {
  84698. vertex.originalOffsets.forEach(function (originalOffset) {
  84699. if (!normalData) {
  84700. return;
  84701. }
  84702. newPositionData.push(vertex.position.x);
  84703. newPositionData.push(vertex.position.y);
  84704. newPositionData.push(vertex.position.z);
  84705. newNormalData.push(normalData[originalOffset * 3]);
  84706. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  84707. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  84708. if (uvs && uvs.length) {
  84709. newUVsData.push(uvs[(originalOffset * 2)]);
  84710. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  84711. }
  84712. else if (colorsData && colorsData.length) {
  84713. newColorsData.push(colorsData[(originalOffset * 4)]);
  84714. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  84715. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  84716. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  84717. }
  84718. ++vertexCount;
  84719. });
  84720. }
  84721. }
  84722. var startingIndex = this._reconstructedMesh.getTotalIndices();
  84723. var startingVertex = this._reconstructedMesh.getTotalVertices();
  84724. var submeshesArray = this._reconstructedMesh.subMeshes;
  84725. this._reconstructedMesh.subMeshes = [];
  84726. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  84727. var originalIndices = this._mesh.getIndices();
  84728. for (i = 0; i < newTriangles.length; ++i) {
  84729. t = newTriangles[i]; //now get the new referencing point for each vertex
  84730. [0, 1, 2].forEach(function (idx) {
  84731. var id = originalIndices[t.originalOffset + idx];
  84732. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  84733. if (offset < 0)
  84734. offset = 0;
  84735. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  84736. });
  84737. }
  84738. //overwriting the old vertex buffers and indices.
  84739. this._reconstructedMesh.setIndices(newIndicesArray);
  84740. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  84741. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  84742. if (newUVsData.length > 0)
  84743. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  84744. if (newColorsData.length > 0)
  84745. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  84746. //create submesh
  84747. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  84748. if (submeshIndex > 0) {
  84749. this._reconstructedMesh.subMeshes = [];
  84750. submeshesArray.forEach(function (submesh) {
  84751. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  84752. });
  84753. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  84754. }
  84755. };
  84756. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  84757. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  84758. this._reconstructedMesh.material = this._mesh.material;
  84759. this._reconstructedMesh.parent = this._mesh.parent;
  84760. this._reconstructedMesh.isVisible = false;
  84761. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  84762. };
  84763. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  84764. for (var i = 0; i < vertex1.triangleCount; ++i) {
  84765. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  84766. if (t.deleted)
  84767. continue;
  84768. var s = this.references[vertex1.triangleStart + i].vertexId;
  84769. var v1 = t.vertices[(s + 1) % 3];
  84770. var v2 = t.vertices[(s + 2) % 3];
  84771. if ((v1 === vertex2 || v2 === vertex2)) {
  84772. deletedArray[i] = true;
  84773. delTr.push(t);
  84774. continue;
  84775. }
  84776. var d1 = v1.position.subtract(point);
  84777. d1 = d1.normalize();
  84778. var d2 = v2.position.subtract(point);
  84779. d2 = d2.normalize();
  84780. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  84781. return true;
  84782. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  84783. deletedArray[i] = false;
  84784. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  84785. return true;
  84786. }
  84787. return false;
  84788. };
  84789. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  84790. var newDeleted = deletedTriangles;
  84791. for (var i = 0; i < vertex.triangleCount; ++i) {
  84792. var ref = this.references[vertex.triangleStart + i];
  84793. var t = this.triangles[ref.triangleId];
  84794. if (t.deleted)
  84795. continue;
  84796. if (deletedArray[i] && t.deletePending) {
  84797. t.deleted = true;
  84798. newDeleted++;
  84799. continue;
  84800. }
  84801. t.vertices[ref.vertexId] = origVertex;
  84802. t.isDirty = true;
  84803. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  84804. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  84805. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  84806. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  84807. this.references.push(ref);
  84808. }
  84809. return newDeleted;
  84810. };
  84811. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  84812. for (var i = 0; i < this.vertices.length; ++i) {
  84813. var vCount = [];
  84814. var vId = [];
  84815. var v = this.vertices[i];
  84816. var j;
  84817. for (j = 0; j < v.triangleCount; ++j) {
  84818. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  84819. for (var ii = 0; ii < 3; ii++) {
  84820. var ofs = 0;
  84821. var vv = triangle.vertices[ii];
  84822. while (ofs < vCount.length) {
  84823. if (vId[ofs] === vv.id)
  84824. break;
  84825. ++ofs;
  84826. }
  84827. if (ofs === vCount.length) {
  84828. vCount.push(1);
  84829. vId.push(vv.id);
  84830. }
  84831. else {
  84832. vCount[ofs]++;
  84833. }
  84834. }
  84835. }
  84836. for (j = 0; j < vCount.length; ++j) {
  84837. if (vCount[j] === 1) {
  84838. this.vertices[vId[j]].isBorder = true;
  84839. }
  84840. else {
  84841. this.vertices[vId[j]].isBorder = false;
  84842. }
  84843. }
  84844. }
  84845. };
  84846. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  84847. if (identifyBorders === void 0) { identifyBorders = false; }
  84848. var i;
  84849. if (!identifyBorders) {
  84850. var newTrianglesVector = [];
  84851. for (i = 0; i < this.triangles.length; ++i) {
  84852. if (!this.triangles[i].deleted) {
  84853. newTrianglesVector.push(this.triangles[i]);
  84854. }
  84855. }
  84856. this.triangles = newTrianglesVector;
  84857. }
  84858. for (i = 0; i < this.vertices.length; ++i) {
  84859. this.vertices[i].triangleCount = 0;
  84860. this.vertices[i].triangleStart = 0;
  84861. }
  84862. var t;
  84863. var j;
  84864. var v;
  84865. for (i = 0; i < this.triangles.length; ++i) {
  84866. t = this.triangles[i];
  84867. for (j = 0; j < 3; ++j) {
  84868. v = t.vertices[j];
  84869. v.triangleCount++;
  84870. }
  84871. }
  84872. var tStart = 0;
  84873. for (i = 0; i < this.vertices.length; ++i) {
  84874. this.vertices[i].triangleStart = tStart;
  84875. tStart += this.vertices[i].triangleCount;
  84876. this.vertices[i].triangleCount = 0;
  84877. }
  84878. var newReferences = new Array(this.triangles.length * 3);
  84879. for (i = 0; i < this.triangles.length; ++i) {
  84880. t = this.triangles[i];
  84881. for (j = 0; j < 3; ++j) {
  84882. v = t.vertices[j];
  84883. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  84884. v.triangleCount++;
  84885. }
  84886. }
  84887. this.references = newReferences;
  84888. if (identifyBorders) {
  84889. this.identifyBorder();
  84890. }
  84891. };
  84892. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  84893. var x = point.x;
  84894. var y = point.y;
  84895. var z = point.z;
  84896. 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
  84897. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  84898. };
  84899. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  84900. var q = vertex1.q.add(vertex2.q);
  84901. var border = vertex1.isBorder && vertex2.isBorder;
  84902. var error = 0;
  84903. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  84904. if (qDet !== 0 && !border) {
  84905. if (!pointResult) {
  84906. pointResult = BABYLON.Vector3.Zero();
  84907. }
  84908. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  84909. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  84910. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  84911. error = this.vertexError(q, pointResult);
  84912. }
  84913. else {
  84914. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  84915. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  84916. var error1 = this.vertexError(q, vertex1.position);
  84917. var error2 = this.vertexError(q, vertex2.position);
  84918. var error3 = this.vertexError(q, p3);
  84919. error = Math.min(error1, error2, error3);
  84920. if (error === error1) {
  84921. if (pointResult) {
  84922. pointResult.copyFrom(vertex1.position);
  84923. }
  84924. }
  84925. else if (error === error2) {
  84926. if (pointResult) {
  84927. pointResult.copyFrom(vertex2.position);
  84928. }
  84929. }
  84930. else {
  84931. if (pointResult) {
  84932. pointResult.copyFrom(p3);
  84933. }
  84934. }
  84935. }
  84936. return error;
  84937. };
  84938. return QuadraticErrorSimplification;
  84939. }());
  84940. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  84941. })(BABYLON || (BABYLON = {}));
  84942. //# sourceMappingURL=babylon.meshSimplification.js.map
  84943. "use strict";
  84944. var BABYLON;
  84945. (function (BABYLON) {
  84946. var MeshLODLevel = /** @class */ (function () {
  84947. function MeshLODLevel(distance, mesh) {
  84948. this.distance = distance;
  84949. this.mesh = mesh;
  84950. }
  84951. return MeshLODLevel;
  84952. }());
  84953. BABYLON.MeshLODLevel = MeshLODLevel;
  84954. })(BABYLON || (BABYLON = {}));
  84955. //# sourceMappingURL=babylon.meshLODLevel.js.map
  84956. "use strict";
  84957. var BABYLON;
  84958. (function (BABYLON) {
  84959. /**
  84960. * Defines the root class used to create scene optimization to use with SceneOptimizer
  84961. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84962. */
  84963. var SceneOptimization = /** @class */ (function () {
  84964. /**
  84965. * Creates the SceneOptimization object
  84966. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84967. * @param desc defines the description associated with the optimization
  84968. */
  84969. function SceneOptimization(
  84970. /**
  84971. * Defines the priority of this optimization (0 by default which means first in the list)
  84972. */
  84973. priority) {
  84974. if (priority === void 0) { priority = 0; }
  84975. this.priority = priority;
  84976. }
  84977. /**
  84978. * Gets a string describing the action executed by the current optimization
  84979. * @returns description string
  84980. */
  84981. SceneOptimization.prototype.getDescription = function () {
  84982. return "";
  84983. };
  84984. /**
  84985. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84986. * @param scene defines the current scene where to apply this optimization
  84987. * @param optimizer defines the current optimizer
  84988. * @returns true if everything that can be done was applied
  84989. */
  84990. SceneOptimization.prototype.apply = function (scene, optimizer) {
  84991. return true;
  84992. };
  84993. ;
  84994. return SceneOptimization;
  84995. }());
  84996. BABYLON.SceneOptimization = SceneOptimization;
  84997. /**
  84998. * Defines an optimization used to reduce the size of render target textures
  84999. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85000. */
  85001. var TextureOptimization = /** @class */ (function (_super) {
  85002. __extends(TextureOptimization, _super);
  85003. /**
  85004. * Creates the TextureOptimization object
  85005. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85006. * @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
  85007. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  85008. */
  85009. function TextureOptimization(
  85010. /**
  85011. * Defines the priority of this optimization (0 by default which means first in the list)
  85012. */
  85013. priority,
  85014. /**
  85015. * 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
  85016. */
  85017. maximumSize,
  85018. /**
  85019. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  85020. */
  85021. step) {
  85022. if (priority === void 0) { priority = 0; }
  85023. if (maximumSize === void 0) { maximumSize = 1024; }
  85024. if (step === void 0) { step = 0.5; }
  85025. var _this = _super.call(this, priority) || this;
  85026. _this.priority = priority;
  85027. _this.maximumSize = maximumSize;
  85028. _this.step = step;
  85029. return _this;
  85030. }
  85031. /**
  85032. * Gets a string describing the action executed by the current optimization
  85033. * @returns description string
  85034. */
  85035. TextureOptimization.prototype.getDescription = function () {
  85036. return "Reducing render target texture size to " + this.maximumSize;
  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. * @returns true if everything that can be done was applied
  85043. */
  85044. TextureOptimization.prototype.apply = function (scene, optimizer) {
  85045. var allDone = true;
  85046. for (var index = 0; index < scene.textures.length; index++) {
  85047. var texture = scene.textures[index];
  85048. if (!texture.canRescale || texture.getContext) {
  85049. continue;
  85050. }
  85051. var currentSize = texture.getSize();
  85052. var maxDimension = Math.max(currentSize.width, currentSize.height);
  85053. if (maxDimension > this.maximumSize) {
  85054. texture.scale(this.step);
  85055. allDone = false;
  85056. }
  85057. }
  85058. return allDone;
  85059. };
  85060. return TextureOptimization;
  85061. }(SceneOptimization));
  85062. BABYLON.TextureOptimization = TextureOptimization;
  85063. /**
  85064. * Defines an optimization used to increase or decrease the rendering resolution
  85065. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85066. */
  85067. var HardwareScalingOptimization = /** @class */ (function (_super) {
  85068. __extends(HardwareScalingOptimization, _super);
  85069. /**
  85070. * Creates the HardwareScalingOptimization object
  85071. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85072. * @param maximumScale defines the maximum scale to use (2 by default)
  85073. * @param step defines the step to use between two passes (0.5 by default)
  85074. */
  85075. function HardwareScalingOptimization(
  85076. /**
  85077. * Defines the priority of this optimization (0 by default which means first in the list)
  85078. */
  85079. priority,
  85080. /**
  85081. * Defines the maximum scale to use (2 by default)
  85082. */
  85083. maximumScale,
  85084. /**
  85085. * Defines the step to use between two passes (0.5 by default)
  85086. */
  85087. step) {
  85088. if (priority === void 0) { priority = 0; }
  85089. if (maximumScale === void 0) { maximumScale = 2; }
  85090. if (step === void 0) { step = 0.25; }
  85091. var _this = _super.call(this, priority) || this;
  85092. _this.priority = priority;
  85093. _this.maximumScale = maximumScale;
  85094. _this.step = step;
  85095. _this._currentScale = -1;
  85096. _this._directionOffset = 1;
  85097. return _this;
  85098. }
  85099. /**
  85100. * Gets a string describing the action executed by the current optimization
  85101. * @return description string
  85102. */
  85103. HardwareScalingOptimization.prototype.getDescription = function () {
  85104. return "Setting hardware scaling level to " + this._currentScale;
  85105. };
  85106. /**
  85107. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85108. * @param scene defines the current scene where to apply this optimization
  85109. * @param optimizer defines the current optimizer
  85110. * @returns true if everything that can be done was applied
  85111. */
  85112. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  85113. if (this._currentScale === -1) {
  85114. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  85115. if (this._currentScale > this.maximumScale) {
  85116. this._directionOffset = -1;
  85117. }
  85118. }
  85119. this._currentScale += this._directionOffset * this.step;
  85120. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  85121. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  85122. };
  85123. ;
  85124. return HardwareScalingOptimization;
  85125. }(SceneOptimization));
  85126. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  85127. /**
  85128. * Defines an optimization used to remove shadows
  85129. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85130. */
  85131. var ShadowsOptimization = /** @class */ (function (_super) {
  85132. __extends(ShadowsOptimization, _super);
  85133. function ShadowsOptimization() {
  85134. return _super !== null && _super.apply(this, arguments) || this;
  85135. }
  85136. /**
  85137. * Gets a string describing the action executed by the current optimization
  85138. * @return description string
  85139. */
  85140. ShadowsOptimization.prototype.getDescription = function () {
  85141. return "Turning shadows on/off";
  85142. };
  85143. /**
  85144. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85145. * @param scene defines the current scene where to apply this optimization
  85146. * @param optimizer defines the current optimizer
  85147. * @returns true if everything that can be done was applied
  85148. */
  85149. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  85150. scene.shadowsEnabled = optimizer.isInImprovementMode;
  85151. return true;
  85152. };
  85153. ;
  85154. return ShadowsOptimization;
  85155. }(SceneOptimization));
  85156. BABYLON.ShadowsOptimization = ShadowsOptimization;
  85157. /**
  85158. * Defines an optimization used to turn post-processes off
  85159. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85160. */
  85161. var PostProcessesOptimization = /** @class */ (function (_super) {
  85162. __extends(PostProcessesOptimization, _super);
  85163. function PostProcessesOptimization() {
  85164. return _super !== null && _super.apply(this, arguments) || this;
  85165. }
  85166. /**
  85167. * Gets a string describing the action executed by the current optimization
  85168. * @return description string
  85169. */
  85170. PostProcessesOptimization.prototype.getDescription = function () {
  85171. return "Turning post-processes on/off";
  85172. };
  85173. /**
  85174. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85175. * @param scene defines the current scene where to apply this optimization
  85176. * @param optimizer defines the current optimizer
  85177. * @returns true if everything that can be done was applied
  85178. */
  85179. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  85180. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  85181. return true;
  85182. };
  85183. ;
  85184. return PostProcessesOptimization;
  85185. }(SceneOptimization));
  85186. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  85187. /**
  85188. * Defines an optimization used to turn lens flares off
  85189. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85190. */
  85191. var LensFlaresOptimization = /** @class */ (function (_super) {
  85192. __extends(LensFlaresOptimization, _super);
  85193. function LensFlaresOptimization() {
  85194. return _super !== null && _super.apply(this, arguments) || this;
  85195. }
  85196. /**
  85197. * Gets a string describing the action executed by the current optimization
  85198. * @return description string
  85199. */
  85200. LensFlaresOptimization.prototype.getDescription = function () {
  85201. return "Turning lens flares on/off";
  85202. };
  85203. /**
  85204. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85205. * @param scene defines the current scene where to apply this optimization
  85206. * @param optimizer defines the current optimizer
  85207. * @returns true if everything that can be done was applied
  85208. */
  85209. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  85210. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  85211. return true;
  85212. };
  85213. ;
  85214. return LensFlaresOptimization;
  85215. }(SceneOptimization));
  85216. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  85217. /**
  85218. * Defines an optimization based on user defined callback.
  85219. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85220. */
  85221. var CustomOptimization = /** @class */ (function (_super) {
  85222. __extends(CustomOptimization, _super);
  85223. function CustomOptimization() {
  85224. return _super !== null && _super.apply(this, arguments) || this;
  85225. }
  85226. /**
  85227. * Gets a string describing the action executed by the current optimization
  85228. * @returns description string
  85229. */
  85230. CustomOptimization.prototype.getDescription = function () {
  85231. if (this.onGetDescription) {
  85232. return this.onGetDescription();
  85233. }
  85234. return "Running user defined callback";
  85235. };
  85236. /**
  85237. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85238. * @param scene defines the current scene where to apply this optimization
  85239. * @param optimizer defines the current optimizer
  85240. * @returns true if everything that can be done was applied
  85241. */
  85242. CustomOptimization.prototype.apply = function (scene, optimizer) {
  85243. if (this.onApply) {
  85244. return this.onApply(scene, optimizer);
  85245. }
  85246. return true;
  85247. };
  85248. ;
  85249. return CustomOptimization;
  85250. }(SceneOptimization));
  85251. BABYLON.CustomOptimization = CustomOptimization;
  85252. /**
  85253. * Defines an optimization used to turn particles off
  85254. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85255. */
  85256. var ParticlesOptimization = /** @class */ (function (_super) {
  85257. __extends(ParticlesOptimization, _super);
  85258. function ParticlesOptimization() {
  85259. return _super !== null && _super.apply(this, arguments) || this;
  85260. }
  85261. /**
  85262. * Gets a string describing the action executed by the current optimization
  85263. * @return description string
  85264. */
  85265. ParticlesOptimization.prototype.getDescription = function () {
  85266. return "Turning particles on/off";
  85267. };
  85268. /**
  85269. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85270. * @param scene defines the current scene where to apply this optimization
  85271. * @param optimizer defines the current optimizer
  85272. * @returns true if everything that can be done was applied
  85273. */
  85274. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  85275. scene.particlesEnabled = optimizer.isInImprovementMode;
  85276. return true;
  85277. };
  85278. ;
  85279. return ParticlesOptimization;
  85280. }(SceneOptimization));
  85281. BABYLON.ParticlesOptimization = ParticlesOptimization;
  85282. /**
  85283. * Defines an optimization used to turn render targets off
  85284. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85285. */
  85286. var RenderTargetsOptimization = /** @class */ (function (_super) {
  85287. __extends(RenderTargetsOptimization, _super);
  85288. function RenderTargetsOptimization() {
  85289. return _super !== null && _super.apply(this, arguments) || this;
  85290. }
  85291. /**
  85292. * Gets a string describing the action executed by the current optimization
  85293. * @return description string
  85294. */
  85295. RenderTargetsOptimization.prototype.getDescription = function () {
  85296. return "Turning render targets off";
  85297. };
  85298. /**
  85299. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85300. * @param scene defines the current scene where to apply this optimization
  85301. * @param optimizer defines the current optimizer
  85302. * @returns true if everything that can be done was applied
  85303. */
  85304. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  85305. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  85306. return true;
  85307. };
  85308. ;
  85309. return RenderTargetsOptimization;
  85310. }(SceneOptimization));
  85311. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  85312. /**
  85313. * Defines an optimization used to merge meshes with compatible materials
  85314. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85315. */
  85316. var MergeMeshesOptimization = /** @class */ (function (_super) {
  85317. __extends(MergeMeshesOptimization, _super);
  85318. function MergeMeshesOptimization() {
  85319. var _this = _super !== null && _super.apply(this, arguments) || this;
  85320. _this._canBeMerged = function (abstractMesh) {
  85321. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  85322. return false;
  85323. }
  85324. var mesh = abstractMesh;
  85325. if (!mesh.isVisible || !mesh.isEnabled()) {
  85326. return false;
  85327. }
  85328. if (mesh.instances.length > 0) {
  85329. return false;
  85330. }
  85331. if (mesh.skeleton || mesh.hasLODLevels) {
  85332. return false;
  85333. }
  85334. if (mesh.parent) {
  85335. return false;
  85336. }
  85337. return true;
  85338. };
  85339. return _this;
  85340. }
  85341. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  85342. /**
  85343. * Gets or sets a boolean which defines if optimization octree has to be updated
  85344. */
  85345. get: function () {
  85346. return MergeMeshesOptimization._UpdateSelectionTree;
  85347. },
  85348. /**
  85349. * Gets or sets a boolean which defines if optimization octree has to be updated
  85350. */
  85351. set: function (value) {
  85352. MergeMeshesOptimization._UpdateSelectionTree = value;
  85353. },
  85354. enumerable: true,
  85355. configurable: true
  85356. });
  85357. /**
  85358. * Gets a string describing the action executed by the current optimization
  85359. * @return description string
  85360. */
  85361. MergeMeshesOptimization.prototype.getDescription = function () {
  85362. return "Merging similar meshes together";
  85363. };
  85364. /**
  85365. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85366. * @param scene defines the current scene where to apply this optimization
  85367. * @param optimizer defines the current optimizer
  85368. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  85369. * @returns true if everything that can be done was applied
  85370. */
  85371. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  85372. var globalPool = scene.meshes.slice(0);
  85373. var globalLength = globalPool.length;
  85374. for (var index = 0; index < globalLength; index++) {
  85375. var currentPool = new Array();
  85376. var current = globalPool[index];
  85377. // Checks
  85378. if (!this._canBeMerged(current)) {
  85379. continue;
  85380. }
  85381. currentPool.push(current);
  85382. // Find compatible meshes
  85383. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  85384. var otherMesh = globalPool[subIndex];
  85385. if (!this._canBeMerged(otherMesh)) {
  85386. continue;
  85387. }
  85388. if (otherMesh.material !== current.material) {
  85389. continue;
  85390. }
  85391. if (otherMesh.checkCollisions !== current.checkCollisions) {
  85392. continue;
  85393. }
  85394. currentPool.push(otherMesh);
  85395. globalLength--;
  85396. globalPool.splice(subIndex, 1);
  85397. subIndex--;
  85398. }
  85399. if (currentPool.length < 2) {
  85400. continue;
  85401. }
  85402. // Merge meshes
  85403. BABYLON.Mesh.MergeMeshes(currentPool);
  85404. }
  85405. if (updateSelectionTree != undefined) {
  85406. if (updateSelectionTree) {
  85407. scene.createOrUpdateSelectionOctree();
  85408. }
  85409. }
  85410. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  85411. scene.createOrUpdateSelectionOctree();
  85412. }
  85413. return true;
  85414. };
  85415. ;
  85416. MergeMeshesOptimization._UpdateSelectionTree = false;
  85417. return MergeMeshesOptimization;
  85418. }(SceneOptimization));
  85419. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  85420. /**
  85421. * Defines a list of options used by SceneOptimizer
  85422. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85423. */
  85424. var SceneOptimizerOptions = /** @class */ (function () {
  85425. /**
  85426. * Creates a new list of options used by SceneOptimizer
  85427. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  85428. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  85429. */
  85430. function SceneOptimizerOptions(
  85431. /**
  85432. * Defines the target frame rate to reach (60 by default)
  85433. */
  85434. targetFrameRate,
  85435. /**
  85436. * Defines the interval between two checkes (2000ms by default)
  85437. */
  85438. trackerDuration) {
  85439. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  85440. if (trackerDuration === void 0) { trackerDuration = 2000; }
  85441. this.targetFrameRate = targetFrameRate;
  85442. this.trackerDuration = trackerDuration;
  85443. /**
  85444. * Gets the list of optimizations to apply
  85445. */
  85446. this.optimizations = new Array();
  85447. }
  85448. /**
  85449. * Add a new optimization
  85450. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  85451. * @returns the current SceneOptimizerOptions
  85452. */
  85453. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  85454. this.optimizations.push(optimization);
  85455. return this;
  85456. };
  85457. /**
  85458. * Add a new custom optimization
  85459. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  85460. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  85461. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85462. * @returns the current SceneOptimizerOptions
  85463. */
  85464. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  85465. if (priority === void 0) { priority = 0; }
  85466. var optimization = new CustomOptimization(priority);
  85467. optimization.onApply = onApply;
  85468. optimization.onGetDescription = onGetDescription;
  85469. this.optimizations.push(optimization);
  85470. return this;
  85471. };
  85472. /**
  85473. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  85474. * @param targetFrameRate defines the target frame rate (60 by default)
  85475. * @returns a SceneOptimizerOptions object
  85476. */
  85477. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  85478. var result = new SceneOptimizerOptions(targetFrameRate);
  85479. var priority = 0;
  85480. result.addOptimization(new MergeMeshesOptimization(priority));
  85481. result.addOptimization(new ShadowsOptimization(priority));
  85482. result.addOptimization(new LensFlaresOptimization(priority));
  85483. // Next priority
  85484. priority++;
  85485. result.addOptimization(new PostProcessesOptimization(priority));
  85486. result.addOptimization(new ParticlesOptimization(priority));
  85487. // Next priority
  85488. priority++;
  85489. result.addOptimization(new TextureOptimization(priority, 1024));
  85490. return result;
  85491. };
  85492. /**
  85493. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  85494. * @param targetFrameRate defines the target frame rate (60 by default)
  85495. * @returns a SceneOptimizerOptions object
  85496. */
  85497. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  85498. var result = new SceneOptimizerOptions(targetFrameRate);
  85499. var priority = 0;
  85500. result.addOptimization(new MergeMeshesOptimization(priority));
  85501. result.addOptimization(new ShadowsOptimization(priority));
  85502. result.addOptimization(new LensFlaresOptimization(priority));
  85503. // Next priority
  85504. priority++;
  85505. result.addOptimization(new PostProcessesOptimization(priority));
  85506. result.addOptimization(new ParticlesOptimization(priority));
  85507. // Next priority
  85508. priority++;
  85509. result.addOptimization(new TextureOptimization(priority, 512));
  85510. // Next priority
  85511. priority++;
  85512. result.addOptimization(new RenderTargetsOptimization(priority));
  85513. // Next priority
  85514. priority++;
  85515. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  85516. return result;
  85517. };
  85518. /**
  85519. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  85520. * @param targetFrameRate defines the target frame rate (60 by default)
  85521. * @returns a SceneOptimizerOptions object
  85522. */
  85523. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  85524. var result = new SceneOptimizerOptions(targetFrameRate);
  85525. var priority = 0;
  85526. result.addOptimization(new MergeMeshesOptimization(priority));
  85527. result.addOptimization(new ShadowsOptimization(priority));
  85528. result.addOptimization(new LensFlaresOptimization(priority));
  85529. // Next priority
  85530. priority++;
  85531. result.addOptimization(new PostProcessesOptimization(priority));
  85532. result.addOptimization(new ParticlesOptimization(priority));
  85533. // Next priority
  85534. priority++;
  85535. result.addOptimization(new TextureOptimization(priority, 256));
  85536. // Next priority
  85537. priority++;
  85538. result.addOptimization(new RenderTargetsOptimization(priority));
  85539. // Next priority
  85540. priority++;
  85541. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  85542. return result;
  85543. };
  85544. return SceneOptimizerOptions;
  85545. }());
  85546. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  85547. /**
  85548. * Class used to run optimizations in order to reach a target frame rate
  85549. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85550. */
  85551. var SceneOptimizer = /** @class */ (function () {
  85552. /**
  85553. * Creates a new SceneOptimizer
  85554. * @param scene defines the scene to work on
  85555. * @param options defines the options to use with the SceneOptimizer
  85556. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  85557. * @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)
  85558. */
  85559. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  85560. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  85561. if (improvementMode === void 0) { improvementMode = false; }
  85562. var _this = this;
  85563. this._isRunning = false;
  85564. this._currentPriorityLevel = 0;
  85565. this._targetFrameRate = 60;
  85566. this._trackerDuration = 2000;
  85567. this._currentFrameRate = 0;
  85568. this._improvementMode = false;
  85569. /**
  85570. * Defines an observable called when the optimizer reaches the target frame rate
  85571. */
  85572. this.onSuccessObservable = new BABYLON.Observable();
  85573. /**
  85574. * Defines an observable called when the optimizer enables an optimization
  85575. */
  85576. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  85577. /**
  85578. * Defines an observable called when the optimizer is not able to reach the target frame rate
  85579. */
  85580. this.onFailureObservable = new BABYLON.Observable();
  85581. if (!options) {
  85582. this._options = new SceneOptimizerOptions();
  85583. }
  85584. else {
  85585. this._options = options;
  85586. }
  85587. if (this._options.targetFrameRate) {
  85588. this._targetFrameRate = this._options.targetFrameRate;
  85589. }
  85590. if (this._options.trackerDuration) {
  85591. this._trackerDuration = this._options.trackerDuration;
  85592. }
  85593. if (autoGeneratePriorities) {
  85594. var priority = 0;
  85595. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  85596. var optim = _a[_i];
  85597. optim.priority = priority++;
  85598. }
  85599. }
  85600. this._improvementMode = improvementMode;
  85601. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85602. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  85603. _this._sceneDisposeObserver = null;
  85604. _this.dispose();
  85605. });
  85606. }
  85607. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  85608. /**
  85609. * Gets a boolean indicating if the optimizer is in improvement mode
  85610. */
  85611. get: function () {
  85612. return this._improvementMode;
  85613. },
  85614. enumerable: true,
  85615. configurable: true
  85616. });
  85617. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  85618. /**
  85619. * Gets the current priority level (0 at start)
  85620. */
  85621. get: function () {
  85622. return this._currentPriorityLevel;
  85623. },
  85624. enumerable: true,
  85625. configurable: true
  85626. });
  85627. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  85628. /**
  85629. * Gets the current frame rate checked by the SceneOptimizer
  85630. */
  85631. get: function () {
  85632. return this._currentFrameRate;
  85633. },
  85634. enumerable: true,
  85635. configurable: true
  85636. });
  85637. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  85638. /**
  85639. * Gets or sets the current target frame rate (60 by default)
  85640. */
  85641. get: function () {
  85642. return this._targetFrameRate;
  85643. },
  85644. /**
  85645. * Gets or sets the current target frame rate (60 by default)
  85646. */
  85647. set: function (value) {
  85648. this._targetFrameRate = value;
  85649. },
  85650. enumerable: true,
  85651. configurable: true
  85652. });
  85653. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  85654. /**
  85655. * Gets or sets the current interval between two checks (every 2000ms by default)
  85656. */
  85657. get: function () {
  85658. return this._trackerDuration;
  85659. },
  85660. /**
  85661. * Gets or sets the current interval between two checks (every 2000ms by default)
  85662. */
  85663. set: function (value) {
  85664. this._trackerDuration = value;
  85665. },
  85666. enumerable: true,
  85667. configurable: true
  85668. });
  85669. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  85670. /**
  85671. * Gets the list of active optimizations
  85672. */
  85673. get: function () {
  85674. return this._options.optimizations;
  85675. },
  85676. enumerable: true,
  85677. configurable: true
  85678. });
  85679. /**
  85680. * Stops the current optimizer
  85681. */
  85682. SceneOptimizer.prototype.stop = function () {
  85683. this._isRunning = false;
  85684. };
  85685. /**
  85686. * Reset the optimizer to initial step (current priority level = 0)
  85687. */
  85688. SceneOptimizer.prototype.reset = function () {
  85689. this._currentPriorityLevel = 0;
  85690. };
  85691. /**
  85692. * Start the optimizer. By default it will try to reach a specific framerate
  85693. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  85694. */
  85695. SceneOptimizer.prototype.start = function () {
  85696. var _this = this;
  85697. if (this._isRunning) {
  85698. return;
  85699. }
  85700. this._isRunning = true;
  85701. // Let's wait for the scene to be ready before running our check
  85702. this._scene.executeWhenReady(function () {
  85703. setTimeout(function () {
  85704. _this._checkCurrentState();
  85705. }, _this._trackerDuration);
  85706. });
  85707. };
  85708. SceneOptimizer.prototype._checkCurrentState = function () {
  85709. var _this = this;
  85710. if (!this._isRunning) {
  85711. return;
  85712. }
  85713. var scene = this._scene;
  85714. var options = this._options;
  85715. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  85716. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  85717. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  85718. this._isRunning = false;
  85719. this.onSuccessObservable.notifyObservers(this);
  85720. return;
  85721. }
  85722. // Apply current level of optimizations
  85723. var allDone = true;
  85724. var noOptimizationApplied = true;
  85725. for (var index = 0; index < options.optimizations.length; index++) {
  85726. var optimization = options.optimizations[index];
  85727. if (optimization.priority === this._currentPriorityLevel) {
  85728. noOptimizationApplied = false;
  85729. allDone = allDone && optimization.apply(scene, this);
  85730. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  85731. }
  85732. }
  85733. // If no optimization was applied, this is a failure :(
  85734. if (noOptimizationApplied) {
  85735. this._isRunning = false;
  85736. this.onFailureObservable.notifyObservers(this);
  85737. return;
  85738. }
  85739. // If all optimizations were done, move to next level
  85740. if (allDone) {
  85741. this._currentPriorityLevel++;
  85742. }
  85743. // Let's the system running for a specific amount of time before checking FPS
  85744. scene.executeWhenReady(function () {
  85745. setTimeout(function () {
  85746. _this._checkCurrentState();
  85747. }, _this._trackerDuration);
  85748. });
  85749. };
  85750. /**
  85751. * Release all resources
  85752. */
  85753. SceneOptimizer.prototype.dispose = function () {
  85754. this.stop();
  85755. this.onSuccessObservable.clear();
  85756. this.onFailureObservable.clear();
  85757. this.onNewOptimizationAppliedObservable.clear();
  85758. if (this._sceneDisposeObserver) {
  85759. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  85760. }
  85761. };
  85762. /**
  85763. * Helper function to create a SceneOptimizer with one single line of code
  85764. * @param scene defines the scene to work on
  85765. * @param options defines the options to use with the SceneOptimizer
  85766. * @param onSuccess defines a callback to call on success
  85767. * @param onFailure defines a callback to call on failure
  85768. * @returns the new SceneOptimizer object
  85769. */
  85770. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  85771. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  85772. if (onSuccess) {
  85773. optimizer.onSuccessObservable.add(function () {
  85774. onSuccess();
  85775. });
  85776. }
  85777. if (onFailure) {
  85778. optimizer.onFailureObservable.add(function () {
  85779. onFailure();
  85780. });
  85781. }
  85782. optimizer.start();
  85783. return optimizer;
  85784. };
  85785. return SceneOptimizer;
  85786. }());
  85787. BABYLON.SceneOptimizer = SceneOptimizer;
  85788. })(BABYLON || (BABYLON = {}));
  85789. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  85790. "use strict";
  85791. var BABYLON;
  85792. (function (BABYLON) {
  85793. var OutlineRenderer = /** @class */ (function () {
  85794. function OutlineRenderer(scene) {
  85795. this.zOffset = 1;
  85796. this._scene = scene;
  85797. }
  85798. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  85799. var _this = this;
  85800. if (useOverlay === void 0) { useOverlay = false; }
  85801. var scene = this._scene;
  85802. var engine = this._scene.getEngine();
  85803. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  85804. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  85805. return;
  85806. }
  85807. var mesh = subMesh.getRenderingMesh();
  85808. var material = subMesh.getMaterial();
  85809. if (!material || !scene.activeCamera) {
  85810. return;
  85811. }
  85812. engine.enableEffect(this._effect);
  85813. // Logarithmic depth
  85814. if (material.useLogarithmicDepth) {
  85815. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  85816. }
  85817. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  85818. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  85819. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  85820. // Bones
  85821. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  85822. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  85823. }
  85824. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  85825. // Alpha test
  85826. if (material && material.needAlphaTesting()) {
  85827. var alphaTexture = material.getAlphaTestTexture();
  85828. if (alphaTexture) {
  85829. this._effect.setTexture("diffuseSampler", alphaTexture);
  85830. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  85831. }
  85832. }
  85833. engine.setZOffset(-this.zOffset);
  85834. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  85835. engine.setZOffset(0);
  85836. };
  85837. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  85838. var defines = [];
  85839. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  85840. var mesh = subMesh.getMesh();
  85841. var material = subMesh.getMaterial();
  85842. if (material) {
  85843. // Alpha test
  85844. if (material.needAlphaTesting()) {
  85845. defines.push("#define ALPHATEST");
  85846. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85847. attribs.push(BABYLON.VertexBuffer.UVKind);
  85848. defines.push("#define UV1");
  85849. }
  85850. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  85851. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85852. defines.push("#define UV2");
  85853. }
  85854. }
  85855. //Logarithmic depth
  85856. if (material.useLogarithmicDepth) {
  85857. defines.push("#define LOGARITHMICDEPTH");
  85858. }
  85859. }
  85860. // Bones
  85861. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  85862. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  85863. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  85864. if (mesh.numBoneInfluencers > 4) {
  85865. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  85866. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  85867. }
  85868. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  85869. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  85870. }
  85871. else {
  85872. defines.push("#define NUM_BONE_INFLUENCERS 0");
  85873. }
  85874. // Instances
  85875. if (useInstances) {
  85876. defines.push("#define INSTANCES");
  85877. attribs.push("world0");
  85878. attribs.push("world1");
  85879. attribs.push("world2");
  85880. attribs.push("world3");
  85881. }
  85882. // Get correct effect
  85883. var join = defines.join("\n");
  85884. if (this._cachedDefines !== join) {
  85885. this._cachedDefines = join;
  85886. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  85887. }
  85888. return this._effect.isReady();
  85889. };
  85890. return OutlineRenderer;
  85891. }());
  85892. BABYLON.OutlineRenderer = OutlineRenderer;
  85893. })(BABYLON || (BABYLON = {}));
  85894. //# sourceMappingURL=babylon.outlineRenderer.js.map
  85895. "use strict";
  85896. var BABYLON;
  85897. (function (BABYLON) {
  85898. var FaceAdjacencies = /** @class */ (function () {
  85899. function FaceAdjacencies() {
  85900. this.edges = new Array();
  85901. this.edgesConnectedCount = 0;
  85902. }
  85903. return FaceAdjacencies;
  85904. }());
  85905. var EdgesRenderer = /** @class */ (function () {
  85906. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  85907. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  85908. if (epsilon === void 0) { epsilon = 0.95; }
  85909. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  85910. this.edgesWidthScalerForOrthographic = 1000.0;
  85911. this.edgesWidthScalerForPerspective = 50.0;
  85912. this._linesPositions = new Array();
  85913. this._linesNormals = new Array();
  85914. this._linesIndices = new Array();
  85915. this._buffers = {};
  85916. this._checkVerticesInsteadOfIndices = false;
  85917. this._source = source;
  85918. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  85919. this._epsilon = epsilon;
  85920. this._prepareRessources();
  85921. this._generateEdgesLines();
  85922. }
  85923. EdgesRenderer.prototype._prepareRessources = function () {
  85924. if (this._lineShader) {
  85925. return;
  85926. }
  85927. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  85928. attributes: ["position", "normal"],
  85929. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  85930. });
  85931. this._lineShader.disableDepthWrite = true;
  85932. this._lineShader.backFaceCulling = false;
  85933. };
  85934. EdgesRenderer.prototype._rebuild = function () {
  85935. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  85936. if (buffer) {
  85937. buffer._rebuild();
  85938. }
  85939. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  85940. if (buffer) {
  85941. buffer._rebuild();
  85942. }
  85943. var scene = this._source.getScene();
  85944. var engine = scene.getEngine();
  85945. this._ib = engine.createIndexBuffer(this._linesIndices);
  85946. };
  85947. EdgesRenderer.prototype.dispose = function () {
  85948. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  85949. if (buffer) {
  85950. buffer.dispose();
  85951. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  85952. }
  85953. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  85954. if (buffer) {
  85955. buffer.dispose();
  85956. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  85957. }
  85958. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  85959. this._lineShader.dispose();
  85960. };
  85961. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  85962. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  85963. return 0;
  85964. }
  85965. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  85966. return 1;
  85967. }
  85968. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  85969. return 2;
  85970. }
  85971. return -1;
  85972. };
  85973. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  85974. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  85975. return 0;
  85976. }
  85977. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  85978. return 1;
  85979. }
  85980. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  85981. return 2;
  85982. }
  85983. return -1;
  85984. };
  85985. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  85986. var needToCreateLine;
  85987. if (edge === undefined) {
  85988. needToCreateLine = true;
  85989. }
  85990. else {
  85991. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  85992. needToCreateLine = dotProduct < this._epsilon;
  85993. }
  85994. if (needToCreateLine) {
  85995. var offset = this._linesPositions.length / 3;
  85996. var normal = p0.subtract(p1);
  85997. normal.normalize();
  85998. // Positions
  85999. this._linesPositions.push(p0.x);
  86000. this._linesPositions.push(p0.y);
  86001. this._linesPositions.push(p0.z);
  86002. this._linesPositions.push(p0.x);
  86003. this._linesPositions.push(p0.y);
  86004. this._linesPositions.push(p0.z);
  86005. this._linesPositions.push(p1.x);
  86006. this._linesPositions.push(p1.y);
  86007. this._linesPositions.push(p1.z);
  86008. this._linesPositions.push(p1.x);
  86009. this._linesPositions.push(p1.y);
  86010. this._linesPositions.push(p1.z);
  86011. // Normals
  86012. this._linesNormals.push(p1.x);
  86013. this._linesNormals.push(p1.y);
  86014. this._linesNormals.push(p1.z);
  86015. this._linesNormals.push(-1);
  86016. this._linesNormals.push(p1.x);
  86017. this._linesNormals.push(p1.y);
  86018. this._linesNormals.push(p1.z);
  86019. this._linesNormals.push(1);
  86020. this._linesNormals.push(p0.x);
  86021. this._linesNormals.push(p0.y);
  86022. this._linesNormals.push(p0.z);
  86023. this._linesNormals.push(-1);
  86024. this._linesNormals.push(p0.x);
  86025. this._linesNormals.push(p0.y);
  86026. this._linesNormals.push(p0.z);
  86027. this._linesNormals.push(1);
  86028. // Indices
  86029. this._linesIndices.push(offset);
  86030. this._linesIndices.push(offset + 1);
  86031. this._linesIndices.push(offset + 2);
  86032. this._linesIndices.push(offset);
  86033. this._linesIndices.push(offset + 2);
  86034. this._linesIndices.push(offset + 3);
  86035. }
  86036. };
  86037. EdgesRenderer.prototype._generateEdgesLines = function () {
  86038. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  86039. var indices = this._source.getIndices();
  86040. if (!indices || !positions) {
  86041. return;
  86042. }
  86043. // First let's find adjacencies
  86044. var adjacencies = new Array();
  86045. var faceNormals = new Array();
  86046. var index;
  86047. var faceAdjacencies;
  86048. // Prepare faces
  86049. for (index = 0; index < indices.length; index += 3) {
  86050. faceAdjacencies = new FaceAdjacencies();
  86051. var p0Index = indices[index];
  86052. var p1Index = indices[index + 1];
  86053. var p2Index = indices[index + 2];
  86054. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  86055. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  86056. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  86057. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  86058. faceNormal.normalize();
  86059. faceNormals.push(faceNormal);
  86060. adjacencies.push(faceAdjacencies);
  86061. }
  86062. // Scan
  86063. for (index = 0; index < adjacencies.length; index++) {
  86064. faceAdjacencies = adjacencies[index];
  86065. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  86066. var otherFaceAdjacencies = adjacencies[otherIndex];
  86067. if (faceAdjacencies.edgesConnectedCount === 3) {
  86068. break;
  86069. }
  86070. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  86071. continue;
  86072. }
  86073. var otherP0 = indices[otherIndex * 3];
  86074. var otherP1 = indices[otherIndex * 3 + 1];
  86075. var otherP2 = indices[otherIndex * 3 + 2];
  86076. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  86077. var otherEdgeIndex = 0;
  86078. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  86079. continue;
  86080. }
  86081. switch (edgeIndex) {
  86082. case 0:
  86083. if (this._checkVerticesInsteadOfIndices) {
  86084. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86085. }
  86086. else {
  86087. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  86088. }
  86089. break;
  86090. case 1:
  86091. if (this._checkVerticesInsteadOfIndices) {
  86092. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86093. }
  86094. else {
  86095. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  86096. }
  86097. break;
  86098. case 2:
  86099. if (this._checkVerticesInsteadOfIndices) {
  86100. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86101. }
  86102. else {
  86103. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  86104. }
  86105. break;
  86106. }
  86107. if (otherEdgeIndex === -1) {
  86108. continue;
  86109. }
  86110. faceAdjacencies.edges[edgeIndex] = otherIndex;
  86111. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  86112. faceAdjacencies.edgesConnectedCount++;
  86113. otherFaceAdjacencies.edgesConnectedCount++;
  86114. if (faceAdjacencies.edgesConnectedCount === 3) {
  86115. break;
  86116. }
  86117. }
  86118. }
  86119. }
  86120. // Create lines
  86121. for (index = 0; index < adjacencies.length; index++) {
  86122. // 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
  86123. var current = adjacencies[index];
  86124. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  86125. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  86126. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  86127. }
  86128. // Merge into a single mesh
  86129. var engine = this._source.getScene().getEngine();
  86130. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  86131. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  86132. this._ib = engine.createIndexBuffer(this._linesIndices);
  86133. this._indicesCount = this._linesIndices.length;
  86134. };
  86135. EdgesRenderer.prototype.render = function () {
  86136. var scene = this._source.getScene();
  86137. if (!this._lineShader.isReady() || !scene.activeCamera) {
  86138. return;
  86139. }
  86140. var engine = scene.getEngine();
  86141. this._lineShader._preBind();
  86142. // VBOs
  86143. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  86144. scene.resetCachedMaterial();
  86145. this._lineShader.setColor4("color", this._source.edgesColor);
  86146. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  86147. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  86148. }
  86149. else {
  86150. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  86151. }
  86152. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  86153. this._lineShader.bind(this._source.getWorldMatrix());
  86154. // Draw order
  86155. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  86156. this._lineShader.unbind();
  86157. engine.setDepthWrite(true);
  86158. };
  86159. return EdgesRenderer;
  86160. }());
  86161. BABYLON.EdgesRenderer = EdgesRenderer;
  86162. })(BABYLON || (BABYLON = {}));
  86163. //# sourceMappingURL=babylon.edgesRenderer.js.map
  86164. "use strict";
  86165. var __assign = (this && this.__assign) || Object.assign || function(t) {
  86166. for (var s, i = 1, n = arguments.length; i < n; i++) {
  86167. s = arguments[i];
  86168. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  86169. t[p] = s[p];
  86170. }
  86171. return t;
  86172. };
  86173. var BABYLON;
  86174. (function (BABYLON) {
  86175. /**
  86176. * The effect layer Helps adding post process effect blended with the main pass.
  86177. *
  86178. * This can be for instance use to generate glow or higlight effects on the scene.
  86179. *
  86180. * The effect layer class can not be used directly and is intented to inherited from to be
  86181. * customized per effects.
  86182. */
  86183. var EffectLayer = /** @class */ (function () {
  86184. /**
  86185. * Instantiates a new effect Layer and references it in the scene.
  86186. * @param name The name of the layer
  86187. * @param scene The scene to use the layer in
  86188. */
  86189. function EffectLayer(
  86190. /** The Friendly of the effect in the scene */
  86191. name, scene) {
  86192. this.name = name;
  86193. this._vertexBuffers = {};
  86194. this._maxSize = 0;
  86195. this._mainTextureDesiredSize = { width: 0, height: 0 };
  86196. this._shouldRender = true;
  86197. this._postProcesses = [];
  86198. this._textures = [];
  86199. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  86200. /**
  86201. * The clear color of the texture used to generate the glow map.
  86202. */
  86203. this.neutralColor = new BABYLON.Color4();
  86204. /**
  86205. * Specifies wether the highlight layer is enabled or not.
  86206. */
  86207. this.isEnabled = true;
  86208. /**
  86209. * An event triggered when the effect layer has been disposed.
  86210. */
  86211. this.onDisposeObservable = new BABYLON.Observable();
  86212. /**
  86213. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  86214. */
  86215. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  86216. /**
  86217. * An event triggered when the generated texture is being merged in the scene.
  86218. */
  86219. this.onBeforeComposeObservable = new BABYLON.Observable();
  86220. /**
  86221. * An event triggered when the generated texture has been merged in the scene.
  86222. */
  86223. this.onAfterComposeObservable = new BABYLON.Observable();
  86224. /**
  86225. * An event triggered when the efffect layer changes its size.
  86226. */
  86227. this.onSizeChangedObservable = new BABYLON.Observable();
  86228. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86229. this._engine = scene.getEngine();
  86230. this._maxSize = this._engine.getCaps().maxTextureSize;
  86231. this._scene.effectLayers.push(this);
  86232. // Generate Buffers
  86233. this._generateIndexBuffer();
  86234. this._genrateVertexBuffer();
  86235. }
  86236. Object.defineProperty(EffectLayer.prototype, "camera", {
  86237. /**
  86238. * Gets the camera attached to the layer.
  86239. */
  86240. get: function () {
  86241. return this._effectLayerOptions.camera;
  86242. },
  86243. enumerable: true,
  86244. configurable: true
  86245. });
  86246. /**
  86247. * Initializes the effect layer with the required options.
  86248. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  86249. */
  86250. EffectLayer.prototype._init = function (options) {
  86251. // Adapt options
  86252. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  86253. this._setMainTextureSize();
  86254. this._createMainTexture();
  86255. this._createTextureAndPostProcesses();
  86256. this._mergeEffect = this._createMergeEffect();
  86257. };
  86258. /**
  86259. * Generates the index buffer of the full screen quad blending to the main canvas.
  86260. */
  86261. EffectLayer.prototype._generateIndexBuffer = function () {
  86262. // Indices
  86263. var indices = [];
  86264. indices.push(0);
  86265. indices.push(1);
  86266. indices.push(2);
  86267. indices.push(0);
  86268. indices.push(2);
  86269. indices.push(3);
  86270. this._indexBuffer = this._engine.createIndexBuffer(indices);
  86271. };
  86272. /**
  86273. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  86274. */
  86275. EffectLayer.prototype._genrateVertexBuffer = function () {
  86276. // VBO
  86277. var vertices = [];
  86278. vertices.push(1, 1);
  86279. vertices.push(-1, 1);
  86280. vertices.push(-1, -1);
  86281. vertices.push(1, -1);
  86282. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86283. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  86284. };
  86285. /**
  86286. * Sets the main texture desired size which is the closest power of two
  86287. * of the engine canvas size.
  86288. */
  86289. EffectLayer.prototype._setMainTextureSize = function () {
  86290. if (this._effectLayerOptions.mainTextureFixedSize) {
  86291. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  86292. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  86293. }
  86294. else {
  86295. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  86296. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  86297. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  86298. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  86299. }
  86300. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  86301. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  86302. };
  86303. /**
  86304. * Creates the main texture for the effect layer.
  86305. */
  86306. EffectLayer.prototype._createMainTexture = function () {
  86307. var _this = this;
  86308. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  86309. width: this._mainTextureDesiredSize.width,
  86310. height: this._mainTextureDesiredSize.height
  86311. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86312. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  86313. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86314. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86315. this._mainTexture.anisotropicFilteringLevel = 1;
  86316. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86317. this._mainTexture.renderParticles = false;
  86318. this._mainTexture.renderList = null;
  86319. this._mainTexture.ignoreCameraViewport = true;
  86320. // Custom render function
  86321. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  86322. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  86323. var index;
  86324. var engine = _this._scene.getEngine();
  86325. if (depthOnlySubMeshes.length) {
  86326. engine.setColorWrite(false);
  86327. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  86328. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  86329. }
  86330. engine.setColorWrite(true);
  86331. }
  86332. for (index = 0; index < opaqueSubMeshes.length; index++) {
  86333. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  86334. }
  86335. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  86336. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  86337. }
  86338. for (index = 0; index < transparentSubMeshes.length; index++) {
  86339. _this._renderSubMesh(transparentSubMeshes.data[index]);
  86340. }
  86341. };
  86342. this._mainTexture.onClearObservable.add(function (engine) {
  86343. engine.clear(_this.neutralColor, true, true, true);
  86344. });
  86345. };
  86346. /**
  86347. * Checks for the readiness of the element composing the layer.
  86348. * @param subMesh the mesh to check for
  86349. * @param useInstances specify wether or not to use instances to render the mesh
  86350. * @param emissiveTexture the associated emissive texture used to generate the glow
  86351. * @return true if ready otherwise, false
  86352. */
  86353. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  86354. var material = subMesh.getMaterial();
  86355. if (!material) {
  86356. return false;
  86357. }
  86358. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  86359. return false;
  86360. }
  86361. var defines = [];
  86362. var attribs = [BABYLON.VertexBuffer.PositionKind];
  86363. var mesh = subMesh.getMesh();
  86364. var uv1 = false;
  86365. var uv2 = false;
  86366. // Alpha test
  86367. if (material && material.needAlphaTesting()) {
  86368. var alphaTexture = material.getAlphaTestTexture();
  86369. if (alphaTexture) {
  86370. defines.push("#define ALPHATEST");
  86371. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  86372. alphaTexture.coordinatesIndex === 1) {
  86373. defines.push("#define DIFFUSEUV2");
  86374. uv2 = true;
  86375. }
  86376. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86377. defines.push("#define DIFFUSEUV1");
  86378. uv1 = true;
  86379. }
  86380. }
  86381. }
  86382. // Emissive
  86383. if (emissiveTexture) {
  86384. defines.push("#define EMISSIVE");
  86385. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  86386. emissiveTexture.coordinatesIndex === 1) {
  86387. defines.push("#define EMISSIVEUV2");
  86388. uv2 = true;
  86389. }
  86390. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86391. defines.push("#define EMISSIVEUV1");
  86392. uv1 = true;
  86393. }
  86394. }
  86395. if (uv1) {
  86396. attribs.push(BABYLON.VertexBuffer.UVKind);
  86397. defines.push("#define UV1");
  86398. }
  86399. if (uv2) {
  86400. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  86401. defines.push("#define UV2");
  86402. }
  86403. // Bones
  86404. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  86405. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  86406. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  86407. if (mesh.numBoneInfluencers > 4) {
  86408. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  86409. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  86410. }
  86411. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  86412. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  86413. }
  86414. else {
  86415. defines.push("#define NUM_BONE_INFLUENCERS 0");
  86416. }
  86417. // Instances
  86418. if (useInstances) {
  86419. defines.push("#define INSTANCES");
  86420. attribs.push("world0");
  86421. attribs.push("world1");
  86422. attribs.push("world2");
  86423. attribs.push("world3");
  86424. }
  86425. // Get correct effect
  86426. var join = defines.join("\n");
  86427. if (this._cachedDefines !== join) {
  86428. this._cachedDefines = join;
  86429. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  86430. }
  86431. return this._effectLayerMapGenerationEffect.isReady();
  86432. };
  86433. /**
  86434. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  86435. */
  86436. EffectLayer.prototype.render = function () {
  86437. var currentEffect = this._mergeEffect;
  86438. // Check
  86439. if (!currentEffect.isReady())
  86440. return;
  86441. for (var i = 0; i < this._postProcesses.length; i++) {
  86442. if (!this._postProcesses[i].isReady()) {
  86443. return;
  86444. }
  86445. }
  86446. var engine = this._scene.getEngine();
  86447. this.onBeforeComposeObservable.notifyObservers(this);
  86448. // Render
  86449. engine.enableEffect(currentEffect);
  86450. engine.setState(false);
  86451. // VBOs
  86452. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  86453. // Cache
  86454. var previousAlphaMode = engine.getAlphaMode();
  86455. // Go Blend.
  86456. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  86457. // Blends the map on the main canvas.
  86458. this._internalRender(currentEffect);
  86459. // Restore Alpha
  86460. engine.setAlphaMode(previousAlphaMode);
  86461. this.onAfterComposeObservable.notifyObservers(this);
  86462. // Handle size changes.
  86463. var size = this._mainTexture.getSize();
  86464. this._setMainTextureSize();
  86465. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  86466. // Recreate RTT and post processes on size change.
  86467. this.onSizeChangedObservable.notifyObservers(this);
  86468. this._disposeTextureAndPostProcesses();
  86469. this._createMainTexture();
  86470. this._createTextureAndPostProcesses();
  86471. }
  86472. };
  86473. /**
  86474. * Determine if a given mesh will be used in the current effect.
  86475. * @param mesh mesh to test
  86476. * @returns true if the mesh will be used
  86477. */
  86478. EffectLayer.prototype.hasMesh = function (mesh) {
  86479. return true;
  86480. };
  86481. /**
  86482. * Returns true if the layer contains information to display, otherwise false.
  86483. * @returns true if the glow layer should be rendered
  86484. */
  86485. EffectLayer.prototype.shouldRender = function () {
  86486. return this.isEnabled && this._shouldRender;
  86487. };
  86488. /**
  86489. * Returns true if the mesh should render, otherwise false.
  86490. * @param mesh The mesh to render
  86491. * @returns true if it should render otherwise false
  86492. */
  86493. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  86494. return true;
  86495. };
  86496. /**
  86497. * Returns true if the mesh should render, otherwise false.
  86498. * @param mesh The mesh to render
  86499. * @returns true if it should render otherwise false
  86500. */
  86501. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  86502. return true;
  86503. };
  86504. /**
  86505. * Renders the submesh passed in parameter to the generation map.
  86506. */
  86507. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  86508. var _this = this;
  86509. if (!this.shouldRender()) {
  86510. return;
  86511. }
  86512. var material = subMesh.getMaterial();
  86513. var mesh = subMesh.getRenderingMesh();
  86514. var scene = this._scene;
  86515. var engine = scene.getEngine();
  86516. if (!material) {
  86517. return;
  86518. }
  86519. // Do not block in blend mode.
  86520. if (material.needAlphaBlendingForMesh(mesh)) {
  86521. return;
  86522. }
  86523. // Culling
  86524. engine.setState(material.backFaceCulling);
  86525. // Managing instances
  86526. var batch = mesh._getInstancesRenderList(subMesh._id);
  86527. if (batch.mustReturn) {
  86528. return;
  86529. }
  86530. // Early Exit per mesh
  86531. if (!this._shouldRenderMesh(mesh)) {
  86532. return;
  86533. }
  86534. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  86535. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  86536. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  86537. engine.enableEffect(this._effectLayerMapGenerationEffect);
  86538. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  86539. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  86540. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  86541. // Alpha test
  86542. if (material && material.needAlphaTesting()) {
  86543. var alphaTexture = material.getAlphaTestTexture();
  86544. if (alphaTexture) {
  86545. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  86546. var textureMatrix = alphaTexture.getTextureMatrix();
  86547. if (textureMatrix) {
  86548. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  86549. }
  86550. }
  86551. }
  86552. // Glow emissive only
  86553. if (this._emissiveTextureAndColor.texture) {
  86554. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  86555. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  86556. }
  86557. // Bones
  86558. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  86559. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  86560. }
  86561. // Draw
  86562. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  86563. }
  86564. else {
  86565. // Need to reset refresh rate of the shadowMap
  86566. this._mainTexture.resetRefreshCounter();
  86567. }
  86568. };
  86569. /**
  86570. * Rebuild the required buffers.
  86571. * @ignore Internal use only.
  86572. */
  86573. EffectLayer.prototype._rebuild = function () {
  86574. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86575. if (vb) {
  86576. vb._rebuild();
  86577. }
  86578. this._generateIndexBuffer();
  86579. };
  86580. /**
  86581. * Dispose only the render target textures and post process.
  86582. */
  86583. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  86584. this._mainTexture.dispose();
  86585. for (var i = 0; i < this._postProcesses.length; i++) {
  86586. if (this._postProcesses[i]) {
  86587. this._postProcesses[i].dispose();
  86588. }
  86589. }
  86590. this._postProcesses = [];
  86591. for (var i = 0; i < this._textures.length; i++) {
  86592. if (this._textures[i]) {
  86593. this._textures[i].dispose();
  86594. }
  86595. }
  86596. this._textures = [];
  86597. };
  86598. /**
  86599. * Dispose the highlight layer and free resources.
  86600. */
  86601. EffectLayer.prototype.dispose = function () {
  86602. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86603. if (vertexBuffer) {
  86604. vertexBuffer.dispose();
  86605. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86606. }
  86607. if (this._indexBuffer) {
  86608. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86609. this._indexBuffer = null;
  86610. }
  86611. // Clean textures and post processes
  86612. this._disposeTextureAndPostProcesses();
  86613. // Remove from scene
  86614. var index = this._scene.effectLayers.indexOf(this, 0);
  86615. if (index > -1) {
  86616. this._scene.effectLayers.splice(index, 1);
  86617. }
  86618. // Callback
  86619. this.onDisposeObservable.notifyObservers(this);
  86620. this.onDisposeObservable.clear();
  86621. this.onBeforeRenderMainTextureObservable.clear();
  86622. this.onBeforeComposeObservable.clear();
  86623. this.onAfterComposeObservable.clear();
  86624. this.onSizeChangedObservable.clear();
  86625. };
  86626. return EffectLayer;
  86627. }());
  86628. BABYLON.EffectLayer = EffectLayer;
  86629. })(BABYLON || (BABYLON = {}));
  86630. //# sourceMappingURL=babylon.effectLayer.js.map
  86631. "use strict";
  86632. var BABYLON;
  86633. (function (BABYLON) {
  86634. /**
  86635. * Special Glow Blur post process only blurring the alpha channel
  86636. * It enforces keeping the most luminous color in the color channel.
  86637. */
  86638. var GlowBlurPostProcess = /** @class */ (function (_super) {
  86639. __extends(GlowBlurPostProcess, _super);
  86640. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  86641. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  86642. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  86643. _this.direction = direction;
  86644. _this.kernel = kernel;
  86645. _this.onApplyObservable.add(function (effect) {
  86646. effect.setFloat2("screenSize", _this.width, _this.height);
  86647. effect.setVector2("direction", _this.direction);
  86648. effect.setFloat("blurWidth", _this.kernel);
  86649. });
  86650. return _this;
  86651. }
  86652. return GlowBlurPostProcess;
  86653. }(BABYLON.PostProcess));
  86654. /**
  86655. * The highlight layer Helps adding a glow effect around a mesh.
  86656. *
  86657. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  86658. * glowy meshes to your scene.
  86659. *
  86660. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  86661. */
  86662. var HighlightLayer = /** @class */ (function (_super) {
  86663. __extends(HighlightLayer, _super);
  86664. /**
  86665. * Instantiates a new highlight Layer and references it to the scene..
  86666. * @param name The name of the layer
  86667. * @param scene The scene to use the layer in
  86668. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  86669. */
  86670. function HighlightLayer(name, scene, options) {
  86671. var _this = _super.call(this, name, scene) || this;
  86672. _this.name = name;
  86673. /**
  86674. * Specifies whether or not the inner glow is ACTIVE in the layer.
  86675. */
  86676. _this.innerGlow = true;
  86677. /**
  86678. * Specifies whether or not the outer glow is ACTIVE in the layer.
  86679. */
  86680. _this.outerGlow = true;
  86681. /**
  86682. * An event triggered when the highlight layer is being blurred.
  86683. */
  86684. _this.onBeforeBlurObservable = new BABYLON.Observable();
  86685. /**
  86686. * An event triggered when the highlight layer has been blurred.
  86687. */
  86688. _this.onAfterBlurObservable = new BABYLON.Observable();
  86689. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  86690. _this._meshes = {};
  86691. _this._excludedMeshes = {};
  86692. _this.neutralColor = HighlightLayer.NeutralColor;
  86693. // Warn on stencil
  86694. if (!_this._engine.isStencilEnable) {
  86695. 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 }");
  86696. }
  86697. // Adapt options
  86698. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  86699. // Initialize the layer
  86700. _this._init({
  86701. alphaBlendingMode: _this._options.alphaBlendingMode,
  86702. camera: _this._options.camera,
  86703. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  86704. mainTextureRatio: _this._options.mainTextureRatio
  86705. });
  86706. // Do not render as long as no meshes have been added
  86707. _this._shouldRender = false;
  86708. return _this;
  86709. }
  86710. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  86711. /**
  86712. * Gets the horizontal size of the blur.
  86713. */
  86714. get: function () {
  86715. return this._horizontalBlurPostprocess.kernel;
  86716. },
  86717. /**
  86718. * Specifies the horizontal size of the blur.
  86719. */
  86720. set: function (value) {
  86721. this._horizontalBlurPostprocess.kernel = value;
  86722. },
  86723. enumerable: true,
  86724. configurable: true
  86725. });
  86726. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  86727. /**
  86728. * Gets the vertical size of the blur.
  86729. */
  86730. get: function () {
  86731. return this._verticalBlurPostprocess.kernel;
  86732. },
  86733. /**
  86734. * Specifies the vertical size of the blur.
  86735. */
  86736. set: function (value) {
  86737. this._verticalBlurPostprocess.kernel = value;
  86738. },
  86739. enumerable: true,
  86740. configurable: true
  86741. });
  86742. /**
  86743. * Get the effect name of the layer.
  86744. * @return The effect name
  86745. */
  86746. HighlightLayer.prototype.getEffectName = function () {
  86747. return HighlightLayer.EffectName;
  86748. };
  86749. /**
  86750. * Create the merge effect. This is the shader use to blit the information back
  86751. * to the main canvas at the end of the scene rendering.
  86752. */
  86753. HighlightLayer.prototype._createMergeEffect = function () {
  86754. // Effect
  86755. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  86756. };
  86757. /**
  86758. * Creates the render target textures and post processes used in the highlight layer.
  86759. */
  86760. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  86761. var _this = this;
  86762. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  86763. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  86764. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  86765. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  86766. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  86767. width: blurTextureWidth,
  86768. height: blurTextureHeight
  86769. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86770. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86771. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86772. this._blurTexture.anisotropicFilteringLevel = 16;
  86773. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  86774. this._blurTexture.renderParticles = false;
  86775. this._blurTexture.ignoreCameraViewport = true;
  86776. this._textures = [this._blurTexture];
  86777. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  86778. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86779. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  86780. effect.setTexture("textureSampler", _this._mainTexture);
  86781. });
  86782. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86783. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  86784. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  86785. });
  86786. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86787. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  86788. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  86789. });
  86790. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  86791. }
  86792. else {
  86793. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  86794. width: blurTextureWidth,
  86795. height: blurTextureHeight
  86796. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86797. this._horizontalBlurPostprocess.width = blurTextureWidth;
  86798. this._horizontalBlurPostprocess.height = blurTextureHeight;
  86799. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  86800. effect.setTexture("textureSampler", _this._mainTexture);
  86801. });
  86802. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  86803. width: blurTextureWidth,
  86804. height: blurTextureHeight
  86805. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86806. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  86807. }
  86808. this._mainTexture.onAfterUnbindObservable.add(function () {
  86809. _this.onBeforeBlurObservable.notifyObservers(_this);
  86810. var internalTexture = _this._blurTexture.getInternalTexture();
  86811. if (internalTexture) {
  86812. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  86813. }
  86814. _this.onAfterBlurObservable.notifyObservers(_this);
  86815. });
  86816. // Prevent autoClear.
  86817. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  86818. };
  86819. /**
  86820. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  86821. */
  86822. HighlightLayer.prototype.needStencil = function () {
  86823. return true;
  86824. };
  86825. /**
  86826. * Checks for the readiness of the element composing the layer.
  86827. * @param subMesh the mesh to check for
  86828. * @param useInstances specify wether or not to use instances to render the mesh
  86829. * @param emissiveTexture the associated emissive texture used to generate the glow
  86830. * @return true if ready otherwise, false
  86831. */
  86832. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  86833. var material = subMesh.getMaterial();
  86834. var mesh = subMesh.getRenderingMesh();
  86835. if (!material || !mesh || !this._meshes) {
  86836. return false;
  86837. }
  86838. var emissiveTexture = null;
  86839. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  86840. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  86841. emissiveTexture = material.emissiveTexture;
  86842. }
  86843. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  86844. };
  86845. /**
  86846. * Implementation specific of rendering the generating effect on the main canvas.
  86847. * @param effect The effect used to render through
  86848. */
  86849. HighlightLayer.prototype._internalRender = function (effect) {
  86850. // Texture
  86851. effect.setTexture("textureSampler", this._blurTexture);
  86852. // Cache
  86853. var engine = this._engine;
  86854. var previousStencilBuffer = engine.getStencilBuffer();
  86855. var previousStencilFunction = engine.getStencilFunction();
  86856. var previousStencilMask = engine.getStencilMask();
  86857. var previousStencilOperationPass = engine.getStencilOperationPass();
  86858. var previousStencilOperationFail = engine.getStencilOperationFail();
  86859. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  86860. var previousStencilReference = engine.getStencilFunctionReference();
  86861. // Stencil operations
  86862. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  86863. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  86864. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  86865. // Draw order
  86866. engine.setStencilMask(0x00);
  86867. engine.setStencilBuffer(true);
  86868. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  86869. // 2 passes inner outer
  86870. if (this.outerGlow) {
  86871. effect.setFloat("offset", 0);
  86872. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  86873. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86874. }
  86875. if (this.innerGlow) {
  86876. effect.setFloat("offset", 1);
  86877. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  86878. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86879. }
  86880. // Restore Cache
  86881. engine.setStencilFunction(previousStencilFunction);
  86882. engine.setStencilMask(previousStencilMask);
  86883. engine.setStencilBuffer(previousStencilBuffer);
  86884. engine.setStencilOperationPass(previousStencilOperationPass);
  86885. engine.setStencilOperationFail(previousStencilOperationFail);
  86886. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  86887. engine.setStencilFunctionReference(previousStencilReference);
  86888. };
  86889. /**
  86890. * Returns true if the layer contains information to display, otherwise false.
  86891. */
  86892. HighlightLayer.prototype.shouldRender = function () {
  86893. if (_super.prototype.shouldRender.call(this)) {
  86894. return this._meshes ? true : false;
  86895. }
  86896. return false;
  86897. };
  86898. /**
  86899. * Returns true if the mesh should render, otherwise false.
  86900. * @param mesh The mesh to render
  86901. * @returns true if it should render otherwise false
  86902. */
  86903. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  86904. // Excluded Mesh
  86905. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  86906. return false;
  86907. }
  86908. ;
  86909. return true;
  86910. };
  86911. /**
  86912. * Sets the required values for both the emissive texture and and the main color.
  86913. */
  86914. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  86915. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  86916. if (highlightLayerMesh) {
  86917. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  86918. }
  86919. else {
  86920. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  86921. }
  86922. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  86923. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  86924. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  86925. }
  86926. else {
  86927. this._emissiveTextureAndColor.texture = null;
  86928. }
  86929. };
  86930. /**
  86931. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  86932. * @param mesh The mesh to exclude from the highlight layer
  86933. */
  86934. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  86935. if (!this._excludedMeshes) {
  86936. return;
  86937. }
  86938. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  86939. if (!meshExcluded) {
  86940. this._excludedMeshes[mesh.uniqueId] = {
  86941. mesh: mesh,
  86942. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  86943. mesh.getEngine().setStencilBuffer(false);
  86944. }),
  86945. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  86946. mesh.getEngine().setStencilBuffer(true);
  86947. }),
  86948. };
  86949. }
  86950. };
  86951. /**
  86952. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  86953. * @param mesh The mesh to highlight
  86954. */
  86955. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  86956. if (!this._excludedMeshes) {
  86957. return;
  86958. }
  86959. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  86960. if (meshExcluded) {
  86961. if (meshExcluded.beforeRender) {
  86962. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  86963. }
  86964. if (meshExcluded.afterRender) {
  86965. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  86966. }
  86967. }
  86968. this._excludedMeshes[mesh.uniqueId] = null;
  86969. };
  86970. /**
  86971. * Determine if a given mesh will be highlighted by the current HighlightLayer
  86972. * @param mesh mesh to test
  86973. * @returns true if the mesh will be highlighted by the current HighlightLayer
  86974. */
  86975. HighlightLayer.prototype.hasMesh = function (mesh) {
  86976. if (!this._meshes) {
  86977. return false;
  86978. }
  86979. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  86980. };
  86981. /**
  86982. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  86983. * @param mesh The mesh to highlight
  86984. * @param color The color of the highlight
  86985. * @param glowEmissiveOnly Extract the glow from the emissive texture
  86986. */
  86987. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  86988. var _this = this;
  86989. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  86990. if (!this._meshes) {
  86991. return;
  86992. }
  86993. var meshHighlight = this._meshes[mesh.uniqueId];
  86994. if (meshHighlight) {
  86995. meshHighlight.color = color;
  86996. }
  86997. else {
  86998. this._meshes[mesh.uniqueId] = {
  86999. mesh: mesh,
  87000. color: color,
  87001. // Lambda required for capture due to Observable this context
  87002. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  87003. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  87004. _this._defaultStencilReference(mesh);
  87005. }
  87006. else {
  87007. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  87008. }
  87009. }),
  87010. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  87011. glowEmissiveOnly: glowEmissiveOnly
  87012. };
  87013. }
  87014. this._shouldRender = true;
  87015. };
  87016. /**
  87017. * Remove a mesh from the highlight layer in order to make it stop glowing.
  87018. * @param mesh The mesh to highlight
  87019. */
  87020. HighlightLayer.prototype.removeMesh = function (mesh) {
  87021. if (!this._meshes) {
  87022. return;
  87023. }
  87024. var meshHighlight = this._meshes[mesh.uniqueId];
  87025. if (meshHighlight) {
  87026. if (meshHighlight.observerHighlight) {
  87027. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  87028. }
  87029. if (meshHighlight.observerDefault) {
  87030. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  87031. }
  87032. delete this._meshes[mesh.uniqueId];
  87033. }
  87034. this._shouldRender = false;
  87035. for (var meshHighlightToCheck in this._meshes) {
  87036. if (this._meshes[meshHighlightToCheck]) {
  87037. this._shouldRender = true;
  87038. break;
  87039. }
  87040. }
  87041. };
  87042. /**
  87043. * Force the stencil to the normal expected value for none glowing parts
  87044. */
  87045. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  87046. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  87047. };
  87048. /**
  87049. * Free any resources and references associated to a mesh.
  87050. * Internal use
  87051. * @param mesh The mesh to free.
  87052. */
  87053. HighlightLayer.prototype._disposeMesh = function (mesh) {
  87054. this.removeMesh(mesh);
  87055. this.removeExcludedMesh(mesh);
  87056. };
  87057. /**
  87058. * Dispose the highlight layer and free resources.
  87059. */
  87060. HighlightLayer.prototype.dispose = function () {
  87061. if (this._meshes) {
  87062. // Clean mesh references
  87063. for (var id in this._meshes) {
  87064. var meshHighlight = this._meshes[id];
  87065. if (meshHighlight && meshHighlight.mesh) {
  87066. if (meshHighlight.observerHighlight) {
  87067. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  87068. }
  87069. if (meshHighlight.observerDefault) {
  87070. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  87071. }
  87072. }
  87073. }
  87074. this._meshes = null;
  87075. }
  87076. if (this._excludedMeshes) {
  87077. for (var id in this._excludedMeshes) {
  87078. var meshHighlight = this._excludedMeshes[id];
  87079. if (meshHighlight) {
  87080. if (meshHighlight.beforeRender) {
  87081. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  87082. }
  87083. if (meshHighlight.afterRender) {
  87084. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  87085. }
  87086. }
  87087. }
  87088. this._excludedMeshes = null;
  87089. }
  87090. _super.prototype.dispose.call(this);
  87091. };
  87092. /**
  87093. * Effect Name of the highlight layer.
  87094. */
  87095. HighlightLayer.EffectName = "HighlightLayer";
  87096. /**
  87097. * The neutral color used during the preparation of the glow effect.
  87098. * This is black by default as the blend operation is a blend operation.
  87099. */
  87100. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  87101. /**
  87102. * Stencil value used for glowing meshes.
  87103. */
  87104. HighlightLayer.GlowingMeshStencilReference = 0x02;
  87105. /**
  87106. * Stencil value used for the other meshes in the scene.
  87107. */
  87108. HighlightLayer.NormalMeshStencilReference = 0x01;
  87109. return HighlightLayer;
  87110. }(BABYLON.EffectLayer));
  87111. BABYLON.HighlightLayer = HighlightLayer;
  87112. })(BABYLON || (BABYLON = {}));
  87113. //# sourceMappingURL=babylon.highlightLayer.js.map
  87114. "use strict";
  87115. var BABYLON;
  87116. (function (BABYLON) {
  87117. /**
  87118. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  87119. *
  87120. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  87121. * glowy meshes to your scene.
  87122. *
  87123. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  87124. */
  87125. var GlowLayer = /** @class */ (function (_super) {
  87126. __extends(GlowLayer, _super);
  87127. /**
  87128. * Instantiates a new glow Layer and references it to the scene.
  87129. * @param name The name of the layer
  87130. * @param scene The scene to use the layer in
  87131. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  87132. */
  87133. function GlowLayer(name, scene, options) {
  87134. var _this = _super.call(this, name, scene) || this;
  87135. _this.name = name;
  87136. _this._intensity = 1.0;
  87137. _this._includedOnlyMeshes = [];
  87138. _this._excludedMeshes = [];
  87139. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  87140. // Adapt options
  87141. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  87142. // Initialize the layer
  87143. _this._init({
  87144. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  87145. camera: _this._options.camera,
  87146. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  87147. mainTextureRatio: _this._options.mainTextureRatio
  87148. });
  87149. return _this;
  87150. }
  87151. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  87152. /**
  87153. * Gets the kernel size of the blur.
  87154. */
  87155. get: function () {
  87156. return this._horizontalBlurPostprocess1.kernel;
  87157. },
  87158. /**
  87159. * Sets the kernel size of the blur.
  87160. */
  87161. set: function (value) {
  87162. this._horizontalBlurPostprocess1.kernel = value;
  87163. this._verticalBlurPostprocess1.kernel = value;
  87164. this._horizontalBlurPostprocess2.kernel = value;
  87165. this._verticalBlurPostprocess2.kernel = value;
  87166. },
  87167. enumerable: true,
  87168. configurable: true
  87169. });
  87170. Object.defineProperty(GlowLayer.prototype, "intensity", {
  87171. /**
  87172. * Gets the glow intensity.
  87173. */
  87174. get: function () {
  87175. return this._intensity;
  87176. },
  87177. /**
  87178. * Sets the glow intensity.
  87179. */
  87180. set: function (value) {
  87181. this._intensity = value;
  87182. },
  87183. enumerable: true,
  87184. configurable: true
  87185. });
  87186. /**
  87187. * Get the effect name of the layer.
  87188. * @return The effect name
  87189. */
  87190. GlowLayer.prototype.getEffectName = function () {
  87191. return GlowLayer.EffectName;
  87192. };
  87193. /**
  87194. * Create the merge effect. This is the shader use to blit the information back
  87195. * to the main canvas at the end of the scene rendering.
  87196. */
  87197. GlowLayer.prototype._createMergeEffect = function () {
  87198. // Effect
  87199. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  87200. };
  87201. /**
  87202. * Creates the render target textures and post processes used in the glow layer.
  87203. */
  87204. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  87205. var _this = this;
  87206. var blurTextureWidth = this._mainTextureDesiredSize.width;
  87207. var blurTextureHeight = this._mainTextureDesiredSize.height;
  87208. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  87209. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  87210. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  87211. width: blurTextureWidth,
  87212. height: blurTextureHeight
  87213. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87214. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87215. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87216. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87217. this._blurTexture1.renderParticles = false;
  87218. this._blurTexture1.ignoreCameraViewport = true;
  87219. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  87220. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  87221. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  87222. width: blurTextureWidth2,
  87223. height: blurTextureHeight2
  87224. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87225. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87226. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87227. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87228. this._blurTexture2.renderParticles = false;
  87229. this._blurTexture2.ignoreCameraViewport = true;
  87230. this._textures = [this._blurTexture1, this._blurTexture2];
  87231. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  87232. width: blurTextureWidth,
  87233. height: blurTextureHeight
  87234. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87235. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  87236. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  87237. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  87238. effect.setTexture("textureSampler", _this._mainTexture);
  87239. });
  87240. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  87241. width: blurTextureWidth,
  87242. height: blurTextureHeight
  87243. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87244. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  87245. width: blurTextureWidth2,
  87246. height: blurTextureHeight2
  87247. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87248. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  87249. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  87250. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  87251. effect.setTexture("textureSampler", _this._blurTexture1);
  87252. });
  87253. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  87254. width: blurTextureWidth2,
  87255. height: blurTextureHeight2
  87256. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87257. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  87258. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  87259. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  87260. this._mainTexture.samples = this._options.mainTextureSamples;
  87261. this._mainTexture.onAfterUnbindObservable.add(function () {
  87262. var internalTexture = _this._blurTexture1.getInternalTexture();
  87263. if (internalTexture) {
  87264. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  87265. internalTexture = _this._blurTexture2.getInternalTexture();
  87266. if (internalTexture) {
  87267. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  87268. }
  87269. }
  87270. });
  87271. // Prevent autoClear.
  87272. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  87273. };
  87274. /**
  87275. * Checks for the readiness of the element composing the layer.
  87276. * @param subMesh the mesh to check for
  87277. * @param useInstances specify wether or not to use instances to render the mesh
  87278. * @param emissiveTexture the associated emissive texture used to generate the glow
  87279. * @return true if ready otherwise, false
  87280. */
  87281. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  87282. var material = subMesh.getMaterial();
  87283. var mesh = subMesh.getRenderingMesh();
  87284. if (!material || !mesh) {
  87285. return false;
  87286. }
  87287. var emissiveTexture = material.emissiveTexture;
  87288. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  87289. };
  87290. /**
  87291. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  87292. */
  87293. GlowLayer.prototype.needStencil = function () {
  87294. return false;
  87295. };
  87296. /**
  87297. * Implementation specific of rendering the generating effect on the main canvas.
  87298. * @param effect The effect used to render through
  87299. */
  87300. GlowLayer.prototype._internalRender = function (effect) {
  87301. // Texture
  87302. effect.setTexture("textureSampler", this._blurTexture1);
  87303. effect.setTexture("textureSampler2", this._blurTexture2);
  87304. effect.setFloat("offset", this._intensity);
  87305. // Cache
  87306. var engine = this._engine;
  87307. var previousStencilBuffer = engine.getStencilBuffer();
  87308. // Draw order
  87309. engine.setStencilBuffer(false);
  87310. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87311. // Draw order
  87312. engine.setStencilBuffer(previousStencilBuffer);
  87313. };
  87314. /**
  87315. * Sets the required values for both the emissive texture and and the main color.
  87316. */
  87317. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  87318. var textureLevel = 1.0;
  87319. if (this.customEmissiveTextureSelector) {
  87320. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  87321. }
  87322. else {
  87323. if (material) {
  87324. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  87325. if (this._emissiveTextureAndColor.texture) {
  87326. textureLevel = this._emissiveTextureAndColor.texture.level;
  87327. }
  87328. }
  87329. else {
  87330. this._emissiveTextureAndColor.texture = null;
  87331. }
  87332. }
  87333. if (this.customEmissiveColorSelector) {
  87334. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  87335. }
  87336. else {
  87337. if (material.emissiveColor) {
  87338. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  87339. }
  87340. else {
  87341. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  87342. }
  87343. }
  87344. };
  87345. /**
  87346. * Returns true if the mesh should render, otherwise false.
  87347. * @param mesh The mesh to render
  87348. * @returns true if it should render otherwise false
  87349. */
  87350. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  87351. return this.hasMesh(mesh);
  87352. };
  87353. /**
  87354. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  87355. * @param mesh The mesh to exclude from the glow layer
  87356. */
  87357. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  87358. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  87359. this._excludedMeshes.push(mesh.uniqueId);
  87360. }
  87361. };
  87362. /**
  87363. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  87364. * @param mesh The mesh to remove
  87365. */
  87366. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  87367. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  87368. if (index !== -1) {
  87369. this._excludedMeshes.splice(index, 1);
  87370. }
  87371. };
  87372. /**
  87373. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  87374. * @param mesh The mesh to include in the glow layer
  87375. */
  87376. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  87377. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  87378. this._includedOnlyMeshes.push(mesh.uniqueId);
  87379. }
  87380. };
  87381. /**
  87382. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  87383. * @param mesh The mesh to remove
  87384. */
  87385. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  87386. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  87387. if (index !== -1) {
  87388. this._includedOnlyMeshes.splice(index, 1);
  87389. }
  87390. };
  87391. /**
  87392. * Determine if a given mesh will be used in the glow layer
  87393. * @param mesh The mesh to test
  87394. * @returns true if the mesh will be highlighted by the current glow layer
  87395. */
  87396. GlowLayer.prototype.hasMesh = function (mesh) {
  87397. // Included Mesh
  87398. if (this._includedOnlyMeshes.length) {
  87399. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  87400. }
  87401. ;
  87402. // Excluded Mesh
  87403. if (this._excludedMeshes.length) {
  87404. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  87405. }
  87406. ;
  87407. return true;
  87408. };
  87409. /**
  87410. * Free any resources and references associated to a mesh.
  87411. * Internal use
  87412. * @param mesh The mesh to free.
  87413. */
  87414. GlowLayer.prototype._disposeMesh = function (mesh) {
  87415. this.removeIncludedOnlyMesh(mesh);
  87416. this.removeExcludedMesh(mesh);
  87417. };
  87418. /**
  87419. * Effect Name of the layer.
  87420. */
  87421. GlowLayer.EffectName = "GlowLayer";
  87422. /**
  87423. * The default blur kernel size used for the glow.
  87424. */
  87425. GlowLayer.DefaultBlurKernelSize = 32;
  87426. /**
  87427. * The default texture size ratio used for the glow.
  87428. */
  87429. GlowLayer.DefaultTextureRatio = 0.5;
  87430. return GlowLayer;
  87431. }(BABYLON.EffectLayer));
  87432. BABYLON.GlowLayer = GlowLayer;
  87433. })(BABYLON || (BABYLON = {}));
  87434. //# sourceMappingURL=babylon.glowLayer.js.map
  87435. "use strict";
  87436. var BABYLON;
  87437. (function (BABYLON) {
  87438. /**
  87439. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  87440. */
  87441. var AssetTaskState;
  87442. (function (AssetTaskState) {
  87443. /**
  87444. * Initialization
  87445. */
  87446. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  87447. /**
  87448. * Running
  87449. */
  87450. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  87451. /**
  87452. * Done
  87453. */
  87454. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  87455. /**
  87456. * Error
  87457. */
  87458. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  87459. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  87460. /**
  87461. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  87462. */
  87463. var AbstractAssetTask = /** @class */ (function () {
  87464. /**
  87465. * Creates a new {BABYLON.AssetsManager}
  87466. * @param name defines the name of the task
  87467. */
  87468. function AbstractAssetTask(
  87469. /**
  87470. * Task name
  87471. */ name) {
  87472. this.name = name;
  87473. this._isCompleted = false;
  87474. this._taskState = AssetTaskState.INIT;
  87475. }
  87476. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  87477. /**
  87478. * Get if the task is completed
  87479. */
  87480. get: function () {
  87481. return this._isCompleted;
  87482. },
  87483. enumerable: true,
  87484. configurable: true
  87485. });
  87486. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  87487. /**
  87488. * Gets the current state of the task
  87489. */
  87490. get: function () {
  87491. return this._taskState;
  87492. },
  87493. enumerable: true,
  87494. configurable: true
  87495. });
  87496. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  87497. /**
  87498. * Gets the current error object (if task is in error)
  87499. */
  87500. get: function () {
  87501. return this._errorObject;
  87502. },
  87503. enumerable: true,
  87504. configurable: true
  87505. });
  87506. /**
  87507. * Internal only
  87508. * @ignore
  87509. */
  87510. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  87511. if (this._errorObject) {
  87512. return;
  87513. }
  87514. this._errorObject = {
  87515. message: message,
  87516. exception: exception
  87517. };
  87518. };
  87519. /**
  87520. * Execute the current task
  87521. * @param scene defines the scene where you want your assets to be loaded
  87522. * @param onSuccess is a callback called when the task is successfully executed
  87523. * @param onError is a callback called if an error occurs
  87524. */
  87525. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  87526. var _this = this;
  87527. this._taskState = AssetTaskState.RUNNING;
  87528. this.runTask(scene, function () {
  87529. _this.onDoneCallback(onSuccess, onError);
  87530. }, function (msg, exception) {
  87531. _this.onErrorCallback(onError, msg, exception);
  87532. });
  87533. };
  87534. /**
  87535. * Execute the current task
  87536. * @param scene defines the scene where you want your assets to be loaded
  87537. * @param onSuccess is a callback called when the task is successfully executed
  87538. * @param onError is a callback called if an error occurs
  87539. */
  87540. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87541. throw new Error("runTask is not implemented");
  87542. };
  87543. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  87544. this._taskState = AssetTaskState.ERROR;
  87545. this._errorObject = {
  87546. message: message,
  87547. exception: exception
  87548. };
  87549. if (this.onError) {
  87550. this.onError(this, message, exception);
  87551. }
  87552. onError();
  87553. };
  87554. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  87555. try {
  87556. this._taskState = AssetTaskState.DONE;
  87557. this._isCompleted = true;
  87558. if (this.onSuccess) {
  87559. this.onSuccess(this);
  87560. }
  87561. onSuccess();
  87562. }
  87563. catch (e) {
  87564. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  87565. }
  87566. };
  87567. return AbstractAssetTask;
  87568. }());
  87569. BABYLON.AbstractAssetTask = AbstractAssetTask;
  87570. /**
  87571. * Class used to share progress information about assets loading
  87572. */
  87573. var AssetsProgressEvent = /** @class */ (function () {
  87574. /**
  87575. * Creates a {BABYLON.AssetsProgressEvent}
  87576. * @param remainingCount defines the number of remaining tasks to process
  87577. * @param totalCount defines the total number of tasks
  87578. * @param task defines the task that was just processed
  87579. */
  87580. function AssetsProgressEvent(remainingCount, totalCount, task) {
  87581. this.remainingCount = remainingCount;
  87582. this.totalCount = totalCount;
  87583. this.task = task;
  87584. }
  87585. return AssetsProgressEvent;
  87586. }());
  87587. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  87588. /**
  87589. * Define a task used by {BABYLON.AssetsManager} to load meshes
  87590. */
  87591. var MeshAssetTask = /** @class */ (function (_super) {
  87592. __extends(MeshAssetTask, _super);
  87593. /**
  87594. * Creates a new {BABYLON.MeshAssetTask}
  87595. * @param name defines the name of the task
  87596. * @param meshesNames defines the list of mesh's names you want to load
  87597. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  87598. * @param sceneFilename defines the filename of the scene to load from
  87599. */
  87600. function MeshAssetTask(
  87601. /**
  87602. * Defines the name of the task
  87603. */
  87604. name,
  87605. /**
  87606. * Defines the list of mesh's names you want to load
  87607. */
  87608. meshesNames,
  87609. /**
  87610. * Defines the root url to use as a base to load your meshes and associated resources
  87611. */
  87612. rootUrl,
  87613. /**
  87614. * Defines the filename of the scene to load from
  87615. */
  87616. sceneFilename) {
  87617. var _this = _super.call(this, name) || this;
  87618. _this.name = name;
  87619. _this.meshesNames = meshesNames;
  87620. _this.rootUrl = rootUrl;
  87621. _this.sceneFilename = sceneFilename;
  87622. return _this;
  87623. }
  87624. /**
  87625. * Execute the current task
  87626. * @param scene defines the scene where you want your assets to be loaded
  87627. * @param onSuccess is a callback called when the task is successfully executed
  87628. * @param onError is a callback called if an error occurs
  87629. */
  87630. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87631. var _this = this;
  87632. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  87633. _this.loadedMeshes = meshes;
  87634. _this.loadedParticleSystems = particleSystems;
  87635. _this.loadedSkeletons = skeletons;
  87636. onSuccess();
  87637. }, null, function (scene, message, exception) {
  87638. onError(message, exception);
  87639. });
  87640. };
  87641. return MeshAssetTask;
  87642. }(AbstractAssetTask));
  87643. BABYLON.MeshAssetTask = MeshAssetTask;
  87644. /**
  87645. * Define a task used by {BABYLON.AssetsManager} to load text content
  87646. */
  87647. var TextFileAssetTask = /** @class */ (function (_super) {
  87648. __extends(TextFileAssetTask, _super);
  87649. /**
  87650. * Creates a new TextFileAssetTask object
  87651. * @param name defines the name of the task
  87652. * @param url defines the location of the file to load
  87653. */
  87654. function TextFileAssetTask(
  87655. /**
  87656. * Defines the name of the task
  87657. */
  87658. name,
  87659. /**
  87660. * Defines the location of the file to load
  87661. */
  87662. url) {
  87663. var _this = _super.call(this, name) || this;
  87664. _this.name = name;
  87665. _this.url = url;
  87666. return _this;
  87667. }
  87668. /**
  87669. * Execute the current task
  87670. * @param scene defines the scene where you want your assets to be loaded
  87671. * @param onSuccess is a callback called when the task is successfully executed
  87672. * @param onError is a callback called if an error occurs
  87673. */
  87674. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87675. var _this = this;
  87676. scene._loadFile(this.url, function (data) {
  87677. _this.text = data;
  87678. onSuccess();
  87679. }, undefined, false, false, function (request, exception) {
  87680. if (request) {
  87681. onError(request.status + " " + request.statusText, exception);
  87682. }
  87683. });
  87684. };
  87685. return TextFileAssetTask;
  87686. }(AbstractAssetTask));
  87687. BABYLON.TextFileAssetTask = TextFileAssetTask;
  87688. /**
  87689. * Define a task used by {BABYLON.AssetsManager} to load binary data
  87690. */
  87691. var BinaryFileAssetTask = /** @class */ (function (_super) {
  87692. __extends(BinaryFileAssetTask, _super);
  87693. /**
  87694. * Creates a new BinaryFileAssetTask object
  87695. * @param name defines the name of the new task
  87696. * @param url defines the location of the file to load
  87697. */
  87698. function BinaryFileAssetTask(
  87699. /**
  87700. * Defines the name of the task
  87701. */
  87702. name,
  87703. /**
  87704. * Defines the location of the file to load
  87705. */
  87706. url) {
  87707. var _this = _super.call(this, name) || this;
  87708. _this.name = name;
  87709. _this.url = url;
  87710. return _this;
  87711. }
  87712. /**
  87713. * Execute the current task
  87714. * @param scene defines the scene where you want your assets to be loaded
  87715. * @param onSuccess is a callback called when the task is successfully executed
  87716. * @param onError is a callback called if an error occurs
  87717. */
  87718. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87719. var _this = this;
  87720. scene._loadFile(this.url, function (data) {
  87721. _this.data = data;
  87722. onSuccess();
  87723. }, undefined, true, true, function (request, exception) {
  87724. if (request) {
  87725. onError(request.status + " " + request.statusText, exception);
  87726. }
  87727. });
  87728. };
  87729. return BinaryFileAssetTask;
  87730. }(AbstractAssetTask));
  87731. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  87732. /**
  87733. * Define a task used by {BABYLON.AssetsManager} to load images
  87734. */
  87735. var ImageAssetTask = /** @class */ (function (_super) {
  87736. __extends(ImageAssetTask, _super);
  87737. /**
  87738. * Creates a new ImageAssetTask
  87739. * @param name defines the name of the task
  87740. * @param url defines the location of the image to load
  87741. */
  87742. function ImageAssetTask(
  87743. /**
  87744. * Defines the name of the task
  87745. */
  87746. name,
  87747. /**
  87748. * Defines the location of the image to load
  87749. */
  87750. url) {
  87751. var _this = _super.call(this, name) || this;
  87752. _this.name = name;
  87753. _this.url = url;
  87754. return _this;
  87755. }
  87756. /**
  87757. * Execute the current task
  87758. * @param scene defines the scene where you want your assets to be loaded
  87759. * @param onSuccess is a callback called when the task is successfully executed
  87760. * @param onError is a callback called if an error occurs
  87761. */
  87762. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87763. var _this = this;
  87764. var img = new Image();
  87765. BABYLON.Tools.SetCorsBehavior(this.url, img);
  87766. img.onload = function () {
  87767. _this.image = img;
  87768. onSuccess();
  87769. };
  87770. img.onerror = function (err) {
  87771. onError("Error loading image", err);
  87772. };
  87773. img.src = this.url;
  87774. };
  87775. return ImageAssetTask;
  87776. }(AbstractAssetTask));
  87777. BABYLON.ImageAssetTask = ImageAssetTask;
  87778. /**
  87779. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  87780. */
  87781. var TextureAssetTask = /** @class */ (function (_super) {
  87782. __extends(TextureAssetTask, _super);
  87783. /**
  87784. * Creates a new TextureAssetTask object
  87785. * @param name defines the name of the task
  87786. * @param url defines the location of the file to load
  87787. * @param noMipmap defines if mipmap should not be generated (default is false)
  87788. * @param invertY defines if texture must be inverted on Y axis (default is false)
  87789. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  87790. */
  87791. function TextureAssetTask(
  87792. /**
  87793. * Defines the name of the task
  87794. */
  87795. name,
  87796. /**
  87797. * Defines the location of the file to load
  87798. */
  87799. url,
  87800. /**
  87801. * Defines if mipmap should not be generated (default is false)
  87802. */
  87803. noMipmap,
  87804. /**
  87805. * Defines if texture must be inverted on Y axis (default is false)
  87806. */
  87807. invertY,
  87808. /**
  87809. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  87810. */
  87811. samplingMode) {
  87812. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  87813. var _this = _super.call(this, name) || this;
  87814. _this.name = name;
  87815. _this.url = url;
  87816. _this.noMipmap = noMipmap;
  87817. _this.invertY = invertY;
  87818. _this.samplingMode = samplingMode;
  87819. return _this;
  87820. }
  87821. /**
  87822. * Execute the current task
  87823. * @param scene defines the scene where you want your assets to be loaded
  87824. * @param onSuccess is a callback called when the task is successfully executed
  87825. * @param onError is a callback called if an error occurs
  87826. */
  87827. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87828. var onload = function () {
  87829. onSuccess();
  87830. };
  87831. var onerror = function (message, exception) {
  87832. onError(message, exception);
  87833. };
  87834. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  87835. };
  87836. return TextureAssetTask;
  87837. }(AbstractAssetTask));
  87838. BABYLON.TextureAssetTask = TextureAssetTask;
  87839. /**
  87840. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  87841. */
  87842. var CubeTextureAssetTask = /** @class */ (function (_super) {
  87843. __extends(CubeTextureAssetTask, _super);
  87844. /**
  87845. * Creates a new CubeTextureAssetTask
  87846. * @param name defines the name of the task
  87847. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  87848. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  87849. * @param noMipmap defines if mipmaps should not be generated (default is false)
  87850. * @param files defines the explicit list of files (undefined by default)
  87851. */
  87852. function CubeTextureAssetTask(
  87853. /**
  87854. * Defines the name of the task
  87855. */
  87856. name,
  87857. /**
  87858. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  87859. */
  87860. url,
  87861. /**
  87862. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  87863. */
  87864. extensions,
  87865. /**
  87866. * Defines if mipmaps should not be generated (default is false)
  87867. */
  87868. noMipmap,
  87869. /**
  87870. * Defines the explicit list of files (undefined by default)
  87871. */
  87872. files) {
  87873. var _this = _super.call(this, name) || this;
  87874. _this.name = name;
  87875. _this.url = url;
  87876. _this.extensions = extensions;
  87877. _this.noMipmap = noMipmap;
  87878. _this.files = files;
  87879. return _this;
  87880. }
  87881. /**
  87882. * Execute the current task
  87883. * @param scene defines the scene where you want your assets to be loaded
  87884. * @param onSuccess is a callback called when the task is successfully executed
  87885. * @param onError is a callback called if an error occurs
  87886. */
  87887. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87888. var onload = function () {
  87889. onSuccess();
  87890. };
  87891. var onerror = function (message, exception) {
  87892. onError(message, exception);
  87893. };
  87894. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  87895. };
  87896. return CubeTextureAssetTask;
  87897. }(AbstractAssetTask));
  87898. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  87899. /**
  87900. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  87901. */
  87902. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  87903. __extends(HDRCubeTextureAssetTask, _super);
  87904. /**
  87905. * Creates a new HDRCubeTextureAssetTask object
  87906. * @param name defines the name of the task
  87907. * @param url defines the location of the file to load
  87908. * @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.
  87909. * @param noMipmap defines if mipmaps should not be generated (default is false)
  87910. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  87911. * @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)
  87912. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  87913. */
  87914. function HDRCubeTextureAssetTask(
  87915. /**
  87916. * Defines the name of the task
  87917. */
  87918. name,
  87919. /**
  87920. * Defines the location of the file to load
  87921. */
  87922. url,
  87923. /**
  87924. * 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.
  87925. */
  87926. size,
  87927. /**
  87928. * Defines if mipmaps should not be generated (default is false)
  87929. */
  87930. noMipmap,
  87931. /**
  87932. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  87933. */
  87934. generateHarmonics,
  87935. /**
  87936. * 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)
  87937. */
  87938. useInGammaSpace,
  87939. /**
  87940. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  87941. */
  87942. usePMREMGenerator) {
  87943. if (noMipmap === void 0) { noMipmap = false; }
  87944. if (generateHarmonics === void 0) { generateHarmonics = true; }
  87945. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  87946. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  87947. var _this = _super.call(this, name) || this;
  87948. _this.name = name;
  87949. _this.url = url;
  87950. _this.size = size;
  87951. _this.noMipmap = noMipmap;
  87952. _this.generateHarmonics = generateHarmonics;
  87953. _this.useInGammaSpace = useInGammaSpace;
  87954. _this.usePMREMGenerator = usePMREMGenerator;
  87955. return _this;
  87956. }
  87957. /**
  87958. * Execute the current task
  87959. * @param scene defines the scene where you want your assets to be loaded
  87960. * @param onSuccess is a callback called when the task is successfully executed
  87961. * @param onError is a callback called if an error occurs
  87962. */
  87963. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  87964. var onload = function () {
  87965. onSuccess();
  87966. };
  87967. var onerror = function (message, exception) {
  87968. onError(message, exception);
  87969. };
  87970. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  87971. };
  87972. return HDRCubeTextureAssetTask;
  87973. }(AbstractAssetTask));
  87974. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  87975. /**
  87976. * This class can be used to easily import assets into a scene
  87977. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  87978. */
  87979. var AssetsManager = /** @class */ (function () {
  87980. /**
  87981. * Creates a new AssetsManager
  87982. * @param scene defines the scene to work on
  87983. */
  87984. function AssetsManager(scene) {
  87985. this._isLoading = false;
  87986. this._tasks = new Array();
  87987. this._waitingTasksCount = 0;
  87988. this._totalTasksCount = 0;
  87989. /**
  87990. * Observable called when all tasks are processed
  87991. */
  87992. this.onTaskSuccessObservable = new BABYLON.Observable();
  87993. /**
  87994. * Observable called when a task had an error
  87995. */
  87996. this.onTaskErrorObservable = new BABYLON.Observable();
  87997. /**
  87998. * Observable called when a task is successful
  87999. */
  88000. this.onTasksDoneObservable = new BABYLON.Observable();
  88001. /**
  88002. * Observable called when a task is done (whatever the result is)
  88003. */
  88004. this.onProgressObservable = new BABYLON.Observable();
  88005. /**
  88006. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  88007. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  88008. */
  88009. this.useDefaultLoadingScreen = true;
  88010. this._scene = scene;
  88011. }
  88012. /**
  88013. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  88014. * @param taskName defines the name of the new task
  88015. * @param meshesNames defines the name of meshes to load
  88016. * @param rootUrl defines the root url to use to locate files
  88017. * @param sceneFilename defines the filename of the scene file
  88018. * @returns a new {BABYLON.MeshAssetTask} object
  88019. */
  88020. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  88021. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  88022. this._tasks.push(task);
  88023. return task;
  88024. };
  88025. /**
  88026. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  88027. * @param taskName defines the name of the new task
  88028. * @param url defines the url of the file to load
  88029. * @returns a new {BABYLON.TextFileAssetTask} object
  88030. */
  88031. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  88032. var task = new TextFileAssetTask(taskName, url);
  88033. this._tasks.push(task);
  88034. return task;
  88035. };
  88036. /**
  88037. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  88038. * @param taskName defines the name of the new task
  88039. * @param url defines the url of the file to load
  88040. * @returns a new {BABYLON.BinaryFileAssetTask} object
  88041. */
  88042. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  88043. var task = new BinaryFileAssetTask(taskName, url);
  88044. this._tasks.push(task);
  88045. return task;
  88046. };
  88047. /**
  88048. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  88049. * @param taskName defines the name of the new task
  88050. * @param url defines the url of the file to load
  88051. * @returns a new {BABYLON.ImageAssetTask} object
  88052. */
  88053. AssetsManager.prototype.addImageTask = function (taskName, url) {
  88054. var task = new ImageAssetTask(taskName, url);
  88055. this._tasks.push(task);
  88056. return task;
  88057. };
  88058. /**
  88059. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  88060. * @param taskName defines the name of the new task
  88061. * @param url defines the url of the file to load
  88062. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88063. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  88064. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  88065. * @returns a new {BABYLON.TextureAssetTask} object
  88066. */
  88067. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  88068. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  88069. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  88070. this._tasks.push(task);
  88071. return task;
  88072. };
  88073. /**
  88074. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  88075. * @param taskName defines the name of the new task
  88076. * @param url defines the url of the file to load
  88077. * @param extensions defines the extension to use to load the cube map (can be null)
  88078. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88079. * @param files defines the list of files to load (can be null)
  88080. * @returns a new {BABYLON.CubeTextureAssetTask} object
  88081. */
  88082. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  88083. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  88084. this._tasks.push(task);
  88085. return task;
  88086. };
  88087. /**
  88088. *
  88089. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  88090. * @param taskName defines the name of the new task
  88091. * @param url defines the url of the file to load
  88092. * @param size defines the size you want for the cubemap (can be null)
  88093. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88094. * @param generateHarmonics defines if you want to automatically generate (true by default)
  88095. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  88096. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  88097. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  88098. */
  88099. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  88100. if (noMipmap === void 0) { noMipmap = false; }
  88101. if (generateHarmonics === void 0) { generateHarmonics = true; }
  88102. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  88103. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  88104. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  88105. this._tasks.push(task);
  88106. return task;
  88107. };
  88108. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  88109. var _this = this;
  88110. this._waitingTasksCount--;
  88111. try {
  88112. if (task.taskState === AssetTaskState.DONE) {
  88113. // Let's remove successfull tasks
  88114. BABYLON.Tools.SetImmediate(function () {
  88115. var index = _this._tasks.indexOf(task);
  88116. if (index > -1) {
  88117. _this._tasks.splice(index, 1);
  88118. }
  88119. });
  88120. }
  88121. if (this.onProgress) {
  88122. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  88123. }
  88124. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  88125. }
  88126. catch (e) {
  88127. BABYLON.Tools.Error("Error running progress callbacks.");
  88128. console.log(e);
  88129. }
  88130. if (this._waitingTasksCount === 0) {
  88131. try {
  88132. if (this.onFinish) {
  88133. this.onFinish(this._tasks);
  88134. }
  88135. this.onTasksDoneObservable.notifyObservers(this._tasks);
  88136. }
  88137. catch (e) {
  88138. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  88139. console.log(e);
  88140. }
  88141. this._isLoading = false;
  88142. this._scene.getEngine().hideLoadingUI();
  88143. }
  88144. };
  88145. AssetsManager.prototype._runTask = function (task) {
  88146. var _this = this;
  88147. var done = function () {
  88148. try {
  88149. if (_this.onTaskSuccess) {
  88150. _this.onTaskSuccess(task);
  88151. }
  88152. _this.onTaskSuccessObservable.notifyObservers(task);
  88153. _this._decreaseWaitingTasksCount(task);
  88154. }
  88155. catch (e) {
  88156. error("Error executing task success callbacks", e);
  88157. }
  88158. };
  88159. var error = function (message, exception) {
  88160. task._setErrorObject(message, exception);
  88161. if (_this.onTaskError) {
  88162. _this.onTaskError(task);
  88163. }
  88164. _this.onTaskErrorObservable.notifyObservers(task);
  88165. _this._decreaseWaitingTasksCount(task);
  88166. };
  88167. task.run(this._scene, done, error);
  88168. };
  88169. /**
  88170. * Reset the {BABYLON.AssetsManager} and remove all tasks
  88171. * @return the current instance of the {BABYLON.AssetsManager}
  88172. */
  88173. AssetsManager.prototype.reset = function () {
  88174. this._isLoading = false;
  88175. this._tasks = new Array();
  88176. return this;
  88177. };
  88178. /**
  88179. * Start the loading process
  88180. * @return the current instance of the {BABYLON.AssetsManager}
  88181. */
  88182. AssetsManager.prototype.load = function () {
  88183. if (this._isLoading) {
  88184. return this;
  88185. }
  88186. this._isLoading = true;
  88187. this._waitingTasksCount = this._tasks.length;
  88188. this._totalTasksCount = this._tasks.length;
  88189. if (this._waitingTasksCount === 0) {
  88190. this._isLoading = false;
  88191. if (this.onFinish) {
  88192. this.onFinish(this._tasks);
  88193. }
  88194. this.onTasksDoneObservable.notifyObservers(this._tasks);
  88195. return this;
  88196. }
  88197. if (this.useDefaultLoadingScreen) {
  88198. this._scene.getEngine().displayLoadingUI();
  88199. }
  88200. for (var index = 0; index < this._tasks.length; index++) {
  88201. var task = this._tasks[index];
  88202. this._runTask(task);
  88203. }
  88204. return this;
  88205. };
  88206. return AssetsManager;
  88207. }());
  88208. BABYLON.AssetsManager = AssetsManager;
  88209. })(BABYLON || (BABYLON = {}));
  88210. //# sourceMappingURL=babylon.assetsManager.js.map
  88211. "use strict";
  88212. var BABYLON;
  88213. (function (BABYLON) {
  88214. var serializedGeometries = [];
  88215. var serializeGeometry = function (geometry, serializationGeometries) {
  88216. if (serializedGeometries[geometry.id]) {
  88217. return;
  88218. }
  88219. if (geometry.doNotSerialize) {
  88220. return;
  88221. }
  88222. if (geometry instanceof BABYLON.BoxGeometry) {
  88223. serializationGeometries.boxes.push(geometry.serialize());
  88224. }
  88225. else if (geometry instanceof BABYLON.SphereGeometry) {
  88226. serializationGeometries.spheres.push(geometry.serialize());
  88227. }
  88228. else if (geometry instanceof BABYLON.CylinderGeometry) {
  88229. serializationGeometries.cylinders.push(geometry.serialize());
  88230. }
  88231. else if (geometry instanceof BABYLON.TorusGeometry) {
  88232. serializationGeometries.toruses.push(geometry.serialize());
  88233. }
  88234. else if (geometry instanceof BABYLON.GroundGeometry) {
  88235. serializationGeometries.grounds.push(geometry.serialize());
  88236. }
  88237. else if (geometry instanceof BABYLON.Plane) {
  88238. serializationGeometries.planes.push(geometry.serialize());
  88239. }
  88240. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  88241. serializationGeometries.torusKnots.push(geometry.serialize());
  88242. }
  88243. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  88244. throw new Error("Unknown primitive type");
  88245. }
  88246. else {
  88247. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  88248. }
  88249. serializedGeometries[geometry.id] = true;
  88250. };
  88251. var serializeMesh = function (mesh, serializationScene) {
  88252. var serializationObject = {};
  88253. // Geometry
  88254. var geometry = mesh._geometry;
  88255. if (geometry) {
  88256. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  88257. // 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
  88258. serializeGeometry(geometry, serializationScene.geometries);
  88259. }
  88260. }
  88261. // Custom
  88262. if (mesh.serialize) {
  88263. mesh.serialize(serializationObject);
  88264. }
  88265. return serializationObject;
  88266. };
  88267. var finalizeSingleMesh = function (mesh, serializationObject) {
  88268. //only works if the mesh is already loaded
  88269. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  88270. //serialize material
  88271. if (mesh.material) {
  88272. if (mesh.material instanceof BABYLON.StandardMaterial) {
  88273. serializationObject.materials = serializationObject.materials || [];
  88274. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  88275. serializationObject.materials.push(mesh.material.serialize());
  88276. }
  88277. }
  88278. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  88279. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  88280. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  88281. serializationObject.multiMaterials.push(mesh.material.serialize());
  88282. }
  88283. }
  88284. }
  88285. //serialize geometry
  88286. var geometry = mesh._geometry;
  88287. if (geometry) {
  88288. if (!serializationObject.geometries) {
  88289. serializationObject.geometries = {};
  88290. serializationObject.geometries.boxes = [];
  88291. serializationObject.geometries.spheres = [];
  88292. serializationObject.geometries.cylinders = [];
  88293. serializationObject.geometries.toruses = [];
  88294. serializationObject.geometries.grounds = [];
  88295. serializationObject.geometries.planes = [];
  88296. serializationObject.geometries.torusKnots = [];
  88297. serializationObject.geometries.vertexData = [];
  88298. }
  88299. serializeGeometry(geometry, serializationObject.geometries);
  88300. }
  88301. // Skeletons
  88302. if (mesh.skeleton) {
  88303. serializationObject.skeletons = serializationObject.skeletons || [];
  88304. serializationObject.skeletons.push(mesh.skeleton.serialize());
  88305. }
  88306. //serialize the actual mesh
  88307. serializationObject.meshes = serializationObject.meshes || [];
  88308. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  88309. }
  88310. };
  88311. var SceneSerializer = /** @class */ (function () {
  88312. function SceneSerializer() {
  88313. }
  88314. SceneSerializer.ClearCache = function () {
  88315. serializedGeometries = [];
  88316. };
  88317. SceneSerializer.Serialize = function (scene) {
  88318. var serializationObject = {};
  88319. SceneSerializer.ClearCache();
  88320. // Scene
  88321. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  88322. serializationObject.autoClear = scene.autoClear;
  88323. serializationObject.clearColor = scene.clearColor.asArray();
  88324. serializationObject.ambientColor = scene.ambientColor.asArray();
  88325. serializationObject.gravity = scene.gravity.asArray();
  88326. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  88327. serializationObject.workerCollisions = scene.workerCollisions;
  88328. // Fog
  88329. if (scene.fogMode && scene.fogMode !== 0) {
  88330. serializationObject.fogMode = scene.fogMode;
  88331. serializationObject.fogColor = scene.fogColor.asArray();
  88332. serializationObject.fogStart = scene.fogStart;
  88333. serializationObject.fogEnd = scene.fogEnd;
  88334. serializationObject.fogDensity = scene.fogDensity;
  88335. }
  88336. //Physics
  88337. if (scene.isPhysicsEnabled()) {
  88338. var physicEngine = scene.getPhysicsEngine();
  88339. if (physicEngine) {
  88340. serializationObject.physicsEnabled = true;
  88341. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  88342. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  88343. }
  88344. }
  88345. // Metadata
  88346. if (scene.metadata) {
  88347. serializationObject.metadata = scene.metadata;
  88348. }
  88349. // Morph targets
  88350. serializationObject.morphTargetManagers = [];
  88351. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  88352. var abstractMesh = _a[_i];
  88353. var manager = abstractMesh.morphTargetManager;
  88354. if (manager) {
  88355. serializationObject.morphTargetManagers.push(manager.serialize());
  88356. }
  88357. }
  88358. // Lights
  88359. serializationObject.lights = [];
  88360. var index;
  88361. var light;
  88362. for (index = 0; index < scene.lights.length; index++) {
  88363. light = scene.lights[index];
  88364. if (!light.doNotSerialize) {
  88365. serializationObject.lights.push(light.serialize());
  88366. }
  88367. }
  88368. // Cameras
  88369. serializationObject.cameras = [];
  88370. for (index = 0; index < scene.cameras.length; index++) {
  88371. var camera = scene.cameras[index];
  88372. if (!camera.doNotSerialize) {
  88373. serializationObject.cameras.push(camera.serialize());
  88374. }
  88375. }
  88376. if (scene.activeCamera) {
  88377. serializationObject.activeCameraID = scene.activeCamera.id;
  88378. }
  88379. // Animations
  88380. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  88381. // Materials
  88382. serializationObject.materials = [];
  88383. serializationObject.multiMaterials = [];
  88384. var material;
  88385. for (index = 0; index < scene.materials.length; index++) {
  88386. material = scene.materials[index];
  88387. if (!material.doNotSerialize) {
  88388. serializationObject.materials.push(material.serialize());
  88389. }
  88390. }
  88391. // MultiMaterials
  88392. serializationObject.multiMaterials = [];
  88393. for (index = 0; index < scene.multiMaterials.length; index++) {
  88394. var multiMaterial = scene.multiMaterials[index];
  88395. serializationObject.multiMaterials.push(multiMaterial.serialize());
  88396. }
  88397. // Environment texture
  88398. if (scene.environmentTexture) {
  88399. serializationObject.environmentTexture = scene.environmentTexture.name;
  88400. }
  88401. // Skeletons
  88402. serializationObject.skeletons = [];
  88403. for (index = 0; index < scene.skeletons.length; index++) {
  88404. var skeleton = scene.skeletons[index];
  88405. if (!skeleton.doNotSerialize) {
  88406. serializationObject.skeletons.push(skeleton.serialize());
  88407. }
  88408. }
  88409. // Transform nodes
  88410. serializationObject.transformNodes = [];
  88411. for (index = 0; index < scene.transformNodes.length; index++) {
  88412. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  88413. }
  88414. // Geometries
  88415. serializationObject.geometries = {};
  88416. serializationObject.geometries.boxes = [];
  88417. serializationObject.geometries.spheres = [];
  88418. serializationObject.geometries.cylinders = [];
  88419. serializationObject.geometries.toruses = [];
  88420. serializationObject.geometries.grounds = [];
  88421. serializationObject.geometries.planes = [];
  88422. serializationObject.geometries.torusKnots = [];
  88423. serializationObject.geometries.vertexData = [];
  88424. serializedGeometries = [];
  88425. var geometries = scene.getGeometries();
  88426. for (index = 0; index < geometries.length; index++) {
  88427. var geometry = geometries[index];
  88428. if (geometry.isReady()) {
  88429. serializeGeometry(geometry, serializationObject.geometries);
  88430. }
  88431. }
  88432. // Meshes
  88433. serializationObject.meshes = [];
  88434. for (index = 0; index < scene.meshes.length; index++) {
  88435. var abstractMesh = scene.meshes[index];
  88436. if (abstractMesh instanceof BABYLON.Mesh) {
  88437. var mesh = abstractMesh;
  88438. if (!mesh.doNotSerialize) {
  88439. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  88440. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  88441. }
  88442. }
  88443. }
  88444. }
  88445. // Particles Systems
  88446. serializationObject.particleSystems = [];
  88447. for (index = 0; index < scene.particleSystems.length; index++) {
  88448. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  88449. }
  88450. // Lens flares
  88451. serializationObject.lensFlareSystems = [];
  88452. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  88453. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  88454. }
  88455. // Shadows
  88456. serializationObject.shadowGenerators = [];
  88457. for (index = 0; index < scene.lights.length; index++) {
  88458. light = scene.lights[index];
  88459. var shadowGenerator = light.getShadowGenerator();
  88460. if (shadowGenerator) {
  88461. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  88462. }
  88463. }
  88464. // Action Manager
  88465. if (scene.actionManager) {
  88466. serializationObject.actions = scene.actionManager.serialize("scene");
  88467. }
  88468. // Audio
  88469. serializationObject.sounds = [];
  88470. for (index = 0; index < scene.soundTracks.length; index++) {
  88471. var soundtrack = scene.soundTracks[index];
  88472. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  88473. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  88474. }
  88475. }
  88476. return serializationObject;
  88477. };
  88478. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  88479. if (withParents === void 0) { withParents = false; }
  88480. if (withChildren === void 0) { withChildren = false; }
  88481. var serializationObject = {};
  88482. SceneSerializer.ClearCache();
  88483. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  88484. if (withParents || withChildren) {
  88485. //deliberate for loop! not for each, appended should be processed as well.
  88486. for (var i = 0; i < toSerialize.length; ++i) {
  88487. if (withChildren) {
  88488. toSerialize[i].getDescendants().forEach(function (node) {
  88489. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  88490. toSerialize.push(node);
  88491. }
  88492. });
  88493. }
  88494. //make sure the array doesn't contain the object already
  88495. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  88496. toSerialize.push(toSerialize[i].parent);
  88497. }
  88498. }
  88499. }
  88500. toSerialize.forEach(function (mesh) {
  88501. finalizeSingleMesh(mesh, serializationObject);
  88502. });
  88503. return serializationObject;
  88504. };
  88505. return SceneSerializer;
  88506. }());
  88507. BABYLON.SceneSerializer = SceneSerializer;
  88508. })(BABYLON || (BABYLON = {}));
  88509. //# sourceMappingURL=babylon.sceneSerializer.js.map
  88510. "use strict";
  88511. var BABYLON;
  88512. (function (BABYLON) {
  88513. var ReflectionProbe = /** @class */ (function () {
  88514. function ReflectionProbe(name, size, scene, generateMipMaps) {
  88515. if (generateMipMaps === void 0) { generateMipMaps = true; }
  88516. var _this = this;
  88517. this.name = name;
  88518. this._viewMatrix = BABYLON.Matrix.Identity();
  88519. this._target = BABYLON.Vector3.Zero();
  88520. this._add = BABYLON.Vector3.Zero();
  88521. this._invertYAxis = false;
  88522. this.position = BABYLON.Vector3.Zero();
  88523. this._scene = scene;
  88524. this._scene.reflectionProbes.push(this);
  88525. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  88526. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  88527. switch (faceIndex) {
  88528. case 0:
  88529. _this._add.copyFromFloats(1, 0, 0);
  88530. break;
  88531. case 1:
  88532. _this._add.copyFromFloats(-1, 0, 0);
  88533. break;
  88534. case 2:
  88535. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  88536. break;
  88537. case 3:
  88538. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  88539. break;
  88540. case 4:
  88541. _this._add.copyFromFloats(0, 0, 1);
  88542. break;
  88543. case 5:
  88544. _this._add.copyFromFloats(0, 0, -1);
  88545. break;
  88546. }
  88547. if (_this._attachedMesh) {
  88548. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  88549. }
  88550. _this.position.addToRef(_this._add, _this._target);
  88551. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  88552. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  88553. scene._forcedViewPosition = _this.position;
  88554. });
  88555. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  88556. scene._forcedViewPosition = null;
  88557. scene.updateTransformMatrix(true);
  88558. });
  88559. if (scene.activeCamera) {
  88560. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  88561. }
  88562. }
  88563. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  88564. get: function () {
  88565. return this._renderTargetTexture.samples;
  88566. },
  88567. set: function (value) {
  88568. this._renderTargetTexture.samples = value;
  88569. },
  88570. enumerable: true,
  88571. configurable: true
  88572. });
  88573. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  88574. get: function () {
  88575. return this._renderTargetTexture.refreshRate;
  88576. },
  88577. set: function (value) {
  88578. this._renderTargetTexture.refreshRate = value;
  88579. },
  88580. enumerable: true,
  88581. configurable: true
  88582. });
  88583. ReflectionProbe.prototype.getScene = function () {
  88584. return this._scene;
  88585. };
  88586. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  88587. get: function () {
  88588. return this._renderTargetTexture;
  88589. },
  88590. enumerable: true,
  88591. configurable: true
  88592. });
  88593. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  88594. get: function () {
  88595. return this._renderTargetTexture.renderList;
  88596. },
  88597. enumerable: true,
  88598. configurable: true
  88599. });
  88600. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  88601. this._attachedMesh = mesh;
  88602. };
  88603. /**
  88604. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  88605. *
  88606. * @param renderingGroupId The rendering group id corresponding to its index
  88607. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  88608. */
  88609. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  88610. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  88611. };
  88612. ReflectionProbe.prototype.dispose = function () {
  88613. var index = this._scene.reflectionProbes.indexOf(this);
  88614. if (index !== -1) {
  88615. // Remove from the scene if found
  88616. this._scene.reflectionProbes.splice(index, 1);
  88617. }
  88618. if (this._renderTargetTexture) {
  88619. this._renderTargetTexture.dispose();
  88620. this._renderTargetTexture = null;
  88621. }
  88622. };
  88623. return ReflectionProbe;
  88624. }());
  88625. BABYLON.ReflectionProbe = ReflectionProbe;
  88626. })(BABYLON || (BABYLON = {}));
  88627. //# sourceMappingURL=babylon.reflectionProbe.js.map
  88628. "use strict";
  88629. var BABYLON;
  88630. (function (BABYLON) {
  88631. var Layer = /** @class */ (function () {
  88632. function Layer(name, imgUrl, scene, isBackground, color) {
  88633. this.name = name;
  88634. this.scale = new BABYLON.Vector2(1, 1);
  88635. this.offset = new BABYLON.Vector2(0, 0);
  88636. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  88637. this.layerMask = 0x0FFFFFFF;
  88638. this._vertexBuffers = {};
  88639. // Events
  88640. /**
  88641. * An event triggered when the layer is disposed.
  88642. * @type {BABYLON.Observable}
  88643. */
  88644. this.onDisposeObservable = new BABYLON.Observable();
  88645. /**
  88646. * An event triggered before rendering the scene
  88647. * @type {BABYLON.Observable}
  88648. */
  88649. this.onBeforeRenderObservable = new BABYLON.Observable();
  88650. /**
  88651. * An event triggered after rendering the scene
  88652. * @type {BABYLON.Observable}
  88653. */
  88654. this.onAfterRenderObservable = new BABYLON.Observable();
  88655. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  88656. this.isBackground = isBackground === undefined ? true : isBackground;
  88657. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  88658. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  88659. this._scene.layers.push(this);
  88660. var engine = this._scene.getEngine();
  88661. // VBO
  88662. var vertices = [];
  88663. vertices.push(1, 1);
  88664. vertices.push(-1, 1);
  88665. vertices.push(-1, -1);
  88666. vertices.push(1, -1);
  88667. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  88668. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  88669. this._createIndexBuffer();
  88670. // Effects
  88671. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  88672. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  88673. }
  88674. Object.defineProperty(Layer.prototype, "onDispose", {
  88675. set: function (callback) {
  88676. if (this._onDisposeObserver) {
  88677. this.onDisposeObservable.remove(this._onDisposeObserver);
  88678. }
  88679. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  88680. },
  88681. enumerable: true,
  88682. configurable: true
  88683. });
  88684. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  88685. set: function (callback) {
  88686. if (this._onBeforeRenderObserver) {
  88687. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  88688. }
  88689. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  88690. },
  88691. enumerable: true,
  88692. configurable: true
  88693. });
  88694. Object.defineProperty(Layer.prototype, "onAfterRender", {
  88695. set: function (callback) {
  88696. if (this._onAfterRenderObserver) {
  88697. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  88698. }
  88699. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  88700. },
  88701. enumerable: true,
  88702. configurable: true
  88703. });
  88704. Layer.prototype._createIndexBuffer = function () {
  88705. var engine = this._scene.getEngine();
  88706. // Indices
  88707. var indices = [];
  88708. indices.push(0);
  88709. indices.push(1);
  88710. indices.push(2);
  88711. indices.push(0);
  88712. indices.push(2);
  88713. indices.push(3);
  88714. this._indexBuffer = engine.createIndexBuffer(indices);
  88715. };
  88716. Layer.prototype._rebuild = function () {
  88717. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88718. if (vb) {
  88719. vb._rebuild();
  88720. }
  88721. this._createIndexBuffer();
  88722. };
  88723. Layer.prototype.render = function () {
  88724. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  88725. // Check
  88726. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  88727. return;
  88728. var engine = this._scene.getEngine();
  88729. this.onBeforeRenderObservable.notifyObservers(this);
  88730. // Render
  88731. engine.enableEffect(currentEffect);
  88732. engine.setState(false);
  88733. // Texture
  88734. currentEffect.setTexture("textureSampler", this.texture);
  88735. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  88736. // Color
  88737. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  88738. // Scale / offset
  88739. currentEffect.setVector2("offset", this.offset);
  88740. currentEffect.setVector2("scale", this.scale);
  88741. // VBOs
  88742. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  88743. // Draw order
  88744. if (!this.alphaTest) {
  88745. engine.setAlphaMode(this.alphaBlendingMode);
  88746. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  88747. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  88748. }
  88749. else {
  88750. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  88751. }
  88752. this.onAfterRenderObservable.notifyObservers(this);
  88753. };
  88754. Layer.prototype.dispose = function () {
  88755. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88756. if (vertexBuffer) {
  88757. vertexBuffer.dispose();
  88758. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  88759. }
  88760. if (this._indexBuffer) {
  88761. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  88762. this._indexBuffer = null;
  88763. }
  88764. if (this.texture) {
  88765. this.texture.dispose();
  88766. this.texture = null;
  88767. }
  88768. // Remove from scene
  88769. var index = this._scene.layers.indexOf(this);
  88770. this._scene.layers.splice(index, 1);
  88771. // Callback
  88772. this.onDisposeObservable.notifyObservers(this);
  88773. this.onDisposeObservable.clear();
  88774. this.onAfterRenderObservable.clear();
  88775. this.onBeforeRenderObservable.clear();
  88776. };
  88777. return Layer;
  88778. }());
  88779. BABYLON.Layer = Layer;
  88780. })(BABYLON || (BABYLON = {}));
  88781. //# sourceMappingURL=babylon.layer.js.map
  88782. "use strict";
  88783. var BABYLON;
  88784. (function (BABYLON) {
  88785. var TextureTools = /** @class */ (function () {
  88786. function TextureTools() {
  88787. }
  88788. /**
  88789. * Uses the GPU to create a copy texture rescaled at a given size
  88790. * @param texture Texture to copy from
  88791. * @param width Desired width
  88792. * @param height Desired height
  88793. * @return Generated texture
  88794. */
  88795. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  88796. if (useBilinearMode === void 0) { useBilinearMode = true; }
  88797. var scene = texture.getScene();
  88798. var engine = scene.getEngine();
  88799. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  88800. rtt.wrapU = texture.wrapU;
  88801. rtt.wrapV = texture.wrapV;
  88802. rtt.uOffset = texture.uOffset;
  88803. rtt.vOffset = texture.vOffset;
  88804. rtt.uScale = texture.uScale;
  88805. rtt.vScale = texture.vScale;
  88806. rtt.uAng = texture.uAng;
  88807. rtt.vAng = texture.vAng;
  88808. rtt.wAng = texture.wAng;
  88809. rtt.coordinatesIndex = texture.coordinatesIndex;
  88810. rtt.level = texture.level;
  88811. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  88812. rtt._texture.isReady = false;
  88813. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88814. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88815. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  88816. passPostProcess.getEffect().executeWhenCompiled(function () {
  88817. passPostProcess.onApply = function (effect) {
  88818. effect.setTexture("textureSampler", texture);
  88819. };
  88820. var internalTexture = rtt.getInternalTexture();
  88821. if (internalTexture) {
  88822. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  88823. engine.unBindFramebuffer(internalTexture);
  88824. rtt.disposeFramebufferObjects();
  88825. passPostProcess.dispose();
  88826. internalTexture.isReady = true;
  88827. }
  88828. });
  88829. return rtt;
  88830. };
  88831. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  88832. if (!scene._environmentBRDFTexture) {
  88833. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  88834. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88835. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88836. scene._environmentBRDFTexture = texture;
  88837. }
  88838. return scene._environmentBRDFTexture;
  88839. };
  88840. 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=";
  88841. return TextureTools;
  88842. }());
  88843. BABYLON.TextureTools = TextureTools;
  88844. })(BABYLON || (BABYLON = {}));
  88845. //# sourceMappingURL=babylon.textureTools.js.map
  88846. "use strict";
  88847. var BABYLON;
  88848. (function (BABYLON) {
  88849. var FramingBehavior = /** @class */ (function () {
  88850. function FramingBehavior() {
  88851. this._mode = FramingBehavior.FitFrustumSidesMode;
  88852. this._radiusScale = 1.0;
  88853. this._positionScale = 0.5;
  88854. this._defaultElevation = 0.3;
  88855. this._elevationReturnTime = 1500;
  88856. this._elevationReturnWaitTime = 1000;
  88857. this._zoomStopsAnimation = false;
  88858. this._framingTime = 1500;
  88859. this._isPointerDown = false;
  88860. this._lastInteractionTime = -Infinity;
  88861. // Framing control
  88862. this._animatables = new Array();
  88863. this._betaIsAnimating = false;
  88864. }
  88865. Object.defineProperty(FramingBehavior.prototype, "name", {
  88866. get: function () {
  88867. return "Framing";
  88868. },
  88869. enumerable: true,
  88870. configurable: true
  88871. });
  88872. Object.defineProperty(FramingBehavior.prototype, "mode", {
  88873. /**
  88874. * Gets current mode used by the behavior.
  88875. */
  88876. get: function () {
  88877. return this._mode;
  88878. },
  88879. /**
  88880. * Sets the current mode used by the behavior
  88881. */
  88882. set: function (mode) {
  88883. this._mode = mode;
  88884. },
  88885. enumerable: true,
  88886. configurable: true
  88887. });
  88888. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  88889. /**
  88890. * Gets the scale applied to the radius
  88891. */
  88892. get: function () {
  88893. return this._radiusScale;
  88894. },
  88895. /**
  88896. * Sets the scale applied to the radius (1 by default)
  88897. */
  88898. set: function (radius) {
  88899. this._radiusScale = radius;
  88900. },
  88901. enumerable: true,
  88902. configurable: true
  88903. });
  88904. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  88905. /**
  88906. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  88907. */
  88908. get: function () {
  88909. return this._positionScale;
  88910. },
  88911. /**
  88912. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  88913. */
  88914. set: function (scale) {
  88915. this._positionScale = scale;
  88916. },
  88917. enumerable: true,
  88918. configurable: true
  88919. });
  88920. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  88921. /**
  88922. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  88923. * behaviour is triggered, in radians.
  88924. */
  88925. get: function () {
  88926. return this._defaultElevation;
  88927. },
  88928. /**
  88929. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  88930. * behaviour is triggered, in radians.
  88931. */
  88932. set: function (elevation) {
  88933. this._defaultElevation = elevation;
  88934. },
  88935. enumerable: true,
  88936. configurable: true
  88937. });
  88938. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  88939. /**
  88940. * Gets the time (in milliseconds) taken to return to the default beta position.
  88941. * Negative value indicates camera should not return to default.
  88942. */
  88943. get: function () {
  88944. return this._elevationReturnTime;
  88945. },
  88946. /**
  88947. * Sets the time (in milliseconds) taken to return to the default beta position.
  88948. * Negative value indicates camera should not return to default.
  88949. */
  88950. set: function (speed) {
  88951. this._elevationReturnTime = speed;
  88952. },
  88953. enumerable: true,
  88954. configurable: true
  88955. });
  88956. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  88957. /**
  88958. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  88959. */
  88960. get: function () {
  88961. return this._elevationReturnWaitTime;
  88962. },
  88963. /**
  88964. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  88965. */
  88966. set: function (time) {
  88967. this._elevationReturnWaitTime = time;
  88968. },
  88969. enumerable: true,
  88970. configurable: true
  88971. });
  88972. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  88973. /**
  88974. * Gets the flag that indicates if user zooming should stop animation.
  88975. */
  88976. get: function () {
  88977. return this._zoomStopsAnimation;
  88978. },
  88979. /**
  88980. * Sets the flag that indicates if user zooming should stop animation.
  88981. */
  88982. set: function (flag) {
  88983. this._zoomStopsAnimation = flag;
  88984. },
  88985. enumerable: true,
  88986. configurable: true
  88987. });
  88988. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  88989. /**
  88990. * Gets the transition time when framing the mesh, in milliseconds
  88991. */
  88992. get: function () {
  88993. return this._framingTime;
  88994. },
  88995. /**
  88996. * Sets the transition time when framing the mesh, in milliseconds
  88997. */
  88998. set: function (time) {
  88999. this._framingTime = time;
  89000. },
  89001. enumerable: true,
  89002. configurable: true
  89003. });
  89004. FramingBehavior.prototype.init = function () {
  89005. // Do notihng
  89006. };
  89007. FramingBehavior.prototype.attach = function (camera) {
  89008. var _this = this;
  89009. this._attachedCamera = camera;
  89010. var scene = this._attachedCamera.getScene();
  89011. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  89012. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  89013. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  89014. _this._isPointerDown = true;
  89015. return;
  89016. }
  89017. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  89018. _this._isPointerDown = false;
  89019. }
  89020. });
  89021. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  89022. if (mesh) {
  89023. _this.zoomOnMesh(mesh);
  89024. }
  89025. });
  89026. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89027. // Stop the animation if there is user interaction and the animation should stop for this interaction
  89028. _this._applyUserInteraction();
  89029. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  89030. // back to the default position after a given timeout
  89031. _this._maintainCameraAboveGround();
  89032. });
  89033. };
  89034. FramingBehavior.prototype.detach = function () {
  89035. if (!this._attachedCamera) {
  89036. return;
  89037. }
  89038. var scene = this._attachedCamera.getScene();
  89039. if (this._onPrePointerObservableObserver) {
  89040. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  89041. }
  89042. if (this._onAfterCheckInputsObserver) {
  89043. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89044. }
  89045. if (this._onMeshTargetChangedObserver) {
  89046. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89047. }
  89048. this._attachedCamera = null;
  89049. };
  89050. /**
  89051. * Targets the given mesh and updates zoom level accordingly.
  89052. * @param mesh The mesh to target.
  89053. * @param radius Optional. If a cached radius position already exists, overrides default.
  89054. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89055. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89056. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89057. */
  89058. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  89059. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89060. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89061. mesh.computeWorldMatrix(true);
  89062. var boundingBox = mesh.getBoundingInfo().boundingBox;
  89063. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  89064. };
  89065. /**
  89066. * Targets the given mesh with its children and updates zoom level accordingly.
  89067. * @param mesh The mesh to target.
  89068. * @param radius Optional. If a cached radius position already exists, overrides default.
  89069. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89070. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89071. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89072. */
  89073. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  89074. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89075. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89076. mesh.computeWorldMatrix(true);
  89077. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  89078. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  89079. };
  89080. /**
  89081. * Targets the given meshes with their children and updates zoom level accordingly.
  89082. * @param meshes The mesh to target.
  89083. * @param radius Optional. If a cached radius position already exists, overrides default.
  89084. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89085. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89086. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89087. */
  89088. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  89089. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89090. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89091. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  89092. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  89093. for (var i = 0; i < meshes.length; i++) {
  89094. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  89095. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  89096. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  89097. }
  89098. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  89099. };
  89100. /**
  89101. * Targets the given mesh and updates zoom level accordingly.
  89102. * @param mesh The mesh to target.
  89103. * @param radius Optional. If a cached radius position already exists, overrides default.
  89104. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89105. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89106. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89107. */
  89108. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  89109. var _this = this;
  89110. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89111. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89112. var zoomTarget;
  89113. if (!this._attachedCamera) {
  89114. return;
  89115. }
  89116. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  89117. var bottom = minimumWorld.y;
  89118. var top = maximumWorld.y;
  89119. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  89120. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  89121. if (focusOnOriginXZ) {
  89122. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  89123. }
  89124. else {
  89125. var centerWorld = minimumWorld.add(radiusWorld);
  89126. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  89127. }
  89128. if (!this._vectorTransition) {
  89129. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  89130. }
  89131. this._betaIsAnimating = true;
  89132. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  89133. if (animatable) {
  89134. this._animatables.push(animatable);
  89135. }
  89136. // sets the radius and lower radius bounds
  89137. // Small delta ensures camera is not always at lower zoom limit.
  89138. var radius = 0;
  89139. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  89140. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  89141. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  89142. radius = position;
  89143. }
  89144. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  89145. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  89146. if (this._attachedCamera.lowerRadiusLimit === null) {
  89147. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  89148. }
  89149. }
  89150. // Set sensibilities
  89151. var extend = maximumWorld.subtract(minimumWorld).length();
  89152. this._attachedCamera.panningSensibility = 5000 / extend;
  89153. this._attachedCamera.wheelPrecision = 100 / radius;
  89154. // transition to new radius
  89155. if (!this._radiusTransition) {
  89156. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  89157. }
  89158. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  89159. _this.stopAllAnimations();
  89160. if (onAnimationEnd) {
  89161. onAnimationEnd();
  89162. }
  89163. if (_this._attachedCamera) {
  89164. _this._attachedCamera.storeState();
  89165. }
  89166. });
  89167. if (animatable) {
  89168. this._animatables.push(animatable);
  89169. }
  89170. };
  89171. /**
  89172. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  89173. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  89174. * frustum width.
  89175. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  89176. * to fully enclose the mesh in the viewing frustum.
  89177. */
  89178. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  89179. var size = maximumWorld.subtract(minimumWorld);
  89180. var boxVectorGlobalDiagonal = size.length();
  89181. var frustumSlope = this._getFrustumSlope();
  89182. // Formula for setting distance
  89183. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  89184. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  89185. // Horizon distance
  89186. var radius = radiusWithoutFraming * this._radiusScale;
  89187. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  89188. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  89189. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  89190. var camera = this._attachedCamera;
  89191. if (!camera) {
  89192. return 0;
  89193. }
  89194. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  89195. // Don't exceed the requested limit
  89196. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  89197. }
  89198. // Don't exceed the upper radius limit
  89199. if (camera.upperRadiusLimit) {
  89200. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  89201. }
  89202. return distance;
  89203. };
  89204. /**
  89205. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  89206. * is automatically returned to its default position (expected to be above ground plane).
  89207. */
  89208. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  89209. var _this = this;
  89210. if (this._elevationReturnTime < 0) {
  89211. return;
  89212. }
  89213. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  89214. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  89215. var limitBeta = Math.PI * 0.5;
  89216. // Bring the camera back up if below the ground plane
  89217. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  89218. this._betaIsAnimating = true;
  89219. //Transition to new position
  89220. this.stopAllAnimations();
  89221. if (!this._betaTransition) {
  89222. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  89223. }
  89224. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  89225. _this._clearAnimationLocks();
  89226. _this.stopAllAnimations();
  89227. });
  89228. if (animatabe) {
  89229. this._animatables.push(animatabe);
  89230. }
  89231. }
  89232. };
  89233. /**
  89234. * Returns the frustum slope based on the canvas ratio and camera FOV
  89235. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  89236. */
  89237. FramingBehavior.prototype._getFrustumSlope = function () {
  89238. // Calculate the viewport ratio
  89239. // Aspect Ratio is Height/Width.
  89240. var camera = this._attachedCamera;
  89241. if (!camera) {
  89242. return BABYLON.Vector2.Zero();
  89243. }
  89244. var engine = camera.getScene().getEngine();
  89245. var aspectRatio = engine.getAspectRatio(camera);
  89246. // Camera FOV is the vertical field of view (top-bottom) in radians.
  89247. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  89248. var frustumSlopeY = Math.tan(camera.fov / 2);
  89249. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  89250. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  89251. // along the forward vector.
  89252. var frustumSlopeX = frustumSlopeY * aspectRatio;
  89253. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  89254. };
  89255. /**
  89256. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  89257. */
  89258. FramingBehavior.prototype._clearAnimationLocks = function () {
  89259. this._betaIsAnimating = false;
  89260. };
  89261. /**
  89262. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  89263. */
  89264. FramingBehavior.prototype._applyUserInteraction = function () {
  89265. if (this.isUserIsMoving) {
  89266. this._lastInteractionTime = BABYLON.Tools.Now;
  89267. this.stopAllAnimations();
  89268. this._clearAnimationLocks();
  89269. }
  89270. };
  89271. /**
  89272. * Stops and removes all animations that have been applied to the camera
  89273. */
  89274. FramingBehavior.prototype.stopAllAnimations = function () {
  89275. if (this._attachedCamera) {
  89276. this._attachedCamera.animations = [];
  89277. }
  89278. while (this._animatables.length) {
  89279. if (this._animatables[0]) {
  89280. this._animatables[0].onAnimationEnd = null;
  89281. this._animatables[0].stop();
  89282. }
  89283. this._animatables.shift();
  89284. }
  89285. };
  89286. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  89287. /**
  89288. * Gets a value indicating if the user is moving the camera
  89289. */
  89290. get: function () {
  89291. if (!this._attachedCamera) {
  89292. return false;
  89293. }
  89294. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  89295. this._attachedCamera.inertialBetaOffset !== 0 ||
  89296. this._attachedCamera.inertialRadiusOffset !== 0 ||
  89297. this._attachedCamera.inertialPanningX !== 0 ||
  89298. this._attachedCamera.inertialPanningY !== 0 ||
  89299. this._isPointerDown;
  89300. },
  89301. enumerable: true,
  89302. configurable: true
  89303. });
  89304. /**
  89305. * The easing function used by animations
  89306. */
  89307. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  89308. /**
  89309. * The easing mode used by animations
  89310. */
  89311. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  89312. // Statics
  89313. /**
  89314. * The camera can move all the way towards the mesh.
  89315. */
  89316. FramingBehavior.IgnoreBoundsSizeMode = 0;
  89317. /**
  89318. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  89319. */
  89320. FramingBehavior.FitFrustumSidesMode = 1;
  89321. return FramingBehavior;
  89322. }());
  89323. BABYLON.FramingBehavior = FramingBehavior;
  89324. })(BABYLON || (BABYLON = {}));
  89325. //# sourceMappingURL=babylon.framingBehavior.js.map
  89326. "use strict";
  89327. var BABYLON;
  89328. (function (BABYLON) {
  89329. /**
  89330. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  89331. */
  89332. var BouncingBehavior = /** @class */ (function () {
  89333. function BouncingBehavior() {
  89334. /**
  89335. * The duration of the animation, in milliseconds
  89336. */
  89337. this.transitionDuration = 450;
  89338. /**
  89339. * Length of the distance animated by the transition when lower radius is reached
  89340. */
  89341. this.lowerRadiusTransitionRange = 2;
  89342. /**
  89343. * Length of the distance animated by the transition when upper radius is reached
  89344. */
  89345. this.upperRadiusTransitionRange = -2;
  89346. this._autoTransitionRange = false;
  89347. // Animations
  89348. this._radiusIsAnimating = false;
  89349. this._radiusBounceTransition = null;
  89350. this._animatables = new Array();
  89351. }
  89352. Object.defineProperty(BouncingBehavior.prototype, "name", {
  89353. get: function () {
  89354. return "Bouncing";
  89355. },
  89356. enumerable: true,
  89357. configurable: true
  89358. });
  89359. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  89360. /**
  89361. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  89362. */
  89363. get: function () {
  89364. return this._autoTransitionRange;
  89365. },
  89366. /**
  89367. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  89368. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  89369. */
  89370. set: function (value) {
  89371. var _this = this;
  89372. if (this._autoTransitionRange === value) {
  89373. return;
  89374. }
  89375. this._autoTransitionRange = value;
  89376. var camera = this._attachedCamera;
  89377. if (!camera) {
  89378. return;
  89379. }
  89380. if (value) {
  89381. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  89382. if (!mesh) {
  89383. return;
  89384. }
  89385. mesh.computeWorldMatrix(true);
  89386. var diagonal = mesh.getBoundingInfo().diagonalLength;
  89387. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  89388. _this.upperRadiusTransitionRange = diagonal * 0.05;
  89389. });
  89390. }
  89391. else if (this._onMeshTargetChangedObserver) {
  89392. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89393. }
  89394. },
  89395. enumerable: true,
  89396. configurable: true
  89397. });
  89398. BouncingBehavior.prototype.init = function () {
  89399. // Do notihng
  89400. };
  89401. BouncingBehavior.prototype.attach = function (camera) {
  89402. var _this = this;
  89403. this._attachedCamera = camera;
  89404. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89405. if (!_this._attachedCamera) {
  89406. return;
  89407. }
  89408. // Add the bounce animation to the lower radius limit
  89409. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  89410. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  89411. }
  89412. // Add the bounce animation to the upper radius limit
  89413. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  89414. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  89415. }
  89416. });
  89417. };
  89418. BouncingBehavior.prototype.detach = function () {
  89419. if (!this._attachedCamera) {
  89420. return;
  89421. }
  89422. if (this._onAfterCheckInputsObserver) {
  89423. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89424. }
  89425. if (this._onMeshTargetChangedObserver) {
  89426. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89427. }
  89428. this._attachedCamera = null;
  89429. };
  89430. /**
  89431. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  89432. * @param radiusLimit The limit to check against.
  89433. * @return Bool to indicate if at limit.
  89434. */
  89435. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  89436. if (!this._attachedCamera) {
  89437. return false;
  89438. }
  89439. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  89440. return true;
  89441. }
  89442. return false;
  89443. };
  89444. /**
  89445. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  89446. * @param radiusDelta The delta by which to animate to. Can be negative.
  89447. */
  89448. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  89449. var _this = this;
  89450. if (!this._attachedCamera) {
  89451. return;
  89452. }
  89453. if (!this._radiusBounceTransition) {
  89454. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  89455. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  89456. }
  89457. // Prevent zoom until bounce has completed
  89458. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  89459. this._attachedCamera.wheelPrecision = Infinity;
  89460. this._attachedCamera.inertialRadiusOffset = 0;
  89461. // Animate to the radius limit
  89462. this.stopAllAnimations();
  89463. this._radiusIsAnimating = true;
  89464. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  89465. if (animatable) {
  89466. this._animatables.push(animatable);
  89467. }
  89468. };
  89469. /**
  89470. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  89471. */
  89472. BouncingBehavior.prototype._clearAnimationLocks = function () {
  89473. this._radiusIsAnimating = false;
  89474. if (this._attachedCamera) {
  89475. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  89476. }
  89477. };
  89478. /**
  89479. * Stops and removes all animations that have been applied to the camera
  89480. */
  89481. BouncingBehavior.prototype.stopAllAnimations = function () {
  89482. if (this._attachedCamera) {
  89483. this._attachedCamera.animations = [];
  89484. }
  89485. while (this._animatables.length) {
  89486. this._animatables[0].onAnimationEnd = null;
  89487. this._animatables[0].stop();
  89488. this._animatables.shift();
  89489. }
  89490. };
  89491. /**
  89492. * The easing function used by animations
  89493. */
  89494. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  89495. /**
  89496. * The easing mode used by animations
  89497. */
  89498. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  89499. return BouncingBehavior;
  89500. }());
  89501. BABYLON.BouncingBehavior = BouncingBehavior;
  89502. })(BABYLON || (BABYLON = {}));
  89503. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  89504. "use strict";
  89505. var BABYLON;
  89506. (function (BABYLON) {
  89507. var AutoRotationBehavior = /** @class */ (function () {
  89508. function AutoRotationBehavior() {
  89509. this._zoomStopsAnimation = false;
  89510. this._idleRotationSpeed = 0.05;
  89511. this._idleRotationWaitTime = 2000;
  89512. this._idleRotationSpinupTime = 2000;
  89513. this._isPointerDown = false;
  89514. this._lastFrameTime = null;
  89515. this._lastInteractionTime = -Infinity;
  89516. this._cameraRotationSpeed = 0;
  89517. this._lastFrameRadius = 0;
  89518. }
  89519. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  89520. get: function () {
  89521. return "AutoRotation";
  89522. },
  89523. enumerable: true,
  89524. configurable: true
  89525. });
  89526. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  89527. /**
  89528. * Gets the flag that indicates if user zooming should stop animation.
  89529. */
  89530. get: function () {
  89531. return this._zoomStopsAnimation;
  89532. },
  89533. /**
  89534. * Sets the flag that indicates if user zooming should stop animation.
  89535. */
  89536. set: function (flag) {
  89537. this._zoomStopsAnimation = flag;
  89538. },
  89539. enumerable: true,
  89540. configurable: true
  89541. });
  89542. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  89543. /**
  89544. * Gets the default speed at which the camera rotates around the model.
  89545. */
  89546. get: function () {
  89547. return this._idleRotationSpeed;
  89548. },
  89549. /**
  89550. * Sets the default speed at which the camera rotates around the model.
  89551. */
  89552. set: function (speed) {
  89553. this._idleRotationSpeed = speed;
  89554. },
  89555. enumerable: true,
  89556. configurable: true
  89557. });
  89558. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  89559. /**
  89560. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  89561. */
  89562. get: function () {
  89563. return this._idleRotationWaitTime;
  89564. },
  89565. /**
  89566. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  89567. */
  89568. set: function (time) {
  89569. this._idleRotationWaitTime = time;
  89570. },
  89571. enumerable: true,
  89572. configurable: true
  89573. });
  89574. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  89575. /**
  89576. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  89577. */
  89578. get: function () {
  89579. return this._idleRotationSpinupTime;
  89580. },
  89581. /**
  89582. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  89583. */
  89584. set: function (time) {
  89585. this._idleRotationSpinupTime = time;
  89586. },
  89587. enumerable: true,
  89588. configurable: true
  89589. });
  89590. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  89591. /**
  89592. * Gets a value indicating if the camera is currently rotating because of this behavior
  89593. */
  89594. get: function () {
  89595. return Math.abs(this._cameraRotationSpeed) > 0;
  89596. },
  89597. enumerable: true,
  89598. configurable: true
  89599. });
  89600. AutoRotationBehavior.prototype.init = function () {
  89601. // Do notihng
  89602. };
  89603. AutoRotationBehavior.prototype.attach = function (camera) {
  89604. var _this = this;
  89605. this._attachedCamera = camera;
  89606. var scene = this._attachedCamera.getScene();
  89607. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  89608. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  89609. _this._isPointerDown = true;
  89610. return;
  89611. }
  89612. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  89613. _this._isPointerDown = false;
  89614. }
  89615. });
  89616. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89617. var now = BABYLON.Tools.Now;
  89618. var dt = 0;
  89619. if (_this._lastFrameTime != null) {
  89620. dt = now - _this._lastFrameTime;
  89621. }
  89622. _this._lastFrameTime = now;
  89623. // Stop the animation if there is user interaction and the animation should stop for this interaction
  89624. _this._applyUserInteraction();
  89625. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  89626. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  89627. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  89628. // Step camera rotation by rotation speed
  89629. if (_this._attachedCamera) {
  89630. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  89631. }
  89632. });
  89633. };
  89634. AutoRotationBehavior.prototype.detach = function () {
  89635. if (!this._attachedCamera) {
  89636. return;
  89637. }
  89638. var scene = this._attachedCamera.getScene();
  89639. if (this._onPrePointerObservableObserver) {
  89640. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  89641. }
  89642. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89643. this._attachedCamera = null;
  89644. };
  89645. /**
  89646. * Returns true if user is scrolling.
  89647. * @return true if user is scrolling.
  89648. */
  89649. AutoRotationBehavior.prototype._userIsZooming = function () {
  89650. if (!this._attachedCamera) {
  89651. return false;
  89652. }
  89653. return this._attachedCamera.inertialRadiusOffset !== 0;
  89654. };
  89655. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  89656. if (!this._attachedCamera) {
  89657. return false;
  89658. }
  89659. var zoomHasHitLimit = false;
  89660. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  89661. zoomHasHitLimit = true;
  89662. }
  89663. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  89664. this._lastFrameRadius = this._attachedCamera.radius;
  89665. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  89666. };
  89667. /**
  89668. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  89669. */
  89670. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  89671. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  89672. this._lastInteractionTime = BABYLON.Tools.Now;
  89673. }
  89674. };
  89675. // Tools
  89676. AutoRotationBehavior.prototype._userIsMoving = function () {
  89677. if (!this._attachedCamera) {
  89678. return false;
  89679. }
  89680. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  89681. this._attachedCamera.inertialBetaOffset !== 0 ||
  89682. this._attachedCamera.inertialRadiusOffset !== 0 ||
  89683. this._attachedCamera.inertialPanningX !== 0 ||
  89684. this._attachedCamera.inertialPanningY !== 0 ||
  89685. this._isPointerDown;
  89686. };
  89687. return AutoRotationBehavior;
  89688. }());
  89689. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  89690. })(BABYLON || (BABYLON = {}));
  89691. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  89692. "use strict";
  89693. var BABYLON;
  89694. (function (BABYLON) {
  89695. var NullEngineOptions = /** @class */ (function () {
  89696. function NullEngineOptions() {
  89697. this.renderWidth = 512;
  89698. this.renderHeight = 256;
  89699. this.textureSize = 512;
  89700. this.deterministicLockstep = false;
  89701. this.lockstepMaxSteps = 4;
  89702. }
  89703. return NullEngineOptions;
  89704. }());
  89705. BABYLON.NullEngineOptions = NullEngineOptions;
  89706. /**
  89707. * The null engine class provides support for headless version of babylon.js.
  89708. * This can be used in server side scenario or for testing purposes
  89709. */
  89710. var NullEngine = /** @class */ (function (_super) {
  89711. __extends(NullEngine, _super);
  89712. function NullEngine(options) {
  89713. if (options === void 0) { options = new NullEngineOptions(); }
  89714. var _this = _super.call(this, null) || this;
  89715. if (options.deterministicLockstep === undefined) {
  89716. options.deterministicLockstep = false;
  89717. }
  89718. if (options.lockstepMaxSteps === undefined) {
  89719. options.lockstepMaxSteps = 4;
  89720. }
  89721. _this._options = options;
  89722. // Init caps
  89723. // We consider we are on a webgl1 capable device
  89724. _this._caps = new BABYLON.EngineCapabilities();
  89725. _this._caps.maxTexturesImageUnits = 16;
  89726. _this._caps.maxVertexTextureImageUnits = 16;
  89727. _this._caps.maxTextureSize = 512;
  89728. _this._caps.maxCubemapTextureSize = 512;
  89729. _this._caps.maxRenderTextureSize = 512;
  89730. _this._caps.maxVertexAttribs = 16;
  89731. _this._caps.maxVaryingVectors = 16;
  89732. _this._caps.maxFragmentUniformVectors = 16;
  89733. _this._caps.maxVertexUniformVectors = 16;
  89734. // Extensions
  89735. _this._caps.standardDerivatives = false;
  89736. _this._caps.astc = null;
  89737. _this._caps.s3tc = null;
  89738. _this._caps.pvrtc = null;
  89739. _this._caps.etc1 = null;
  89740. _this._caps.etc2 = null;
  89741. _this._caps.textureAnisotropicFilterExtension = null;
  89742. _this._caps.maxAnisotropy = 0;
  89743. _this._caps.uintIndices = false;
  89744. _this._caps.fragmentDepthSupported = false;
  89745. _this._caps.highPrecisionShaderSupported = true;
  89746. _this._caps.colorBufferFloat = false;
  89747. _this._caps.textureFloat = false;
  89748. _this._caps.textureFloatLinearFiltering = false;
  89749. _this._caps.textureFloatRender = false;
  89750. _this._caps.textureHalfFloat = false;
  89751. _this._caps.textureHalfFloatLinearFiltering = false;
  89752. _this._caps.textureHalfFloatRender = false;
  89753. _this._caps.textureLOD = false;
  89754. _this._caps.drawBuffersExtension = false;
  89755. _this._caps.depthTextureExtension = false;
  89756. _this._caps.vertexArrayObject = false;
  89757. _this._caps.instancedArrays = false;
  89758. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  89759. // Wrappers
  89760. if (typeof URL === "undefined") {
  89761. URL = {
  89762. createObjectURL: function () { },
  89763. revokeObjectURL: function () { }
  89764. };
  89765. }
  89766. if (typeof Blob === "undefined") {
  89767. Blob = function () { };
  89768. }
  89769. return _this;
  89770. }
  89771. NullEngine.prototype.isDeterministicLockStep = function () {
  89772. return this._options.deterministicLockstep;
  89773. };
  89774. NullEngine.prototype.getLockstepMaxSteps = function () {
  89775. return this._options.lockstepMaxSteps;
  89776. };
  89777. NullEngine.prototype.getHardwareScalingLevel = function () {
  89778. return 1.0;
  89779. };
  89780. NullEngine.prototype.createVertexBuffer = function (vertices) {
  89781. return {
  89782. capacity: 0,
  89783. references: 1,
  89784. is32Bits: false
  89785. };
  89786. };
  89787. NullEngine.prototype.createIndexBuffer = function (indices) {
  89788. return {
  89789. capacity: 0,
  89790. references: 1,
  89791. is32Bits: false
  89792. };
  89793. };
  89794. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  89795. if (stencil === void 0) { stencil = false; }
  89796. };
  89797. NullEngine.prototype.getRenderWidth = function (useScreen) {
  89798. if (useScreen === void 0) { useScreen = false; }
  89799. if (!useScreen && this._currentRenderTarget) {
  89800. return this._currentRenderTarget.width;
  89801. }
  89802. return this._options.renderWidth;
  89803. };
  89804. NullEngine.prototype.getRenderHeight = function (useScreen) {
  89805. if (useScreen === void 0) { useScreen = false; }
  89806. if (!useScreen && this._currentRenderTarget) {
  89807. return this._currentRenderTarget.height;
  89808. }
  89809. return this._options.renderHeight;
  89810. };
  89811. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  89812. this._cachedViewport = viewport;
  89813. };
  89814. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  89815. return {
  89816. transformFeedback: null,
  89817. __SPECTOR_rebuildProgram: null
  89818. };
  89819. };
  89820. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  89821. return [];
  89822. };
  89823. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  89824. return [];
  89825. };
  89826. NullEngine.prototype.bindSamplers = function (effect) {
  89827. this._currentEffect = null;
  89828. };
  89829. NullEngine.prototype.enableEffect = function (effect) {
  89830. this._currentEffect = effect;
  89831. if (effect.onBind) {
  89832. effect.onBind(effect);
  89833. }
  89834. effect.onBindObservable.notifyObservers(effect);
  89835. };
  89836. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  89837. if (zOffset === void 0) { zOffset = 0; }
  89838. if (reverseSide === void 0) { reverseSide = false; }
  89839. };
  89840. NullEngine.prototype.setIntArray = function (uniform, array) {
  89841. };
  89842. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  89843. };
  89844. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  89845. };
  89846. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  89847. };
  89848. NullEngine.prototype.setFloatArray = function (uniform, array) {
  89849. };
  89850. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  89851. };
  89852. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  89853. };
  89854. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  89855. };
  89856. NullEngine.prototype.setArray = function (uniform, array) {
  89857. };
  89858. NullEngine.prototype.setArray2 = function (uniform, array) {
  89859. };
  89860. NullEngine.prototype.setArray3 = function (uniform, array) {
  89861. };
  89862. NullEngine.prototype.setArray4 = function (uniform, array) {
  89863. };
  89864. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  89865. };
  89866. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  89867. };
  89868. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  89869. };
  89870. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  89871. };
  89872. NullEngine.prototype.setFloat = function (uniform, value) {
  89873. };
  89874. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  89875. };
  89876. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  89877. };
  89878. NullEngine.prototype.setBool = function (uniform, bool) {
  89879. };
  89880. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  89881. };
  89882. NullEngine.prototype.setColor3 = function (uniform, color3) {
  89883. };
  89884. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  89885. };
  89886. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  89887. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  89888. if (this._alphaMode === mode) {
  89889. return;
  89890. }
  89891. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  89892. if (!noDepthWriteChange) {
  89893. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  89894. }
  89895. this._alphaMode = mode;
  89896. };
  89897. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  89898. };
  89899. NullEngine.prototype.wipeCaches = function (bruteForce) {
  89900. if (this.preventCacheWipeBetweenFrames) {
  89901. return;
  89902. }
  89903. this.resetTextureCache();
  89904. this._currentEffect = null;
  89905. if (bruteForce) {
  89906. this._currentProgram = null;
  89907. this._stencilState.reset();
  89908. this._depthCullingState.reset();
  89909. this._alphaState.reset();
  89910. }
  89911. this._cachedVertexBuffers = null;
  89912. this._cachedIndexBuffer = null;
  89913. this._cachedEffectForVertexBuffers = null;
  89914. };
  89915. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  89916. };
  89917. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  89918. };
  89919. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  89920. };
  89921. NullEngine.prototype._createTexture = function () {
  89922. return {};
  89923. };
  89924. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  89925. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  89926. if (onLoad === void 0) { onLoad = null; }
  89927. if (onError === void 0) { onError = null; }
  89928. if (buffer === void 0) { buffer = null; }
  89929. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  89930. var url = String(urlArg);
  89931. texture.url = url;
  89932. texture.generateMipMaps = !noMipmap;
  89933. texture.samplingMode = samplingMode;
  89934. texture.invertY = invertY;
  89935. texture.baseWidth = this._options.textureSize;
  89936. texture.baseHeight = this._options.textureSize;
  89937. texture.width = this._options.textureSize;
  89938. texture.height = this._options.textureSize;
  89939. if (format) {
  89940. texture.format = format;
  89941. }
  89942. texture.isReady = true;
  89943. if (onLoad) {
  89944. onLoad();
  89945. }
  89946. return texture;
  89947. };
  89948. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  89949. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  89950. if (options !== undefined && typeof options === "object") {
  89951. fullOptions.generateMipMaps = options.generateMipMaps;
  89952. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  89953. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  89954. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  89955. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  89956. }
  89957. else {
  89958. fullOptions.generateMipMaps = options;
  89959. fullOptions.generateDepthBuffer = true;
  89960. fullOptions.generateStencilBuffer = false;
  89961. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89962. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  89963. }
  89964. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  89965. var width = size.width || size;
  89966. var height = size.height || size;
  89967. texture._depthStencilBuffer = {};
  89968. texture._framebuffer = {};
  89969. texture.baseWidth = width;
  89970. texture.baseHeight = height;
  89971. texture.width = width;
  89972. texture.height = height;
  89973. texture.isReady = true;
  89974. texture.samples = 1;
  89975. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  89976. texture.samplingMode = fullOptions.samplingMode;
  89977. texture.type = fullOptions.type;
  89978. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  89979. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  89980. return texture;
  89981. };
  89982. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  89983. texture.samplingMode = samplingMode;
  89984. };
  89985. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  89986. if (this._currentRenderTarget) {
  89987. this.unBindFramebuffer(this._currentRenderTarget);
  89988. }
  89989. this._currentRenderTarget = texture;
  89990. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  89991. if (this._cachedViewport && !forceFullscreenViewport) {
  89992. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  89993. }
  89994. };
  89995. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  89996. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  89997. this._currentRenderTarget = null;
  89998. if (onBeforeUnbind) {
  89999. if (texture._MSAAFramebuffer) {
  90000. this._currentFramebuffer = texture._framebuffer;
  90001. }
  90002. onBeforeUnbind();
  90003. }
  90004. this._currentFramebuffer = null;
  90005. };
  90006. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  90007. var vbo = {
  90008. capacity: 1,
  90009. references: 1,
  90010. is32Bits: false
  90011. };
  90012. return vbo;
  90013. };
  90014. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  90015. if (offset === void 0) { offset = 0; }
  90016. };
  90017. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  90018. };
  90019. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  90020. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  90021. this._boundTexturesCache[this._activeChannel] = texture;
  90022. }
  90023. };
  90024. NullEngine.prototype._bindTexture = function (channel, texture) {
  90025. if (channel < 0) {
  90026. return;
  90027. }
  90028. this._bindTextureDirectly(0, texture);
  90029. };
  90030. NullEngine.prototype._releaseBuffer = function (buffer) {
  90031. buffer.references--;
  90032. if (buffer.references === 0) {
  90033. return true;
  90034. }
  90035. return false;
  90036. };
  90037. return NullEngine;
  90038. }(BABYLON.Engine));
  90039. BABYLON.NullEngine = NullEngine;
  90040. })(BABYLON || (BABYLON = {}));
  90041. //# sourceMappingURL=babylon.nullEngine.js.map
  90042. "use strict";
  90043. var BABYLON;
  90044. (function (BABYLON) {
  90045. /**
  90046. * This class can be used to get instrumentation data from a Babylon engine
  90047. */
  90048. var EngineInstrumentation = /** @class */ (function () {
  90049. function EngineInstrumentation(engine) {
  90050. this.engine = engine;
  90051. this._captureGPUFrameTime = false;
  90052. this._gpuFrameTime = new BABYLON.PerfCounter();
  90053. this._captureShaderCompilationTime = false;
  90054. this._shaderCompilationTime = new BABYLON.PerfCounter();
  90055. // Observers
  90056. this._onBeginFrameObserver = null;
  90057. this._onEndFrameObserver = null;
  90058. this._onBeforeShaderCompilationObserver = null;
  90059. this._onAfterShaderCompilationObserver = null;
  90060. }
  90061. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  90062. // Properties
  90063. /**
  90064. * Gets the perf counter used for GPU frame time
  90065. */
  90066. get: function () {
  90067. return this._gpuFrameTime;
  90068. },
  90069. enumerable: true,
  90070. configurable: true
  90071. });
  90072. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  90073. /**
  90074. * Gets the GPU frame time capture status
  90075. */
  90076. get: function () {
  90077. return this._captureGPUFrameTime;
  90078. },
  90079. /**
  90080. * Enable or disable the GPU frame time capture
  90081. */
  90082. set: function (value) {
  90083. var _this = this;
  90084. if (value === this._captureGPUFrameTime) {
  90085. return;
  90086. }
  90087. this._captureGPUFrameTime = value;
  90088. if (value) {
  90089. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  90090. if (!_this._gpuFrameTimeToken) {
  90091. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  90092. }
  90093. });
  90094. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  90095. if (!_this._gpuFrameTimeToken) {
  90096. return;
  90097. }
  90098. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  90099. if (time > -1) {
  90100. _this._gpuFrameTimeToken = null;
  90101. _this._gpuFrameTime.fetchNewFrame();
  90102. _this._gpuFrameTime.addCount(time, true);
  90103. }
  90104. });
  90105. }
  90106. else {
  90107. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  90108. this._onBeginFrameObserver = null;
  90109. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  90110. this._onEndFrameObserver = null;
  90111. }
  90112. },
  90113. enumerable: true,
  90114. configurable: true
  90115. });
  90116. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  90117. /**
  90118. * Gets the perf counter used for shader compilation time
  90119. */
  90120. get: function () {
  90121. return this._shaderCompilationTime;
  90122. },
  90123. enumerable: true,
  90124. configurable: true
  90125. });
  90126. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  90127. /**
  90128. * Gets the shader compilation time capture status
  90129. */
  90130. get: function () {
  90131. return this._captureShaderCompilationTime;
  90132. },
  90133. /**
  90134. * Enable or disable the shader compilation time capture
  90135. */
  90136. set: function (value) {
  90137. var _this = this;
  90138. if (value === this._captureShaderCompilationTime) {
  90139. return;
  90140. }
  90141. this._captureShaderCompilationTime = value;
  90142. if (value) {
  90143. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  90144. _this._shaderCompilationTime.fetchNewFrame();
  90145. _this._shaderCompilationTime.beginMonitoring();
  90146. });
  90147. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  90148. _this._shaderCompilationTime.endMonitoring();
  90149. });
  90150. }
  90151. else {
  90152. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  90153. this._onBeforeShaderCompilationObserver = null;
  90154. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  90155. this._onAfterShaderCompilationObserver = null;
  90156. }
  90157. },
  90158. enumerable: true,
  90159. configurable: true
  90160. });
  90161. EngineInstrumentation.prototype.dispose = function () {
  90162. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  90163. this._onBeginFrameObserver = null;
  90164. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  90165. this._onEndFrameObserver = null;
  90166. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  90167. this._onBeforeShaderCompilationObserver = null;
  90168. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  90169. this._onAfterShaderCompilationObserver = null;
  90170. this.engine = null;
  90171. };
  90172. return EngineInstrumentation;
  90173. }());
  90174. BABYLON.EngineInstrumentation = EngineInstrumentation;
  90175. })(BABYLON || (BABYLON = {}));
  90176. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  90177. "use strict";
  90178. var BABYLON;
  90179. (function (BABYLON) {
  90180. /**
  90181. * This class can be used to get instrumentation data from a Babylon engine
  90182. */
  90183. var SceneInstrumentation = /** @class */ (function () {
  90184. function SceneInstrumentation(scene) {
  90185. var _this = this;
  90186. this.scene = scene;
  90187. this._captureActiveMeshesEvaluationTime = false;
  90188. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  90189. this._captureRenderTargetsRenderTime = false;
  90190. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  90191. this._captureFrameTime = false;
  90192. this._frameTime = new BABYLON.PerfCounter();
  90193. this._captureRenderTime = false;
  90194. this._renderTime = new BABYLON.PerfCounter();
  90195. this._captureInterFrameTime = false;
  90196. this._interFrameTime = new BABYLON.PerfCounter();
  90197. this._captureParticlesRenderTime = false;
  90198. this._particlesRenderTime = new BABYLON.PerfCounter();
  90199. this._captureSpritesRenderTime = false;
  90200. this._spritesRenderTime = new BABYLON.PerfCounter();
  90201. this._capturePhysicsTime = false;
  90202. this._physicsTime = new BABYLON.PerfCounter();
  90203. this._captureAnimationsTime = false;
  90204. this._animationsTime = new BABYLON.PerfCounter();
  90205. // Observers
  90206. this._onBeforeActiveMeshesEvaluationObserver = null;
  90207. this._onAfterActiveMeshesEvaluationObserver = null;
  90208. this._onBeforeRenderTargetsRenderObserver = null;
  90209. this._onAfterRenderTargetsRenderObserver = null;
  90210. this._onAfterRenderObserver = null;
  90211. this._onBeforeDrawPhaseObserver = null;
  90212. this._onAfterDrawPhaseObserver = null;
  90213. this._onBeforeAnimationsObserver = null;
  90214. this._onBeforeParticlesRenderingObserver = null;
  90215. this._onAfterParticlesRenderingObserver = null;
  90216. this._onBeforeSpritesRenderingObserver = null;
  90217. this._onAfterSpritesRenderingObserver = null;
  90218. this._onBeforePhysicsObserver = null;
  90219. this._onAfterPhysicsObserver = null;
  90220. this._onAfterAnimationsObserver = null;
  90221. // Before render
  90222. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  90223. if (_this._captureActiveMeshesEvaluationTime) {
  90224. _this._activeMeshesEvaluationTime.fetchNewFrame();
  90225. }
  90226. if (_this._captureRenderTargetsRenderTime) {
  90227. _this._renderTargetsRenderTime.fetchNewFrame();
  90228. }
  90229. if (_this._captureFrameTime) {
  90230. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  90231. _this._frameTime.beginMonitoring();
  90232. }
  90233. if (_this._captureInterFrameTime) {
  90234. _this._interFrameTime.endMonitoring();
  90235. }
  90236. if (_this._captureParticlesRenderTime) {
  90237. _this._particlesRenderTime.fetchNewFrame();
  90238. }
  90239. if (_this._captureSpritesRenderTime) {
  90240. _this._spritesRenderTime.fetchNewFrame();
  90241. }
  90242. if (_this._captureAnimationsTime) {
  90243. _this._animationsTime.beginMonitoring();
  90244. }
  90245. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  90246. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  90247. });
  90248. // After render
  90249. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  90250. if (_this._captureFrameTime) {
  90251. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  90252. _this._frameTime.endMonitoring();
  90253. }
  90254. if (_this._captureRenderTime) {
  90255. _this._renderTime.endMonitoring(false);
  90256. }
  90257. if (_this._captureInterFrameTime) {
  90258. _this._interFrameTime.beginMonitoring();
  90259. }
  90260. });
  90261. }
  90262. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  90263. // Properties
  90264. /**
  90265. * Gets the perf counter used for active meshes evaluation time
  90266. */
  90267. get: function () {
  90268. return this._activeMeshesEvaluationTime;
  90269. },
  90270. enumerable: true,
  90271. configurable: true
  90272. });
  90273. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  90274. /**
  90275. * Gets the active meshes evaluation time capture status
  90276. */
  90277. get: function () {
  90278. return this._captureActiveMeshesEvaluationTime;
  90279. },
  90280. /**
  90281. * Enable or disable the active meshes evaluation time capture
  90282. */
  90283. set: function (value) {
  90284. var _this = this;
  90285. if (value === this._captureActiveMeshesEvaluationTime) {
  90286. return;
  90287. }
  90288. this._captureActiveMeshesEvaluationTime = value;
  90289. if (value) {
  90290. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  90291. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  90292. _this._activeMeshesEvaluationTime.beginMonitoring();
  90293. });
  90294. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  90295. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  90296. _this._activeMeshesEvaluationTime.endMonitoring();
  90297. });
  90298. }
  90299. else {
  90300. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  90301. this._onBeforeActiveMeshesEvaluationObserver = null;
  90302. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  90303. this._onAfterActiveMeshesEvaluationObserver = null;
  90304. }
  90305. },
  90306. enumerable: true,
  90307. configurable: true
  90308. });
  90309. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  90310. /**
  90311. * Gets the perf counter used for render targets render time
  90312. */
  90313. get: function () {
  90314. return this._renderTargetsRenderTime;
  90315. },
  90316. enumerable: true,
  90317. configurable: true
  90318. });
  90319. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  90320. /**
  90321. * Gets the render targets render time capture status
  90322. */
  90323. get: function () {
  90324. return this._captureRenderTargetsRenderTime;
  90325. },
  90326. /**
  90327. * Enable or disable the render targets render time capture
  90328. */
  90329. set: function (value) {
  90330. var _this = this;
  90331. if (value === this._captureRenderTargetsRenderTime) {
  90332. return;
  90333. }
  90334. this._captureRenderTargetsRenderTime = value;
  90335. if (value) {
  90336. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  90337. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  90338. _this._renderTargetsRenderTime.beginMonitoring();
  90339. });
  90340. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  90341. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  90342. _this._renderTargetsRenderTime.endMonitoring(false);
  90343. });
  90344. }
  90345. else {
  90346. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  90347. this._onBeforeRenderTargetsRenderObserver = null;
  90348. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  90349. this._onAfterRenderTargetsRenderObserver = null;
  90350. }
  90351. },
  90352. enumerable: true,
  90353. configurable: true
  90354. });
  90355. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  90356. /**
  90357. * Gets the perf counter used for particles render time
  90358. */
  90359. get: function () {
  90360. return this._particlesRenderTime;
  90361. },
  90362. enumerable: true,
  90363. configurable: true
  90364. });
  90365. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  90366. /**
  90367. * Gets the particles render time capture status
  90368. */
  90369. get: function () {
  90370. return this._captureParticlesRenderTime;
  90371. },
  90372. /**
  90373. * Enable or disable the particles render time capture
  90374. */
  90375. set: function (value) {
  90376. var _this = this;
  90377. if (value === this._captureParticlesRenderTime) {
  90378. return;
  90379. }
  90380. this._captureParticlesRenderTime = value;
  90381. if (value) {
  90382. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  90383. BABYLON.Tools.StartPerformanceCounter("Particles");
  90384. _this._particlesRenderTime.beginMonitoring();
  90385. });
  90386. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  90387. BABYLON.Tools.EndPerformanceCounter("Particles");
  90388. _this._particlesRenderTime.endMonitoring(false);
  90389. });
  90390. }
  90391. else {
  90392. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  90393. this._onBeforeParticlesRenderingObserver = null;
  90394. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  90395. this._onAfterParticlesRenderingObserver = null;
  90396. }
  90397. },
  90398. enumerable: true,
  90399. configurable: true
  90400. });
  90401. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  90402. /**
  90403. * Gets the perf counter used for sprites render time
  90404. */
  90405. get: function () {
  90406. return this._spritesRenderTime;
  90407. },
  90408. enumerable: true,
  90409. configurable: true
  90410. });
  90411. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  90412. /**
  90413. * Gets the sprites render time capture status
  90414. */
  90415. get: function () {
  90416. return this._captureSpritesRenderTime;
  90417. },
  90418. /**
  90419. * Enable or disable the sprites render time capture
  90420. */
  90421. set: function (value) {
  90422. var _this = this;
  90423. if (value === this._captureSpritesRenderTime) {
  90424. return;
  90425. }
  90426. this._captureSpritesRenderTime = value;
  90427. if (value) {
  90428. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  90429. BABYLON.Tools.StartPerformanceCounter("Sprites");
  90430. _this._spritesRenderTime.beginMonitoring();
  90431. });
  90432. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  90433. BABYLON.Tools.EndPerformanceCounter("Sprites");
  90434. _this._spritesRenderTime.endMonitoring(false);
  90435. });
  90436. }
  90437. else {
  90438. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  90439. this._onBeforeSpritesRenderingObserver = null;
  90440. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  90441. this._onAfterSpritesRenderingObserver = null;
  90442. }
  90443. },
  90444. enumerable: true,
  90445. configurable: true
  90446. });
  90447. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  90448. /**
  90449. * Gets the perf counter used for physics time
  90450. */
  90451. get: function () {
  90452. return this._physicsTime;
  90453. },
  90454. enumerable: true,
  90455. configurable: true
  90456. });
  90457. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  90458. /**
  90459. * Gets the physics time capture status
  90460. */
  90461. get: function () {
  90462. return this._capturePhysicsTime;
  90463. },
  90464. /**
  90465. * Enable or disable the physics time capture
  90466. */
  90467. set: function (value) {
  90468. var _this = this;
  90469. if (value === this._capturePhysicsTime) {
  90470. return;
  90471. }
  90472. this._capturePhysicsTime = value;
  90473. if (value) {
  90474. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  90475. BABYLON.Tools.StartPerformanceCounter("Physics");
  90476. _this._physicsTime.beginMonitoring();
  90477. });
  90478. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  90479. BABYLON.Tools.EndPerformanceCounter("Physics");
  90480. _this._physicsTime.endMonitoring();
  90481. });
  90482. }
  90483. else {
  90484. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  90485. this._onBeforePhysicsObserver = null;
  90486. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  90487. this._onAfterPhysicsObserver = null;
  90488. }
  90489. },
  90490. enumerable: true,
  90491. configurable: true
  90492. });
  90493. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  90494. /**
  90495. * Gets the perf counter used for animations time
  90496. */
  90497. get: function () {
  90498. return this._animationsTime;
  90499. },
  90500. enumerable: true,
  90501. configurable: true
  90502. });
  90503. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  90504. /**
  90505. * Gets the animations time capture status
  90506. */
  90507. get: function () {
  90508. return this._captureAnimationsTime;
  90509. },
  90510. /**
  90511. * Enable or disable the animations time capture
  90512. */
  90513. set: function (value) {
  90514. var _this = this;
  90515. if (value === this._captureAnimationsTime) {
  90516. return;
  90517. }
  90518. this._captureAnimationsTime = value;
  90519. if (value) {
  90520. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  90521. _this._animationsTime.endMonitoring();
  90522. });
  90523. }
  90524. else {
  90525. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  90526. this._onAfterAnimationsObserver = null;
  90527. }
  90528. },
  90529. enumerable: true,
  90530. configurable: true
  90531. });
  90532. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  90533. /**
  90534. * Gets the perf counter used for frame time capture
  90535. */
  90536. get: function () {
  90537. return this._frameTime;
  90538. },
  90539. enumerable: true,
  90540. configurable: true
  90541. });
  90542. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  90543. /**
  90544. * Gets the frame time capture status
  90545. */
  90546. get: function () {
  90547. return this._captureFrameTime;
  90548. },
  90549. /**
  90550. * Enable or disable the frame time capture
  90551. */
  90552. set: function (value) {
  90553. this._captureFrameTime = value;
  90554. },
  90555. enumerable: true,
  90556. configurable: true
  90557. });
  90558. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  90559. /**
  90560. * Gets the perf counter used for inter-frames time capture
  90561. */
  90562. get: function () {
  90563. return this._interFrameTime;
  90564. },
  90565. enumerable: true,
  90566. configurable: true
  90567. });
  90568. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  90569. /**
  90570. * Gets the inter-frames time capture status
  90571. */
  90572. get: function () {
  90573. return this._captureInterFrameTime;
  90574. },
  90575. /**
  90576. * Enable or disable the inter-frames time capture
  90577. */
  90578. set: function (value) {
  90579. this._captureInterFrameTime = value;
  90580. },
  90581. enumerable: true,
  90582. configurable: true
  90583. });
  90584. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  90585. /**
  90586. * Gets the perf counter used for render time capture
  90587. */
  90588. get: function () {
  90589. return this._renderTime;
  90590. },
  90591. enumerable: true,
  90592. configurable: true
  90593. });
  90594. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  90595. /**
  90596. * Gets the render time capture status
  90597. */
  90598. get: function () {
  90599. return this._captureRenderTime;
  90600. },
  90601. /**
  90602. * Enable or disable the render time capture
  90603. */
  90604. set: function (value) {
  90605. var _this = this;
  90606. if (value === this._captureRenderTime) {
  90607. return;
  90608. }
  90609. this._captureRenderTime = value;
  90610. if (value) {
  90611. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  90612. _this._renderTime.beginMonitoring();
  90613. BABYLON.Tools.StartPerformanceCounter("Main render");
  90614. });
  90615. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  90616. _this._renderTime.endMonitoring(false);
  90617. BABYLON.Tools.EndPerformanceCounter("Main render");
  90618. });
  90619. }
  90620. else {
  90621. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  90622. this._onBeforeDrawPhaseObserver = null;
  90623. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  90624. this._onAfterDrawPhaseObserver = null;
  90625. }
  90626. },
  90627. enumerable: true,
  90628. configurable: true
  90629. });
  90630. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  90631. /**
  90632. * Gets the perf counter used for draw calls
  90633. */
  90634. get: function () {
  90635. return this.scene.getEngine()._drawCalls;
  90636. },
  90637. enumerable: true,
  90638. configurable: true
  90639. });
  90640. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  90641. /**
  90642. * Gets the perf counter used for texture collisions
  90643. */
  90644. get: function () {
  90645. return this.scene.getEngine()._textureCollisions;
  90646. },
  90647. enumerable: true,
  90648. configurable: true
  90649. });
  90650. SceneInstrumentation.prototype.dispose = function () {
  90651. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  90652. this._onAfterRenderObserver = null;
  90653. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  90654. this._onBeforeActiveMeshesEvaluationObserver = null;
  90655. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  90656. this._onAfterActiveMeshesEvaluationObserver = null;
  90657. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  90658. this._onBeforeRenderTargetsRenderObserver = null;
  90659. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  90660. this._onAfterRenderTargetsRenderObserver = null;
  90661. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  90662. this._onBeforeAnimationsObserver = null;
  90663. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  90664. this._onBeforeParticlesRenderingObserver = null;
  90665. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  90666. this._onAfterParticlesRenderingObserver = null;
  90667. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  90668. this._onBeforeSpritesRenderingObserver = null;
  90669. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  90670. this._onAfterSpritesRenderingObserver = null;
  90671. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  90672. this._onBeforeDrawPhaseObserver = null;
  90673. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  90674. this._onAfterDrawPhaseObserver = null;
  90675. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  90676. this._onBeforePhysicsObserver = null;
  90677. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  90678. this._onAfterPhysicsObserver = null;
  90679. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  90680. this._onAfterAnimationsObserver = null;
  90681. this.scene = null;
  90682. };
  90683. return SceneInstrumentation;
  90684. }());
  90685. BABYLON.SceneInstrumentation = SceneInstrumentation;
  90686. })(BABYLON || (BABYLON = {}));
  90687. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  90688. "use strict";
  90689. var BABYLON;
  90690. (function (BABYLON) {
  90691. var _TimeToken = /** @class */ (function () {
  90692. function _TimeToken() {
  90693. this._timeElapsedQueryEnded = false;
  90694. }
  90695. return _TimeToken;
  90696. }());
  90697. BABYLON._TimeToken = _TimeToken;
  90698. })(BABYLON || (BABYLON = {}));
  90699. //# sourceMappingURL=babylon.timeToken.js.map
  90700. "use strict";
  90701. var BABYLON;
  90702. (function (BABYLON) {
  90703. /**
  90704. * Background material defines definition.
  90705. * @ignore Mainly internal Use
  90706. */
  90707. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  90708. __extends(BackgroundMaterialDefines, _super);
  90709. /**
  90710. * Constructor of the defines.
  90711. */
  90712. function BackgroundMaterialDefines() {
  90713. var _this = _super.call(this) || this;
  90714. /**
  90715. * True if the diffuse texture is in use.
  90716. */
  90717. _this.DIFFUSE = false;
  90718. /**
  90719. * The direct UV channel to use.
  90720. */
  90721. _this.DIFFUSEDIRECTUV = 0;
  90722. /**
  90723. * True if the diffuse texture is in gamma space.
  90724. */
  90725. _this.GAMMADIFFUSE = false;
  90726. /**
  90727. * True if the diffuse texture has opacity in the alpha channel.
  90728. */
  90729. _this.DIFFUSEHASALPHA = false;
  90730. /**
  90731. * True if you want the material to fade to transparent at grazing angle.
  90732. */
  90733. _this.OPACITYFRESNEL = false;
  90734. /**
  90735. * True if an extra blur needs to be added in the reflection.
  90736. */
  90737. _this.REFLECTIONBLUR = false;
  90738. /**
  90739. * True if you want the material to fade to reflection at grazing angle.
  90740. */
  90741. _this.REFLECTIONFRESNEL = false;
  90742. /**
  90743. * True if you want the material to falloff as far as you move away from the scene center.
  90744. */
  90745. _this.REFLECTIONFALLOFF = false;
  90746. /**
  90747. * False if the current Webgl implementation does not support the texture lod extension.
  90748. */
  90749. _this.TEXTURELODSUPPORT = false;
  90750. /**
  90751. * True to ensure the data are premultiplied.
  90752. */
  90753. _this.PREMULTIPLYALPHA = false;
  90754. /**
  90755. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  90756. */
  90757. _this.USERGBCOLOR = false;
  90758. /**
  90759. * True to add noise in order to reduce the banding effect.
  90760. */
  90761. _this.NOISE = false;
  90762. /**
  90763. * is the reflection texture in BGR color scheme?
  90764. * Mainly used to solve a bug in ios10 video tag
  90765. */
  90766. _this.REFLECTIONBGR = false;
  90767. _this.IMAGEPROCESSING = false;
  90768. _this.VIGNETTE = false;
  90769. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  90770. _this.VIGNETTEBLENDMODEOPAQUE = false;
  90771. _this.TONEMAPPING = false;
  90772. _this.CONTRAST = false;
  90773. _this.COLORCURVES = false;
  90774. _this.COLORGRADING = false;
  90775. _this.COLORGRADING3D = false;
  90776. _this.SAMPLER3DGREENDEPTH = false;
  90777. _this.SAMPLER3DBGRMAP = false;
  90778. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  90779. _this.EXPOSURE = false;
  90780. _this.GRAIN = false;
  90781. // Reflection.
  90782. _this.REFLECTION = false;
  90783. _this.REFLECTIONMAP_3D = false;
  90784. _this.REFLECTIONMAP_SPHERICAL = false;
  90785. _this.REFLECTIONMAP_PLANAR = false;
  90786. _this.REFLECTIONMAP_CUBIC = false;
  90787. _this.REFLECTIONMAP_PROJECTION = false;
  90788. _this.REFLECTIONMAP_SKYBOX = false;
  90789. _this.REFLECTIONMAP_EXPLICIT = false;
  90790. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  90791. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  90792. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  90793. _this.INVERTCUBICMAP = false;
  90794. _this.REFLECTIONMAP_OPPOSITEZ = false;
  90795. _this.LODINREFLECTIONALPHA = false;
  90796. _this.GAMMAREFLECTION = false;
  90797. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  90798. // Default BJS.
  90799. _this.MAINUV1 = false;
  90800. _this.MAINUV2 = false;
  90801. _this.UV1 = false;
  90802. _this.UV2 = false;
  90803. _this.CLIPPLANE = false;
  90804. _this.POINTSIZE = false;
  90805. _this.FOG = false;
  90806. _this.NORMAL = false;
  90807. _this.NUM_BONE_INFLUENCERS = 0;
  90808. _this.BonesPerMesh = 0;
  90809. _this.INSTANCES = false;
  90810. _this.SHADOWFLOAT = false;
  90811. _this.rebuild();
  90812. return _this;
  90813. }
  90814. return BackgroundMaterialDefines;
  90815. }(BABYLON.MaterialDefines));
  90816. /**
  90817. * Background material used to create an efficient environement around your scene.
  90818. */
  90819. var BackgroundMaterial = /** @class */ (function (_super) {
  90820. __extends(BackgroundMaterial, _super);
  90821. /**
  90822. * Instantiates a Background Material in the given scene
  90823. * @param name The friendly name of the material
  90824. * @param scene The scene to add the material to
  90825. */
  90826. function BackgroundMaterial(name, scene) {
  90827. var _this = _super.call(this, name, scene) || this;
  90828. /**
  90829. * Key light Color (multiply against the R channel of the environement texture)
  90830. */
  90831. _this.primaryColor = BABYLON.Color3.White();
  90832. /**
  90833. * Key light Level (allowing HDR output of the background)
  90834. */
  90835. _this.primaryLevel = 1;
  90836. /**
  90837. * Secondary light Color (multiply against the G channel of the environement texture)
  90838. */
  90839. _this.secondaryColor = BABYLON.Color3.Gray();
  90840. /**
  90841. * Secondary light Level (allowing HDR output of the background)
  90842. */
  90843. _this.secondaryLevel = 1;
  90844. /**
  90845. * Tertiary light Color (multiply against the B channel of the environement texture)
  90846. */
  90847. _this.tertiaryColor = BABYLON.Color3.Black();
  90848. /**
  90849. * Tertiary light Level (allowing HDR output of the background)
  90850. */
  90851. _this.tertiaryLevel = 1;
  90852. /**
  90853. * Reflection Texture used in the material.
  90854. * Should be author in a specific way for the best result (refer to the documentation).
  90855. */
  90856. _this.reflectionTexture = null;
  90857. /**
  90858. * Reflection Texture level of blur.
  90859. *
  90860. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  90861. * texture twice.
  90862. */
  90863. _this.reflectionBlur = 0;
  90864. /**
  90865. * Diffuse Texture used in the material.
  90866. * Should be author in a specific way for the best result (refer to the documentation).
  90867. */
  90868. _this.diffuseTexture = null;
  90869. _this._shadowLights = null;
  90870. /**
  90871. * Specify the list of lights casting shadow on the material.
  90872. * All scene shadow lights will be included if null.
  90873. */
  90874. _this.shadowLights = null;
  90875. /**
  90876. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  90877. * soft lighting on the background.
  90878. */
  90879. _this.shadowBlurScale = 1;
  90880. /**
  90881. * Helps adjusting the shadow to a softer level if required.
  90882. * 0 means black shadows and 1 means no shadows.
  90883. */
  90884. _this.shadowLevel = 0;
  90885. /**
  90886. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  90887. * It is usually zero but might be interesting to modify according to your setup.
  90888. */
  90889. _this.sceneCenter = BABYLON.Vector3.Zero();
  90890. /**
  90891. * This helps specifying that the material is falling off to the sky box at grazing angle.
  90892. * This helps ensuring a nice transition when the camera goes under the ground.
  90893. */
  90894. _this.opacityFresnel = true;
  90895. /**
  90896. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  90897. * This helps adding a mirror texture on the ground.
  90898. */
  90899. _this.reflectionFresnel = false;
  90900. /**
  90901. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  90902. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  90903. */
  90904. _this.reflectionFalloffDistance = 0.0;
  90905. /**
  90906. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  90907. */
  90908. _this.reflectionAmount = 1.0;
  90909. /**
  90910. * This specifies the weight of the reflection at grazing angle.
  90911. */
  90912. _this.reflectionReflectance0 = 0.05;
  90913. /**
  90914. * This specifies the weight of the reflection at a perpendicular point of view.
  90915. */
  90916. _this.reflectionReflectance90 = 0.5;
  90917. /**
  90918. * Helps to directly use the maps channels instead of their level.
  90919. */
  90920. _this.useRGBColor = true;
  90921. /**
  90922. * This helps reducing the banding effect that could occur on the background.
  90923. */
  90924. _this.enableNoise = false;
  90925. _this._fovMultiplier = 1.0;
  90926. /**
  90927. * Enable the FOV adjustment feature controlled by fovMultiplier.
  90928. * @type {boolean}
  90929. */
  90930. _this.useEquirectangularFOV = false;
  90931. _this._maxSimultaneousLights = 4;
  90932. /**
  90933. * Number of Simultaneous lights allowed on the material.
  90934. */
  90935. _this.maxSimultaneousLights = 4;
  90936. /**
  90937. * Keep track of the image processing observer to allow dispose and replace.
  90938. */
  90939. _this._imageProcessingObserver = null;
  90940. /**
  90941. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  90942. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  90943. */
  90944. _this.switchToBGR = false;
  90945. // Temp values kept as cache in the material.
  90946. _this._renderTargets = new BABYLON.SmartArray(16);
  90947. _this._reflectionControls = BABYLON.Vector4.Zero();
  90948. // Setup the default processing configuration to the scene.
  90949. _this._attachImageProcessingConfiguration(null);
  90950. _this.getRenderTargetTextures = function () {
  90951. _this._renderTargets.reset();
  90952. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  90953. _this._renderTargets.push(_this._diffuseTexture);
  90954. }
  90955. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  90956. _this._renderTargets.push(_this._reflectionTexture);
  90957. }
  90958. return _this._renderTargets;
  90959. };
  90960. return _this;
  90961. }
  90962. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  90963. /**
  90964. * Sets the reflection reflectance fresnel values according to the default standard
  90965. * empirically know to work well :-)
  90966. */
  90967. set: function (value) {
  90968. var reflectionWeight = value;
  90969. if (reflectionWeight < 0.5) {
  90970. reflectionWeight = reflectionWeight * 2.0;
  90971. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  90972. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  90973. }
  90974. else {
  90975. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  90976. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  90977. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  90978. }
  90979. },
  90980. enumerable: true,
  90981. configurable: true
  90982. });
  90983. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  90984. /**
  90985. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  90986. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  90987. * Recommended to be keep at 1.0 except for special cases.
  90988. */
  90989. get: function () {
  90990. return this._fovMultiplier;
  90991. },
  90992. set: function (value) {
  90993. if (isNaN(value)) {
  90994. value = 1.0;
  90995. }
  90996. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  90997. },
  90998. enumerable: true,
  90999. configurable: true
  91000. });
  91001. /**
  91002. * Attaches a new image processing configuration to the PBR Material.
  91003. * @param configuration (if null the scene configuration will be use)
  91004. */
  91005. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  91006. var _this = this;
  91007. if (configuration === this._imageProcessingConfiguration) {
  91008. return;
  91009. }
  91010. // Detaches observer.
  91011. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  91012. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  91013. }
  91014. // Pick the scene configuration if needed.
  91015. if (!configuration) {
  91016. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  91017. }
  91018. else {
  91019. this._imageProcessingConfiguration = configuration;
  91020. }
  91021. // Attaches observer.
  91022. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  91023. _this._markAllSubMeshesAsImageProcessingDirty();
  91024. });
  91025. };
  91026. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  91027. /**
  91028. * Gets the image processing configuration used either in this material.
  91029. */
  91030. get: function () {
  91031. return this._imageProcessingConfiguration;
  91032. },
  91033. /**
  91034. * Sets the Default image processing configuration used either in the this material.
  91035. *
  91036. * If sets to null, the scene one is in use.
  91037. */
  91038. set: function (value) {
  91039. this._attachImageProcessingConfiguration(value);
  91040. // Ensure the effect will be rebuilt.
  91041. this._markAllSubMeshesAsTexturesDirty();
  91042. },
  91043. enumerable: true,
  91044. configurable: true
  91045. });
  91046. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  91047. /**
  91048. * Gets wether the color curves effect is enabled.
  91049. */
  91050. get: function () {
  91051. return this.imageProcessingConfiguration.colorCurvesEnabled;
  91052. },
  91053. /**
  91054. * Sets wether the color curves effect is enabled.
  91055. */
  91056. set: function (value) {
  91057. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  91058. },
  91059. enumerable: true,
  91060. configurable: true
  91061. });
  91062. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  91063. /**
  91064. * Gets wether the color grading effect is enabled.
  91065. */
  91066. get: function () {
  91067. return this.imageProcessingConfiguration.colorGradingEnabled;
  91068. },
  91069. /**
  91070. * Gets wether the color grading effect is enabled.
  91071. */
  91072. set: function (value) {
  91073. this.imageProcessingConfiguration.colorGradingEnabled = value;
  91074. },
  91075. enumerable: true,
  91076. configurable: true
  91077. });
  91078. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  91079. /**
  91080. * Gets wether tonemapping is enabled or not.
  91081. */
  91082. get: function () {
  91083. return this._imageProcessingConfiguration.toneMappingEnabled;
  91084. },
  91085. /**
  91086. * Sets wether tonemapping is enabled or not
  91087. */
  91088. set: function (value) {
  91089. this._imageProcessingConfiguration.toneMappingEnabled = value;
  91090. },
  91091. enumerable: true,
  91092. configurable: true
  91093. });
  91094. ;
  91095. ;
  91096. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  91097. /**
  91098. * The camera exposure used on this material.
  91099. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  91100. * This corresponds to a photographic exposure.
  91101. */
  91102. get: function () {
  91103. return this._imageProcessingConfiguration.exposure;
  91104. },
  91105. /**
  91106. * The camera exposure used on this material.
  91107. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  91108. * This corresponds to a photographic exposure.
  91109. */
  91110. set: function (value) {
  91111. this._imageProcessingConfiguration.exposure = value;
  91112. },
  91113. enumerable: true,
  91114. configurable: true
  91115. });
  91116. ;
  91117. ;
  91118. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  91119. /**
  91120. * Gets The camera contrast used on this material.
  91121. */
  91122. get: function () {
  91123. return this._imageProcessingConfiguration.contrast;
  91124. },
  91125. /**
  91126. * Sets The camera contrast used on this material.
  91127. */
  91128. set: function (value) {
  91129. this._imageProcessingConfiguration.contrast = value;
  91130. },
  91131. enumerable: true,
  91132. configurable: true
  91133. });
  91134. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  91135. /**
  91136. * Gets the Color Grading 2D Lookup Texture.
  91137. */
  91138. get: function () {
  91139. return this._imageProcessingConfiguration.colorGradingTexture;
  91140. },
  91141. /**
  91142. * Sets the Color Grading 2D Lookup Texture.
  91143. */
  91144. set: function (value) {
  91145. this.imageProcessingConfiguration.colorGradingTexture = value;
  91146. },
  91147. enumerable: true,
  91148. configurable: true
  91149. });
  91150. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  91151. /**
  91152. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  91153. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  91154. * 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;
  91155. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  91156. */
  91157. get: function () {
  91158. return this.imageProcessingConfiguration.colorCurves;
  91159. },
  91160. /**
  91161. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  91162. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  91163. * 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;
  91164. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  91165. */
  91166. set: function (value) {
  91167. this.imageProcessingConfiguration.colorCurves = value;
  91168. },
  91169. enumerable: true,
  91170. configurable: true
  91171. });
  91172. /**
  91173. * The entire material has been created in order to prevent overdraw.
  91174. * @returns false
  91175. */
  91176. BackgroundMaterial.prototype.needAlphaTesting = function () {
  91177. return true;
  91178. };
  91179. /**
  91180. * The entire material has been created in order to prevent overdraw.
  91181. * @returns true if blending is enable
  91182. */
  91183. BackgroundMaterial.prototype.needAlphaBlending = function () {
  91184. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  91185. };
  91186. /**
  91187. * Checks wether the material is ready to be rendered for a given mesh.
  91188. * @param mesh The mesh to render
  91189. * @param subMesh The submesh to check against
  91190. * @param useInstances Specify wether or not the material is used with instances
  91191. * @returns true if all the dependencies are ready (Textures, Effects...)
  91192. */
  91193. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  91194. var _this = this;
  91195. if (useInstances === void 0) { useInstances = false; }
  91196. if (subMesh.effect && this.isFrozen) {
  91197. if (this._wasPreviouslyReady) {
  91198. return true;
  91199. }
  91200. }
  91201. if (!subMesh._materialDefines) {
  91202. subMesh._materialDefines = new BackgroundMaterialDefines();
  91203. }
  91204. var scene = this.getScene();
  91205. var defines = subMesh._materialDefines;
  91206. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  91207. if (defines._renderId === scene.getRenderId()) {
  91208. return true;
  91209. }
  91210. }
  91211. var engine = scene.getEngine();
  91212. // Lights
  91213. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  91214. defines._needNormals = true;
  91215. // Textures
  91216. if (defines._areTexturesDirty) {
  91217. defines._needUVs = false;
  91218. if (scene.texturesEnabled) {
  91219. if (scene.getEngine().getCaps().textureLOD) {
  91220. defines.TEXTURELODSUPPORT = true;
  91221. }
  91222. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91223. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  91224. return false;
  91225. }
  91226. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  91227. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  91228. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  91229. defines.OPACITYFRESNEL = this._opacityFresnel;
  91230. }
  91231. else {
  91232. defines.DIFFUSE = false;
  91233. defines.DIFFUSEHASALPHA = false;
  91234. defines.GAMMADIFFUSE = false;
  91235. defines.OPACITYFRESNEL = false;
  91236. }
  91237. var reflectionTexture = this._reflectionTexture;
  91238. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91239. if (!reflectionTexture.isReadyOrNotBlocking()) {
  91240. return false;
  91241. }
  91242. defines.REFLECTION = true;
  91243. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  91244. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  91245. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  91246. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  91247. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  91248. defines.REFLECTIONBGR = this.switchToBGR;
  91249. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  91250. defines.INVERTCUBICMAP = true;
  91251. }
  91252. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  91253. switch (reflectionTexture.coordinatesMode) {
  91254. case BABYLON.Texture.CUBIC_MODE:
  91255. case BABYLON.Texture.INVCUBIC_MODE:
  91256. defines.REFLECTIONMAP_CUBIC = true;
  91257. break;
  91258. case BABYLON.Texture.EXPLICIT_MODE:
  91259. defines.REFLECTIONMAP_EXPLICIT = true;
  91260. break;
  91261. case BABYLON.Texture.PLANAR_MODE:
  91262. defines.REFLECTIONMAP_PLANAR = true;
  91263. break;
  91264. case BABYLON.Texture.PROJECTION_MODE:
  91265. defines.REFLECTIONMAP_PROJECTION = true;
  91266. break;
  91267. case BABYLON.Texture.SKYBOX_MODE:
  91268. defines.REFLECTIONMAP_SKYBOX = true;
  91269. break;
  91270. case BABYLON.Texture.SPHERICAL_MODE:
  91271. defines.REFLECTIONMAP_SPHERICAL = true;
  91272. break;
  91273. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  91274. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  91275. break;
  91276. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  91277. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  91278. break;
  91279. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  91280. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  91281. break;
  91282. }
  91283. if (this.reflectionFresnel) {
  91284. defines.REFLECTIONFRESNEL = true;
  91285. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  91286. this._reflectionControls.x = this.reflectionAmount;
  91287. this._reflectionControls.y = this.reflectionReflectance0;
  91288. this._reflectionControls.z = this.reflectionReflectance90;
  91289. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  91290. }
  91291. else {
  91292. defines.REFLECTIONFRESNEL = false;
  91293. defines.REFLECTIONFALLOFF = false;
  91294. }
  91295. }
  91296. else {
  91297. defines.REFLECTION = false;
  91298. defines.REFLECTIONFALLOFF = false;
  91299. defines.REFLECTIONBLUR = false;
  91300. defines.REFLECTIONMAP_3D = false;
  91301. defines.REFLECTIONMAP_SPHERICAL = false;
  91302. defines.REFLECTIONMAP_PLANAR = false;
  91303. defines.REFLECTIONMAP_CUBIC = false;
  91304. defines.REFLECTIONMAP_PROJECTION = false;
  91305. defines.REFLECTIONMAP_SKYBOX = false;
  91306. defines.REFLECTIONMAP_EXPLICIT = false;
  91307. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  91308. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  91309. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  91310. defines.INVERTCUBICMAP = false;
  91311. defines.REFLECTIONMAP_OPPOSITEZ = false;
  91312. defines.LODINREFLECTIONALPHA = false;
  91313. defines.GAMMAREFLECTION = false;
  91314. }
  91315. }
  91316. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  91317. defines.USERGBCOLOR = this._useRGBColor;
  91318. defines.NOISE = this._enableNoise;
  91319. }
  91320. if (defines._areImageProcessingDirty) {
  91321. if (!this._imageProcessingConfiguration.isReady()) {
  91322. return false;
  91323. }
  91324. this._imageProcessingConfiguration.prepareDefines(defines);
  91325. }
  91326. // Misc.
  91327. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  91328. // Values that need to be evaluated on every frame
  91329. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  91330. // Attribs
  91331. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  91332. if (mesh) {
  91333. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  91334. mesh.createNormals(true);
  91335. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  91336. }
  91337. }
  91338. }
  91339. // Get correct effect
  91340. if (defines.isDirty) {
  91341. defines.markAsProcessed();
  91342. scene.resetCachedMaterial();
  91343. // Fallbacks
  91344. var fallbacks = new BABYLON.EffectFallbacks();
  91345. if (defines.FOG) {
  91346. fallbacks.addFallback(0, "FOG");
  91347. }
  91348. if (defines.POINTSIZE) {
  91349. fallbacks.addFallback(1, "POINTSIZE");
  91350. }
  91351. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  91352. if (defines.NUM_BONE_INFLUENCERS > 0) {
  91353. fallbacks.addCPUSkinningFallback(0, mesh);
  91354. }
  91355. //Attributes
  91356. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91357. if (defines.NORMAL) {
  91358. attribs.push(BABYLON.VertexBuffer.NormalKind);
  91359. }
  91360. if (defines.UV1) {
  91361. attribs.push(BABYLON.VertexBuffer.UVKind);
  91362. }
  91363. if (defines.UV2) {
  91364. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91365. }
  91366. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  91367. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  91368. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  91369. "vFogInfos", "vFogColor", "pointSize",
  91370. "vClipPlane", "mBones",
  91371. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  91372. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  91373. "shadowLevel", "alpha",
  91374. "vBackgroundCenter", "vReflectionControl",
  91375. "vDiffuseInfos", "diffuseMatrix",
  91376. ];
  91377. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  91378. var uniformBuffers = ["Material", "Scene"];
  91379. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  91380. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  91381. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  91382. uniformsNames: uniforms,
  91383. uniformBuffersNames: uniformBuffers,
  91384. samplers: samplers,
  91385. defines: defines,
  91386. maxSimultaneousLights: this._maxSimultaneousLights
  91387. });
  91388. var onCompiled = function (effect) {
  91389. if (_this.onCompiled) {
  91390. _this.onCompiled(effect);
  91391. }
  91392. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  91393. };
  91394. var join = defines.toString();
  91395. subMesh.setEffect(scene.getEngine().createEffect("background", {
  91396. attributes: attribs,
  91397. uniformsNames: uniforms,
  91398. uniformBuffersNames: uniformBuffers,
  91399. samplers: samplers,
  91400. defines: join,
  91401. fallbacks: fallbacks,
  91402. onCompiled: onCompiled,
  91403. onError: this.onError,
  91404. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  91405. }, engine), defines);
  91406. this.buildUniformLayout();
  91407. }
  91408. if (!subMesh.effect || !subMesh.effect.isReady()) {
  91409. return false;
  91410. }
  91411. defines._renderId = scene.getRenderId();
  91412. this._wasPreviouslyReady = true;
  91413. return true;
  91414. };
  91415. /**
  91416. * Build the uniform buffer used in the material.
  91417. */
  91418. BackgroundMaterial.prototype.buildUniformLayout = function () {
  91419. // Order is important !
  91420. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  91421. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  91422. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  91423. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  91424. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  91425. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  91426. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  91427. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  91428. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  91429. this._uniformBuffer.addUniform("pointSize", 1);
  91430. this._uniformBuffer.addUniform("shadowLevel", 1);
  91431. this._uniformBuffer.addUniform("alpha", 1);
  91432. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  91433. this._uniformBuffer.addUniform("vReflectionControl", 4);
  91434. this._uniformBuffer.create();
  91435. };
  91436. /**
  91437. * Unbind the material.
  91438. */
  91439. BackgroundMaterial.prototype.unbind = function () {
  91440. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  91441. this._uniformBuffer.setTexture("diffuseSampler", null);
  91442. }
  91443. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  91444. this._uniformBuffer.setTexture("reflectionSampler", null);
  91445. }
  91446. _super.prototype.unbind.call(this);
  91447. };
  91448. /**
  91449. * Bind only the world matrix to the material.
  91450. * @param world The world matrix to bind.
  91451. */
  91452. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  91453. this._activeEffect.setMatrix("world", world);
  91454. };
  91455. /**
  91456. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  91457. * @param world The world matrix to bind.
  91458. * @param subMesh The submesh to bind for.
  91459. */
  91460. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  91461. var scene = this.getScene();
  91462. var defines = subMesh._materialDefines;
  91463. if (!defines) {
  91464. return;
  91465. }
  91466. var effect = subMesh.effect;
  91467. if (!effect) {
  91468. return;
  91469. }
  91470. this._activeEffect = effect;
  91471. // Matrices
  91472. this.bindOnlyWorldMatrix(world);
  91473. // Bones
  91474. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  91475. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  91476. if (mustRebind) {
  91477. this._uniformBuffer.bindToEffect(effect, "Material");
  91478. this.bindViewProjection(effect);
  91479. var reflectionTexture = this._reflectionTexture;
  91480. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  91481. // Texture uniforms
  91482. if (scene.texturesEnabled) {
  91483. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91484. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  91485. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  91486. }
  91487. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91488. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  91489. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  91490. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  91491. }
  91492. }
  91493. if (this.shadowLevel > 0) {
  91494. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  91495. }
  91496. this._uniformBuffer.updateFloat("alpha", this.alpha);
  91497. // Point size
  91498. if (this.pointsCloud) {
  91499. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  91500. }
  91501. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  91502. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  91503. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  91504. }
  91505. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  91506. // Textures
  91507. if (scene.texturesEnabled) {
  91508. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91509. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  91510. }
  91511. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91512. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  91513. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  91514. }
  91515. else if (!defines.REFLECTIONBLUR) {
  91516. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  91517. }
  91518. else {
  91519. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  91520. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  91521. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  91522. }
  91523. if (defines.REFLECTIONFRESNEL) {
  91524. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  91525. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  91526. }
  91527. }
  91528. }
  91529. // Clip plane
  91530. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  91531. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  91532. }
  91533. if (mustRebind || !this.isFrozen) {
  91534. if (scene.lightsEnabled) {
  91535. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  91536. }
  91537. // View
  91538. this.bindView(effect);
  91539. // Fog
  91540. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  91541. // image processing
  91542. this._imageProcessingConfiguration.bind(this._activeEffect);
  91543. }
  91544. this._uniformBuffer.update();
  91545. this._afterBind(mesh);
  91546. };
  91547. /**
  91548. * Dispose the material.
  91549. * @param forceDisposeEffect Force disposal of the associated effect.
  91550. * @param forceDisposeTextures Force disposal of the associated textures.
  91551. */
  91552. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  91553. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  91554. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  91555. if (forceDisposeTextures) {
  91556. if (this.diffuseTexture) {
  91557. this.diffuseTexture.dispose();
  91558. }
  91559. if (this.reflectionTexture) {
  91560. this.reflectionTexture.dispose();
  91561. }
  91562. }
  91563. this._renderTargets.dispose();
  91564. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  91565. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  91566. }
  91567. _super.prototype.dispose.call(this, forceDisposeEffect);
  91568. };
  91569. /**
  91570. * Clones the material.
  91571. * @param name The cloned name.
  91572. * @returns The cloned material.
  91573. */
  91574. BackgroundMaterial.prototype.clone = function (name) {
  91575. var _this = this;
  91576. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  91577. };
  91578. /**
  91579. * Serializes the current material to its JSON representation.
  91580. * @returns The JSON representation.
  91581. */
  91582. BackgroundMaterial.prototype.serialize = function () {
  91583. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  91584. serializationObject.customType = "BABYLON.BackgroundMaterial";
  91585. return serializationObject;
  91586. };
  91587. /**
  91588. * Gets the class name of the material
  91589. * @returns "BackgroundMaterial"
  91590. */
  91591. BackgroundMaterial.prototype.getClassName = function () {
  91592. return "BackgroundMaterial";
  91593. };
  91594. /**
  91595. * Parse a JSON input to create back a background material.
  91596. * @param source The JSON data to parse
  91597. * @param scene The scene to create the parsed material in
  91598. * @param rootUrl The root url of the assets the material depends upon
  91599. * @returns the instantiated BackgroundMaterial.
  91600. */
  91601. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  91602. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  91603. };
  91604. /**
  91605. * Standard reflectance value at parallel view angle.
  91606. */
  91607. BackgroundMaterial.StandardReflectance0 = 0.05;
  91608. /**
  91609. * Standard reflectance value at grazing angle.
  91610. */
  91611. BackgroundMaterial.StandardReflectance90 = 0.5;
  91612. __decorate([
  91613. BABYLON.serializeAsColor3()
  91614. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  91615. __decorate([
  91616. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91617. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  91618. __decorate([
  91619. BABYLON.serialize()
  91620. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  91621. __decorate([
  91622. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91623. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  91624. __decorate([
  91625. BABYLON.serializeAsColor3()
  91626. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  91627. __decorate([
  91628. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91629. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  91630. __decorate([
  91631. BABYLON.serialize()
  91632. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  91633. __decorate([
  91634. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91635. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  91636. __decorate([
  91637. BABYLON.serializeAsColor3()
  91638. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  91639. __decorate([
  91640. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91641. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  91642. __decorate([
  91643. BABYLON.serialize()
  91644. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  91645. __decorate([
  91646. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91647. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  91648. __decorate([
  91649. BABYLON.serializeAsTexture()
  91650. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  91651. __decorate([
  91652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91653. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  91654. __decorate([
  91655. BABYLON.serialize()
  91656. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  91657. __decorate([
  91658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91659. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  91660. __decorate([
  91661. BABYLON.serializeAsTexture()
  91662. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  91663. __decorate([
  91664. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91665. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  91666. __decorate([
  91667. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91668. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  91669. __decorate([
  91670. BABYLON.serialize()
  91671. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  91672. __decorate([
  91673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91674. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  91675. __decorate([
  91676. BABYLON.serialize()
  91677. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  91678. __decorate([
  91679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91680. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  91681. __decorate([
  91682. BABYLON.serializeAsVector3()
  91683. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  91684. __decorate([
  91685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91686. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  91687. __decorate([
  91688. BABYLON.serialize()
  91689. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  91690. __decorate([
  91691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91692. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  91693. __decorate([
  91694. BABYLON.serialize()
  91695. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  91696. __decorate([
  91697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91698. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  91699. __decorate([
  91700. BABYLON.serialize()
  91701. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  91702. __decorate([
  91703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91704. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  91705. __decorate([
  91706. BABYLON.serialize()
  91707. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  91708. __decorate([
  91709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91710. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  91711. __decorate([
  91712. BABYLON.serialize()
  91713. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  91714. __decorate([
  91715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91716. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  91717. __decorate([
  91718. BABYLON.serialize()
  91719. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  91720. __decorate([
  91721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91722. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  91723. __decorate([
  91724. BABYLON.serialize()
  91725. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  91726. __decorate([
  91727. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91728. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  91729. __decorate([
  91730. BABYLON.serialize()
  91731. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  91732. __decorate([
  91733. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91734. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  91735. __decorate([
  91736. BABYLON.serialize()
  91737. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  91738. __decorate([
  91739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91740. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  91741. __decorate([
  91742. BABYLON.serializeAsImageProcessingConfiguration()
  91743. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  91744. return BackgroundMaterial;
  91745. }(BABYLON.PushMaterial));
  91746. BABYLON.BackgroundMaterial = BackgroundMaterial;
  91747. })(BABYLON || (BABYLON = {}));
  91748. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  91749. "use strict";
  91750. var __assign = (this && this.__assign) || Object.assign || function(t) {
  91751. for (var s, i = 1, n = arguments.length; i < n; i++) {
  91752. s = arguments[i];
  91753. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  91754. t[p] = s[p];
  91755. }
  91756. return t;
  91757. };
  91758. var BABYLON;
  91759. (function (BABYLON) {
  91760. /**
  91761. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  91762. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  91763. * It also helps with the default setup of your imageProcessing configuration.
  91764. */
  91765. var EnvironmentHelper = /** @class */ (function () {
  91766. /**
  91767. * constructor
  91768. * @param options
  91769. * @param scene The scene to add the material to
  91770. */
  91771. function EnvironmentHelper(options, scene) {
  91772. var _this = this;
  91773. this._errorHandler = function (message, exception) {
  91774. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  91775. };
  91776. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  91777. this._scene = scene;
  91778. this.onErrorObservable = new BABYLON.Observable();
  91779. this._setupBackground();
  91780. this._setupImageProcessing();
  91781. }
  91782. /**
  91783. * Creates the default options for the helper.
  91784. */
  91785. EnvironmentHelper._getDefaultOptions = function () {
  91786. return {
  91787. createGround: true,
  91788. groundSize: 15,
  91789. groundTexture: this._groundTextureCDNUrl,
  91790. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  91791. groundOpacity: 0.9,
  91792. enableGroundShadow: true,
  91793. groundShadowLevel: 0.5,
  91794. enableGroundMirror: false,
  91795. groundMirrorSizeRatio: 0.3,
  91796. groundMirrorBlurKernel: 64,
  91797. groundMirrorAmount: 1,
  91798. groundMirrorFresnelWeight: 1,
  91799. groundMirrorFallOffDistance: 0,
  91800. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  91801. groundYBias: 0.00001,
  91802. createSkybox: true,
  91803. skyboxSize: 20,
  91804. skyboxTexture: this._skyboxTextureCDNUrl,
  91805. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  91806. backgroundYRotation: 0,
  91807. sizeAuto: true,
  91808. rootPosition: BABYLON.Vector3.Zero(),
  91809. setupImageProcessing: true,
  91810. environmentTexture: this._environmentTextureCDNUrl,
  91811. cameraExposure: 0.8,
  91812. cameraContrast: 1.2,
  91813. toneMappingEnabled: true,
  91814. };
  91815. };
  91816. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  91817. /**
  91818. * Gets the root mesh created by the helper.
  91819. */
  91820. get: function () {
  91821. return this._rootMesh;
  91822. },
  91823. enumerable: true,
  91824. configurable: true
  91825. });
  91826. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  91827. /**
  91828. * Gets the skybox created by the helper.
  91829. */
  91830. get: function () {
  91831. return this._skybox;
  91832. },
  91833. enumerable: true,
  91834. configurable: true
  91835. });
  91836. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  91837. /**
  91838. * Gets the skybox texture created by the helper.
  91839. */
  91840. get: function () {
  91841. return this._skyboxTexture;
  91842. },
  91843. enumerable: true,
  91844. configurable: true
  91845. });
  91846. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  91847. /**
  91848. * Gets the skybox material created by the helper.
  91849. */
  91850. get: function () {
  91851. return this._skyboxMaterial;
  91852. },
  91853. enumerable: true,
  91854. configurable: true
  91855. });
  91856. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  91857. /**
  91858. * Gets the ground mesh created by the helper.
  91859. */
  91860. get: function () {
  91861. return this._ground;
  91862. },
  91863. enumerable: true,
  91864. configurable: true
  91865. });
  91866. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  91867. /**
  91868. * Gets the ground texture created by the helper.
  91869. */
  91870. get: function () {
  91871. return this._groundTexture;
  91872. },
  91873. enumerable: true,
  91874. configurable: true
  91875. });
  91876. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  91877. /**
  91878. * Gets the ground mirror created by the helper.
  91879. */
  91880. get: function () {
  91881. return this._groundMirror;
  91882. },
  91883. enumerable: true,
  91884. configurable: true
  91885. });
  91886. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  91887. /**
  91888. * Gets the ground mirror render list to helps pushing the meshes
  91889. * you wish in the ground reflection.
  91890. */
  91891. get: function () {
  91892. if (this._groundMirror) {
  91893. return this._groundMirror.renderList;
  91894. }
  91895. return null;
  91896. },
  91897. enumerable: true,
  91898. configurable: true
  91899. });
  91900. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  91901. /**
  91902. * Gets the ground material created by the helper.
  91903. */
  91904. get: function () {
  91905. return this._groundMaterial;
  91906. },
  91907. enumerable: true,
  91908. configurable: true
  91909. });
  91910. /**
  91911. * Updates the background according to the new options
  91912. * @param options
  91913. */
  91914. EnvironmentHelper.prototype.updateOptions = function (options) {
  91915. var newOptions = __assign({}, this._options, options);
  91916. if (this._ground && !newOptions.createGround) {
  91917. this._ground.dispose();
  91918. this._ground = null;
  91919. }
  91920. if (this._groundMaterial && !newOptions.createGround) {
  91921. this._groundMaterial.dispose();
  91922. this._groundMaterial = null;
  91923. }
  91924. if (this._groundTexture) {
  91925. if (this._options.groundTexture != newOptions.groundTexture) {
  91926. this._groundTexture.dispose();
  91927. this._groundTexture = null;
  91928. }
  91929. }
  91930. if (this._skybox && !newOptions.createSkybox) {
  91931. this._skybox.dispose();
  91932. this._skybox = null;
  91933. }
  91934. if (this._skyboxMaterial && !newOptions.createSkybox) {
  91935. this._skyboxMaterial.dispose();
  91936. this._skyboxMaterial = null;
  91937. }
  91938. if (this._skyboxTexture) {
  91939. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  91940. this._skyboxTexture.dispose();
  91941. this._skyboxTexture = null;
  91942. }
  91943. }
  91944. if (this._groundMirror && !newOptions.enableGroundMirror) {
  91945. this._groundMirror.dispose();
  91946. this._groundMirror = null;
  91947. }
  91948. if (this._scene.environmentTexture) {
  91949. if (this._options.environmentTexture != newOptions.environmentTexture) {
  91950. this._scene.environmentTexture.dispose();
  91951. }
  91952. }
  91953. this._options = newOptions;
  91954. this._setupBackground();
  91955. this._setupImageProcessing();
  91956. };
  91957. /**
  91958. * Sets the primary color of all the available elements.
  91959. * @param color
  91960. */
  91961. EnvironmentHelper.prototype.setMainColor = function (color) {
  91962. if (this.groundMaterial) {
  91963. this.groundMaterial.primaryColor = color;
  91964. }
  91965. if (this.skyboxMaterial) {
  91966. this.skyboxMaterial.primaryColor = color;
  91967. }
  91968. if (this.groundMirror) {
  91969. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  91970. }
  91971. };
  91972. /**
  91973. * Setup the image processing according to the specified options.
  91974. */
  91975. EnvironmentHelper.prototype._setupImageProcessing = function () {
  91976. if (this._options.setupImageProcessing) {
  91977. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  91978. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  91979. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  91980. this._setupEnvironmentTexture();
  91981. }
  91982. };
  91983. /**
  91984. * Setup the environment texture according to the specified options.
  91985. */
  91986. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  91987. if (this._scene.environmentTexture) {
  91988. return;
  91989. }
  91990. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  91991. this._scene.environmentTexture = this._options.environmentTexture;
  91992. return;
  91993. }
  91994. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  91995. this._scene.environmentTexture = environmentTexture;
  91996. };
  91997. /**
  91998. * Setup the background according to the specified options.
  91999. */
  92000. EnvironmentHelper.prototype._setupBackground = function () {
  92001. if (!this._rootMesh) {
  92002. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  92003. }
  92004. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  92005. var sceneSize = this._getSceneSize();
  92006. if (this._options.createGround) {
  92007. this._setupGround(sceneSize);
  92008. this._setupGroundMaterial();
  92009. this._setupGroundDiffuseTexture();
  92010. if (this._options.enableGroundMirror) {
  92011. this._setupGroundMirrorTexture(sceneSize);
  92012. }
  92013. this._setupMirrorInGroundMaterial();
  92014. }
  92015. if (this._options.createSkybox) {
  92016. this._setupSkybox(sceneSize);
  92017. this._setupSkyboxMaterial();
  92018. this._setupSkyboxReflectionTexture();
  92019. }
  92020. this._rootMesh.position.x = sceneSize.rootPosition.x;
  92021. this._rootMesh.position.z = sceneSize.rootPosition.z;
  92022. this._rootMesh.position.y = sceneSize.rootPosition.y;
  92023. };
  92024. /**
  92025. * Get the scene sizes according to the setup.
  92026. */
  92027. EnvironmentHelper.prototype._getSceneSize = function () {
  92028. var _this = this;
  92029. var groundSize = this._options.groundSize;
  92030. var skyboxSize = this._options.skyboxSize;
  92031. var rootPosition = this._options.rootPosition;
  92032. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  92033. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  92034. }
  92035. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  92036. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  92037. });
  92038. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  92039. if (this._options.sizeAuto) {
  92040. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  92041. this._scene.activeCamera.upperRadiusLimit) {
  92042. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  92043. skyboxSize = groundSize;
  92044. }
  92045. var sceneDiagonalLenght = sceneDiagonal.length();
  92046. if (sceneDiagonalLenght > groundSize) {
  92047. groundSize = sceneDiagonalLenght * 2;
  92048. skyboxSize = groundSize;
  92049. }
  92050. // 10 % bigger.
  92051. groundSize *= 1.1;
  92052. skyboxSize *= 1.5;
  92053. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  92054. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  92055. }
  92056. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  92057. };
  92058. /**
  92059. * Setup the ground according to the specified options.
  92060. */
  92061. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  92062. var _this = this;
  92063. if (!this._ground) {
  92064. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  92065. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  92066. this._ground.parent = this._rootMesh;
  92067. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  92068. }
  92069. this._ground.receiveShadows = this._options.enableGroundShadow;
  92070. };
  92071. /**
  92072. * Setup the ground material according to the specified options.
  92073. */
  92074. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  92075. if (!this._groundMaterial) {
  92076. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  92077. }
  92078. this._groundMaterial.alpha = this._options.groundOpacity;
  92079. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  92080. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  92081. this._groundMaterial.primaryLevel = 1;
  92082. this._groundMaterial.primaryColor = this._options.groundColor;
  92083. this._groundMaterial.secondaryLevel = 0;
  92084. this._groundMaterial.tertiaryLevel = 0;
  92085. this._groundMaterial.useRGBColor = false;
  92086. this._groundMaterial.enableNoise = true;
  92087. if (this._ground) {
  92088. this._ground.material = this._groundMaterial;
  92089. }
  92090. };
  92091. /**
  92092. * Setup the ground diffuse texture according to the specified options.
  92093. */
  92094. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  92095. if (!this._groundMaterial) {
  92096. return;
  92097. }
  92098. if (this._groundTexture) {
  92099. return;
  92100. }
  92101. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  92102. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  92103. return;
  92104. }
  92105. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  92106. diffuseTexture.gammaSpace = false;
  92107. diffuseTexture.hasAlpha = true;
  92108. this._groundMaterial.diffuseTexture = diffuseTexture;
  92109. };
  92110. /**
  92111. * Setup the ground mirror texture according to the specified options.
  92112. */
  92113. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  92114. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92115. if (!this._groundMirror) {
  92116. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  92117. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  92118. this._groundMirror.anisotropicFilteringLevel = 1;
  92119. this._groundMirror.wrapU = wrapping;
  92120. this._groundMirror.wrapV = wrapping;
  92121. this._groundMirror.gammaSpace = false;
  92122. if (this._groundMirror.renderList) {
  92123. for (var i = 0; i < this._scene.meshes.length; i++) {
  92124. var mesh = this._scene.meshes[i];
  92125. if (mesh !== this._ground &&
  92126. mesh !== this._skybox &&
  92127. mesh !== this._rootMesh) {
  92128. this._groundMirror.renderList.push(mesh);
  92129. }
  92130. }
  92131. }
  92132. }
  92133. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  92134. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  92135. };
  92136. /**
  92137. * Setup the ground to receive the mirror texture.
  92138. */
  92139. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  92140. if (this._groundMaterial) {
  92141. this._groundMaterial.reflectionTexture = this._groundMirror;
  92142. this._groundMaterial.reflectionFresnel = true;
  92143. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  92144. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  92145. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  92146. }
  92147. };
  92148. /**
  92149. * Setup the skybox according to the specified options.
  92150. */
  92151. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  92152. var _this = this;
  92153. if (!this._skybox) {
  92154. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  92155. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  92156. }
  92157. this._skybox.parent = this._rootMesh;
  92158. };
  92159. /**
  92160. * Setup the skybox material according to the specified options.
  92161. */
  92162. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  92163. if (!this._skybox) {
  92164. return;
  92165. }
  92166. if (!this._skyboxMaterial) {
  92167. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  92168. }
  92169. this._skyboxMaterial.useRGBColor = false;
  92170. this._skyboxMaterial.primaryLevel = 1;
  92171. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  92172. this._skyboxMaterial.secondaryLevel = 0;
  92173. this._skyboxMaterial.tertiaryLevel = 0;
  92174. this._skyboxMaterial.enableNoise = true;
  92175. this._skybox.material = this._skyboxMaterial;
  92176. };
  92177. /**
  92178. * Setup the skybox reflection texture according to the specified options.
  92179. */
  92180. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  92181. if (!this._skyboxMaterial) {
  92182. return;
  92183. }
  92184. if (this._skyboxTexture) {
  92185. return;
  92186. }
  92187. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  92188. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  92189. return;
  92190. }
  92191. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  92192. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  92193. this._skyboxTexture.gammaSpace = false;
  92194. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  92195. };
  92196. /**
  92197. * Dispose all the elements created by the Helper.
  92198. */
  92199. EnvironmentHelper.prototype.dispose = function () {
  92200. if (this._groundMaterial) {
  92201. this._groundMaterial.dispose(true, true);
  92202. }
  92203. if (this._skyboxMaterial) {
  92204. this._skyboxMaterial.dispose(true, true);
  92205. }
  92206. this._rootMesh.dispose(false);
  92207. };
  92208. /**
  92209. * Default ground texture URL.
  92210. */
  92211. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  92212. /**
  92213. * Default skybox texture URL.
  92214. */
  92215. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  92216. /**
  92217. * Default environment texture URL.
  92218. */
  92219. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  92220. return EnvironmentHelper;
  92221. }());
  92222. BABYLON.EnvironmentHelper = EnvironmentHelper;
  92223. })(BABYLON || (BABYLON = {}));
  92224. //# sourceMappingURL=babylon.environmentHelper.js.map
  92225. "use strict";
  92226. var BABYLON;
  92227. (function (BABYLON) {
  92228. /**
  92229. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  92230. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  92231. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  92232. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  92233. */
  92234. var VideoDome = /** @class */ (function (_super) {
  92235. __extends(VideoDome, _super);
  92236. /**
  92237. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  92238. * @param name Element's name, child elements will append suffixes for their own names.
  92239. * @param urlsOrVideo
  92240. * @param options An object containing optional or exposed sub element properties:
  92241. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  92242. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  92243. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  92244. * @param options **loop=true** Automatically loop video on end.
  92245. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  92246. */
  92247. function VideoDome(name, urlsOrVideo, options, scene) {
  92248. var _this = _super.call(this, name, scene) || this;
  92249. // set defaults and manage values
  92250. name = name || "videoDome";
  92251. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  92252. options.clickToPlay = Boolean(options.clickToPlay);
  92253. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  92254. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  92255. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  92256. // create
  92257. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  92258. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  92259. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  92260. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  92261. flat: false,
  92262. radius: options.size,
  92263. subdivisions: options.resolution,
  92264. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  92265. }, scene);
  92266. // configure material
  92267. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  92268. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  92269. material.reflectionTexture = _this._videoTexture;
  92270. material.useEquirectangularFOV = true;
  92271. material.fovMultiplier = 1.0;
  92272. // configure mesh
  92273. _this._mesh.material = material;
  92274. _this._mesh.parent = _this;
  92275. // optional configuration
  92276. if (options.clickToPlay) {
  92277. scene.onPointerUp = function () {
  92278. _this._videoTexture.video.play();
  92279. };
  92280. }
  92281. return _this;
  92282. }
  92283. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  92284. /**
  92285. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  92286. * Also see the options.resolution property.
  92287. */
  92288. get: function () {
  92289. return this._material.fovMultiplier;
  92290. },
  92291. set: function (value) {
  92292. this._material.fovMultiplier = value;
  92293. },
  92294. enumerable: true,
  92295. configurable: true
  92296. });
  92297. /**
  92298. * Releases resources associated with this node.
  92299. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  92300. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  92301. */
  92302. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  92303. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  92304. this._videoTexture.dispose();
  92305. this._mesh.dispose();
  92306. this._material.dispose();
  92307. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  92308. };
  92309. return VideoDome;
  92310. }(BABYLON.Node));
  92311. BABYLON.VideoDome = VideoDome;
  92312. })(BABYLON || (BABYLON = {}));
  92313. //# sourceMappingURL=babylon.videoDome.js.map
  92314. 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#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\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\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\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","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 circleOfConfusionSampler;\nuniform sampler2D blurStep0;\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{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(textureSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\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"};
  92315. 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};"};
  92316. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  92317. globalObject["BABYLON"] = BABYLON
  92318. return BABYLON;
  92319. });
  92320. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(16)))
  92321. /***/ }),
  92322. /* 1 */
  92323. /***/ (function(module, exports, __webpack_require__) {
  92324. "use strict";
  92325. Object.defineProperty(exports, "__esModule", { value: true });
  92326. var babylonjs_1 = __webpack_require__(0);
  92327. var helper_1 = __webpack_require__(2);
  92328. var HTMLMapper = (function () {
  92329. function HTMLMapper() {
  92330. }
  92331. HTMLMapper.prototype.map = function (element) {
  92332. var config = {};
  92333. var _loop_1 = function (attrIdx) {
  92334. var attr = element.attributes.item(attrIdx);
  92335. var split = attr.nodeName.split('.');
  92336. split.reduce(function (currentConfig, key, idx) {
  92337. var camelKey = helper_1.kebabToCamel(key);
  92338. if (idx === split.length - 1) {
  92339. var val = attr.nodeValue;
  92340. if (val === "true") {
  92341. val = true;
  92342. }
  92343. else if (val === "false") {
  92344. val = false;
  92345. }
  92346. else {
  92347. var isnum = /^\d+$/.test(val);
  92348. if (isnum) {
  92349. var number = parseFloat(val);
  92350. if (!isNaN(number)) {
  92351. val = number;
  92352. }
  92353. }
  92354. }
  92355. currentConfig[camelKey] = val;
  92356. }
  92357. else {
  92358. currentConfig[camelKey] = currentConfig[camelKey] || {};
  92359. }
  92360. return currentConfig[camelKey];
  92361. }, config);
  92362. };
  92363. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  92364. _loop_1(attrIdx);
  92365. }
  92366. return config;
  92367. };
  92368. return HTMLMapper;
  92369. }());
  92370. var JSONMapper = (function () {
  92371. function JSONMapper() {
  92372. }
  92373. JSONMapper.prototype.map = function (rawSource) {
  92374. return JSON.parse(rawSource);
  92375. };
  92376. return JSONMapper;
  92377. }());
  92378. var DOMMapper = (function () {
  92379. function DOMMapper() {
  92380. }
  92381. DOMMapper.prototype.map = function (baseElement) {
  92382. var htmlMapper = new HTMLMapper();
  92383. var config = htmlMapper.map(baseElement);
  92384. var traverseChildren = function (element, partConfig) {
  92385. var children = element.children;
  92386. if (children.length) {
  92387. for (var i = 0; i < children.length; ++i) {
  92388. var item = children.item(i);
  92389. var configMapped = htmlMapper.map(item);
  92390. var key = helper_1.kebabToCamel(item.nodeName.toLowerCase());
  92391. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  92392. partConfig[key] = [];
  92393. }
  92394. else {
  92395. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  92396. partConfig.push(configMapped);
  92397. }
  92398. else if (partConfig[key]) {
  92399. element.setAttribute('array', 'true');
  92400. var oldItem = partConfig[key];
  92401. partConfig = [oldItem, configMapped];
  92402. }
  92403. else {
  92404. partConfig[key] = configMapped;
  92405. }
  92406. }
  92407. traverseChildren(item, partConfig[key] || configMapped);
  92408. }
  92409. }
  92410. return partConfig;
  92411. };
  92412. traverseChildren(baseElement, config);
  92413. return config;
  92414. };
  92415. return DOMMapper;
  92416. }());
  92417. var MapperManager = (function () {
  92418. function MapperManager() {
  92419. this.mappers = {
  92420. "html": new HTMLMapper(),
  92421. "json": new JSONMapper(),
  92422. "dom": new DOMMapper()
  92423. };
  92424. }
  92425. MapperManager.prototype.getMapper = function (type) {
  92426. if (!this.mappers[type]) {
  92427. babylonjs_1.Tools.Error("No mapper defined for " + type);
  92428. }
  92429. return this.mappers[type] || this.mappers[MapperManager.DefaultMapper];
  92430. };
  92431. MapperManager.prototype.registerMapper = function (type, mapper) {
  92432. this.mappers[type] = mapper;
  92433. };
  92434. MapperManager.DefaultMapper = 'json';
  92435. return MapperManager;
  92436. }());
  92437. exports.MapperManager = MapperManager;
  92438. exports.mapperManager = new MapperManager();
  92439. /***/ }),
  92440. /* 2 */
  92441. /***/ (function(module, exports, __webpack_require__) {
  92442. "use strict";
  92443. Object.defineProperty(exports, "__esModule", { value: true });
  92444. function isUrl(urlToCheck) {
  92445. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  92446. return true;
  92447. }
  92448. return false;
  92449. }
  92450. exports.isUrl = isUrl;
  92451. function kebabToCamel(s) {
  92452. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  92453. }
  92454. exports.kebabToCamel = kebabToCamel;
  92455. function camelToKebab(str) {
  92456. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  92457. }
  92458. exports.camelToKebab = camelToKebab;
  92459. /***/ }),
  92460. /* 3 */
  92461. /***/ (function(module, exports, __webpack_require__) {
  92462. "use strict";
  92463. Object.defineProperty(exports, "__esModule", { value: true });
  92464. var babylonjs_1 = __webpack_require__(0);
  92465. var ViewerManager = (function () {
  92466. function ViewerManager() {
  92467. this.viewers = {};
  92468. this.onViewerAddedObservable = new babylonjs_1.Observable();
  92469. }
  92470. ViewerManager.prototype.addViewer = function (viewer) {
  92471. this.viewers[viewer.getBaseId()] = viewer;
  92472. this._onViewerAdded(viewer);
  92473. };
  92474. ViewerManager.prototype.getViewerById = function (id) {
  92475. return this.viewers[id];
  92476. };
  92477. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  92478. for (var id in this.viewers) {
  92479. if (this.viewers[id].containerElement === element) {
  92480. return this.getViewerById(id);
  92481. }
  92482. }
  92483. };
  92484. ViewerManager.prototype.getViewerPromiseById = function (id) {
  92485. var _this = this;
  92486. return new Promise(function (resolve, reject) {
  92487. var localViewer = _this.getViewerById(id);
  92488. if (localViewer) {
  92489. return resolve(localViewer);
  92490. }
  92491. var viewerFunction = function (viewer) {
  92492. if (viewer.getBaseId() === id) {
  92493. resolve(viewer);
  92494. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  92495. }
  92496. };
  92497. _this.onViewerAddedObservable.add(viewerFunction);
  92498. });
  92499. };
  92500. ViewerManager.prototype._onViewerAdded = function (viewer) {
  92501. this.onViewerAdded && this.onViewerAdded(viewer);
  92502. this.onViewerAddedObservable.notifyObservers(viewer);
  92503. };
  92504. return ViewerManager;
  92505. }());
  92506. exports.ViewerManager = ViewerManager;
  92507. exports.viewerManager = new ViewerManager();
  92508. /***/ }),
  92509. /* 4 */
  92510. /***/ (function(module, exports, __webpack_require__) {
  92511. "use strict";
  92512. var __extends = (this && this.__extends) || (function () {
  92513. var extendStatics = Object.setPrototypeOf ||
  92514. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  92515. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  92516. return function (d, b) {
  92517. extendStatics(d, b);
  92518. function __() { this.constructor = d; }
  92519. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  92520. };
  92521. })();
  92522. Object.defineProperty(exports, "__esModule", { value: true });
  92523. var viewer_1 = __webpack_require__(5);
  92524. var babylonjs_1 = __webpack_require__(0);
  92525. var DefaultViewer = (function (_super) {
  92526. __extends(DefaultViewer, _super);
  92527. function DefaultViewer(containerElement, initialConfiguration) {
  92528. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  92529. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  92530. _this.containerElement = containerElement;
  92531. _this.onModelLoaded = function (model) {
  92532. var hideLoadingDelay = 500;
  92533. if (_this.configuration.lab && _this.configuration.lab.hideLoadingDelay !== undefined) {
  92534. hideLoadingDelay = _this.configuration.lab.hideLoadingDelay;
  92535. }
  92536. setTimeout(function () {
  92537. _this.hideLoadingScreen();
  92538. }, hideLoadingDelay);
  92539. return;
  92540. };
  92541. _this.onModelLoadedObservable.add(_this.onModelLoaded);
  92542. return _this;
  92543. }
  92544. DefaultViewer.prototype.initScene = function () {
  92545. var _this = this;
  92546. return _super.prototype.initScene.call(this).then(function () {
  92547. _this.extendClassWithConfig(_this.scene, _this.configuration.scene);
  92548. return _this.scene;
  92549. });
  92550. };
  92551. DefaultViewer.prototype.onTemplatesLoaded = function () {
  92552. var _this = this;
  92553. this.showLoadingScreen();
  92554. this.initNavbar();
  92555. var closeButton = document.getElementById('close-button');
  92556. if (closeButton) {
  92557. closeButton.addEventListener('pointerdown', function () {
  92558. _this.hideOverlayScreen();
  92559. });
  92560. }
  92561. return _super.prototype.onTemplatesLoaded.call(this);
  92562. };
  92563. DefaultViewer.prototype.initNavbar = function () {
  92564. var navbar = this.templateManager.getTemplate('navBar');
  92565. if (navbar) {
  92566. var navbarHeight_1 = navbar.parent.clientHeight + 'px';
  92567. var navbarShown_1 = true;
  92568. var timeoutCancel_1;
  92569. var triggerNavbar = function (show, evt) {
  92570. if (show === void 0) { show = false; }
  92571. if (!navbar || evt.button > 0)
  92572. return;
  92573. timeoutCancel_1 && clearTimeout(timeoutCancel_1);
  92574. if (show === navbarShown_1)
  92575. return;
  92576. if (show) {
  92577. navbar.parent.style.bottom = show ? '0px' : '-' + navbarHeight_1;
  92578. navbarShown_1 = show;
  92579. }
  92580. else {
  92581. var visibilityTimeout = 2000;
  92582. if (navbar.configuration.params && navbar.configuration.params.visibilityTimeout !== undefined) {
  92583. visibilityTimeout = navbar.configuration.params.visibilityTimeout;
  92584. }
  92585. timeoutCancel_1 = setTimeout(function () {
  92586. if (navbar) {
  92587. navbar.parent.style.bottom = '-' + navbarHeight_1;
  92588. }
  92589. navbarShown_1 = show;
  92590. }, visibilityTimeout);
  92591. }
  92592. };
  92593. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerout');
  92594. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, true), 'pointerdown');
  92595. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerup');
  92596. this.templateManager.eventManager.registerCallback('navBar', triggerNavbar.bind(this, true), 'pointerover');
  92597. var viewerTemplate = this.templateManager.getTemplate('viewer');
  92598. var viewerElement_1 = viewerTemplate && viewerTemplate.parent;
  92599. var triggerFullscren = function (eventData) {
  92600. if (viewerElement_1) {
  92601. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  92602. if (!fullscreenElement) {
  92603. var requestFullScreen = viewerElement_1.requestFullscreen || viewerElement_1.webkitRequestFullscreen || viewerElement_1.msRequestFullscreen || viewerElement_1.mozRequestFullScreen;
  92604. requestFullScreen.call(viewerElement_1);
  92605. }
  92606. else {
  92607. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  92608. exitFullscreen.call(document);
  92609. }
  92610. }
  92611. };
  92612. this.templateManager.eventManager.registerCallback('navBar', triggerFullscren, 'pointerdown', '#fullscreen-button');
  92613. }
  92614. };
  92615. DefaultViewer.prototype.prepareContainerElement = function () {
  92616. this.containerElement.style.position = 'relative';
  92617. this.containerElement.style.display = 'flex';
  92618. };
  92619. DefaultViewer.prototype.configureModel = function (modelConfiguration, model) {
  92620. _super.prototype.configureModel.call(this, modelConfiguration, model);
  92621. var navbar = this.templateManager.getTemplate('navBar');
  92622. if (!navbar)
  92623. return;
  92624. var metadataContainer = navbar.parent.querySelector('#model-metadata');
  92625. if (metadataContainer) {
  92626. if (modelConfiguration.title !== undefined) {
  92627. var element = metadataContainer.querySelector('span.model-title');
  92628. if (element) {
  92629. element.innerHTML = modelConfiguration.title;
  92630. }
  92631. }
  92632. if (modelConfiguration.subtitle !== undefined) {
  92633. var element = metadataContainer.querySelector('span.model-subtitle');
  92634. if (element) {
  92635. element.innerHTML = modelConfiguration.subtitle;
  92636. }
  92637. }
  92638. if (modelConfiguration.thumbnail !== undefined) {
  92639. metadataContainer.querySelector('.thumbnail').style.backgroundImage = "url('" + modelConfiguration.thumbnail + "')";
  92640. }
  92641. }
  92642. };
  92643. DefaultViewer.prototype.loadModel = function (model) {
  92644. var _this = this;
  92645. if (model === void 0) { model = this.configuration.model; }
  92646. this.showLoadingScreen();
  92647. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  92648. console.log(error);
  92649. _this.hideLoadingScreen();
  92650. _this.showOverlayScreen('error');
  92651. return Promise.reject(error);
  92652. });
  92653. };
  92654. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  92655. var _this = this;
  92656. var template = this.templateManager.getTemplate('overlay');
  92657. if (!template)
  92658. return Promise.resolve('Overlay template not found');
  92659. return template.show((function (template) {
  92660. var canvasRect = _this.containerElement.getBoundingClientRect();
  92661. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  92662. template.parent.style.display = 'flex';
  92663. template.parent.style.width = canvasRect.width + "px";
  92664. template.parent.style.height = canvasRect.height + "px";
  92665. template.parent.style.opacity = "1";
  92666. var subTemplate = _this.templateManager.getTemplate(subScreen);
  92667. if (!subTemplate) {
  92668. return Promise.reject(subScreen + ' template not found');
  92669. }
  92670. return subTemplate.show((function (template) {
  92671. template.parent.style.display = 'flex';
  92672. return Promise.resolve(template);
  92673. }));
  92674. }));
  92675. };
  92676. DefaultViewer.prototype.hideOverlayScreen = function () {
  92677. var template = this.templateManager.getTemplate('overlay');
  92678. if (!template)
  92679. return Promise.resolve('Overlay template not found');
  92680. return template.hide((function (template) {
  92681. template.parent.style.opacity = "0";
  92682. var onTransitionEnd = function () {
  92683. template.parent.removeEventListener("transitionend", onTransitionEnd);
  92684. template.parent.style.display = 'none';
  92685. };
  92686. template.parent.addEventListener("transitionend", onTransitionEnd);
  92687. var overlays = template.parent.querySelectorAll('.overlay');
  92688. if (overlays) {
  92689. for (var i = 0; i < overlays.length; ++i) {
  92690. var htmlElement = overlays.item(i);
  92691. htmlElement.style.display = 'none';
  92692. }
  92693. }
  92694. return Promise.resolve(template);
  92695. }));
  92696. };
  92697. DefaultViewer.prototype.showLoadingScreen = function () {
  92698. var _this = this;
  92699. var template = this.templateManager.getTemplate('loadingScreen');
  92700. if (!template)
  92701. return Promise.resolve('Loading Screen template not found');
  92702. return template.show((function (template) {
  92703. var canvasRect = _this.containerElement.getBoundingClientRect();
  92704. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  92705. template.parent.style.display = 'flex';
  92706. template.parent.style.width = canvasRect.width + "px";
  92707. template.parent.style.height = canvasRect.height + "px";
  92708. template.parent.style.opacity = "1";
  92709. template.parent.style.backgroundColor = "black";
  92710. return Promise.resolve(template);
  92711. }));
  92712. };
  92713. DefaultViewer.prototype.hideLoadingScreen = function () {
  92714. var template = this.templateManager.getTemplate('loadingScreen');
  92715. if (!template)
  92716. return Promise.resolve('Loading Screen template not found');
  92717. return template.hide((function (template) {
  92718. template.parent.style.opacity = "0";
  92719. var onTransitionEnd = function () {
  92720. template.parent.removeEventListener("transitionend", onTransitionEnd);
  92721. template.parent.style.display = 'none';
  92722. };
  92723. template.parent.addEventListener("transitionend", onTransitionEnd);
  92724. return Promise.resolve(template);
  92725. }));
  92726. };
  92727. DefaultViewer.prototype.configureLights = function (lightsConfiguration, model) {
  92728. var _this = this;
  92729. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  92730. _super.prototype.configureLights.call(this, lightsConfiguration, model);
  92731. if (this.configuration.lab && this.configuration.lab.flashlight) {
  92732. var pointerPosition = BABYLON.Vector3.Zero();
  92733. var lightTarget_1;
  92734. var angle = 0.5;
  92735. var exponent = Math.PI / 2;
  92736. if (typeof this.configuration.lab.flashlight === "object") {
  92737. exponent = this.configuration.lab.flashlight.exponent || exponent;
  92738. angle = this.configuration.lab.flashlight.angle || angle;
  92739. }
  92740. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.scene);
  92741. if (typeof this.configuration.lab.flashlight === "object") {
  92742. flashlight.intensity = this.configuration.lab.flashlight.intensity || flashlight.intensity;
  92743. if (this.configuration.lab.flashlight.diffuse) {
  92744. flashlight.diffuse.r = this.configuration.lab.flashlight.diffuse.r;
  92745. flashlight.diffuse.g = this.configuration.lab.flashlight.diffuse.g;
  92746. flashlight.diffuse.b = this.configuration.lab.flashlight.diffuse.b;
  92747. }
  92748. if (this.configuration.lab.flashlight.specular) {
  92749. flashlight.specular.r = this.configuration.lab.flashlight.specular.r;
  92750. flashlight.specular.g = this.configuration.lab.flashlight.specular.g;
  92751. flashlight.specular.b = this.configuration.lab.flashlight.specular.b;
  92752. }
  92753. }
  92754. this.scene.constantlyUpdateMeshUnderPointer = true;
  92755. this.scene.onPointerObservable.add(function (eventData, eventState) {
  92756. if (eventData.type === 4 && eventData.pickInfo) {
  92757. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  92758. }
  92759. else {
  92760. lightTarget_1 = undefined;
  92761. }
  92762. });
  92763. var updateFlashlightFunction = function () {
  92764. if (_this.camera && flashlight) {
  92765. flashlight.position.copyFrom(_this.camera.position);
  92766. if (lightTarget_1) {
  92767. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  92768. }
  92769. }
  92770. };
  92771. this.scene.registerBeforeRender(updateFlashlightFunction);
  92772. this.registeredOnBeforerenderFunctions.push(updateFlashlightFunction);
  92773. }
  92774. };
  92775. return DefaultViewer;
  92776. }(viewer_1.AbstractViewer));
  92777. exports.DefaultViewer = DefaultViewer;
  92778. /***/ }),
  92779. /* 5 */
  92780. /***/ (function(module, exports, __webpack_require__) {
  92781. "use strict";
  92782. Object.defineProperty(exports, "__esModule", { value: true });
  92783. var viewerManager_1 = __webpack_require__(3);
  92784. var templateManager_1 = __webpack_require__(19);
  92785. var loader_1 = __webpack_require__(22);
  92786. var babylonjs_1 = __webpack_require__(0);
  92787. var deepmerge = __webpack_require__(13);
  92788. var viewerModel_1 = __webpack_require__(30);
  92789. var AbstractViewer = (function () {
  92790. function AbstractViewer(containerElement, initialConfiguration) {
  92791. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  92792. var _this = this;
  92793. this.containerElement = containerElement;
  92794. this.resize = function () {
  92795. if (!_this.isCanvasInDOM()) {
  92796. return;
  92797. }
  92798. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  92799. return;
  92800. }
  92801. _this.engine.resize();
  92802. };
  92803. this.render = function () {
  92804. _this.scene && _this.scene.activeCamera && _this.scene.render();
  92805. };
  92806. if (containerElement.id) {
  92807. this.baseId = containerElement.id;
  92808. }
  92809. else {
  92810. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  92811. }
  92812. this.onSceneInitObservable = new babylonjs_1.Observable();
  92813. this.onEngineInitObservable = new babylonjs_1.Observable();
  92814. this.onModelLoadedObservable = new babylonjs_1.Observable();
  92815. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  92816. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  92817. this.onInitDoneObservable = new babylonjs_1.Observable();
  92818. this.onLoaderInitObservable = new babylonjs_1.Observable();
  92819. this.registeredOnBeforerenderFunctions = [];
  92820. this.models = [];
  92821. viewerManager_1.viewerManager.addViewer(this);
  92822. this.templateManager = new templateManager_1.TemplateManager(containerElement);
  92823. this.prepareContainerElement();
  92824. loader_1.default.loadConfiguration(initialConfiguration, function (configuration) {
  92825. _this.configuration = deepmerge(_this.configuration || {}, configuration);
  92826. if (_this.configuration.observers) {
  92827. _this.configureObservers(_this.configuration.observers);
  92828. }
  92829. var templateConfiguration = _this.configuration.templates || {};
  92830. _this.templateManager.initTemplate(templateConfiguration);
  92831. _this.templateManager.onAllLoaded.add(function () {
  92832. var canvas = _this.templateManager.getCanvas();
  92833. if (canvas) {
  92834. _this.canvas = canvas;
  92835. }
  92836. _this._onTemplateLoaded();
  92837. });
  92838. });
  92839. }
  92840. Object.defineProperty(AbstractViewer.prototype, "isHdrSupported", {
  92841. get: function () {
  92842. return this._hdrSupport;
  92843. },
  92844. enumerable: true,
  92845. configurable: true
  92846. });
  92847. AbstractViewer.prototype.getBaseId = function () {
  92848. return this.baseId;
  92849. };
  92850. AbstractViewer.prototype.isCanvasInDOM = function () {
  92851. return !!this.canvas && !!this.canvas.parentElement;
  92852. };
  92853. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  92854. if (newConfiguration === void 0) { newConfiguration = this.configuration; }
  92855. this.configuration = deepmerge(this.configuration || {}, newConfiguration);
  92856. if (newConfiguration.scene) {
  92857. this.configureScene(newConfiguration.scene);
  92858. }
  92859. if (newConfiguration.optimizer) {
  92860. this.configureOptimizer(newConfiguration.optimizer);
  92861. }
  92862. if (newConfiguration.observers) {
  92863. this.configureObservers(newConfiguration.observers);
  92864. }
  92865. if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  92866. this.configureModel(newConfiguration.model);
  92867. }
  92868. if (newConfiguration.lights) {
  92869. this.configureLights(newConfiguration.lights);
  92870. }
  92871. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  92872. this.configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  92873. }
  92874. if (newConfiguration.camera) {
  92875. this.configureCamera(newConfiguration.camera);
  92876. }
  92877. };
  92878. AbstractViewer.prototype.configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  92879. if (!skyboxConifguration && !groundConfiguration) {
  92880. if (this.environmentHelper) {
  92881. this.environmentHelper.dispose();
  92882. delete this.environmentHelper;
  92883. }
  92884. ;
  92885. return Promise.resolve(this.scene);
  92886. }
  92887. var options = {
  92888. createGround: !!groundConfiguration,
  92889. createSkybox: !!skyboxConifguration,
  92890. setupImageProcessing: false
  92891. };
  92892. if (groundConfiguration) {
  92893. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  92894. var groundSize = groundConfig.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  92895. if (groundSize) {
  92896. options.groundSize = groundSize;
  92897. }
  92898. options.enableGroundShadow = groundConfig === true || groundConfig.receiveShadows;
  92899. if (groundConfig.shadowLevel !== undefined) {
  92900. options.groundShadowLevel = groundConfig.shadowLevel;
  92901. }
  92902. options.enableGroundMirror = !!groundConfig.mirror;
  92903. if (groundConfig.texture) {
  92904. options.groundTexture = groundConfig.texture;
  92905. }
  92906. if (groundConfig.color) {
  92907. options.groundColor = new babylonjs_1.Color3(groundConfig.color.r, groundConfig.color.g, groundConfig.color.b);
  92908. }
  92909. if (groundConfig.opacity !== undefined) {
  92910. options.groundOpacity = groundConfig.opacity;
  92911. }
  92912. if (groundConfig.mirror) {
  92913. options.enableGroundMirror = true;
  92914. if (typeof groundConfig.mirror === "object") {
  92915. if (groundConfig.mirror.amount !== undefined)
  92916. options.groundMirrorAmount = groundConfig.mirror.amount;
  92917. if (groundConfig.mirror.sizeRatio !== undefined)
  92918. options.groundMirrorSizeRatio = groundConfig.mirror.sizeRatio;
  92919. if (groundConfig.mirror.blurKernel !== undefined)
  92920. options.groundMirrorBlurKernel = groundConfig.mirror.blurKernel;
  92921. if (groundConfig.mirror.fresnelWeight !== undefined)
  92922. options.groundMirrorFresnelWeight = groundConfig.mirror.fresnelWeight;
  92923. if (groundConfig.mirror.fallOffDistance !== undefined)
  92924. options.groundMirrorFallOffDistance = groundConfig.mirror.fallOffDistance;
  92925. if (this.defaultPipelineTextureType !== undefined)
  92926. options.groundMirrorTextureType = this.defaultPipelineTextureType;
  92927. }
  92928. }
  92929. }
  92930. var postInitSkyboxMaterial = false;
  92931. if (skyboxConifguration) {
  92932. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  92933. if (conf.material && conf.material.imageProcessingConfiguration) {
  92934. options.setupImageProcessing = false;
  92935. }
  92936. var skyboxSize = conf.scale;
  92937. if (skyboxSize) {
  92938. options.skyboxSize = skyboxSize;
  92939. }
  92940. options.sizeAuto = !options.skyboxSize;
  92941. if (conf.color) {
  92942. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  92943. }
  92944. if (conf.cubeTexture && conf.cubeTexture.url) {
  92945. if (typeof conf.cubeTexture.url === "string") {
  92946. options.skyboxTexture = conf.cubeTexture.url;
  92947. }
  92948. else {
  92949. postInitSkyboxMaterial = true;
  92950. }
  92951. }
  92952. if (conf.material && conf.material.imageProcessingConfiguration) {
  92953. postInitSkyboxMaterial = true;
  92954. }
  92955. }
  92956. options.setupImageProcessing = false;
  92957. if (!this.environmentHelper) {
  92958. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  92959. }
  92960. else {
  92961. var scene = this.environmentHelper.rootMesh.getScene();
  92962. if (scene !== this.scene) {
  92963. this.environmentHelper.dispose();
  92964. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  92965. }
  92966. else {
  92967. this.environmentHelper.updateOptions(options);
  92968. }
  92969. }
  92970. if (postInitSkyboxMaterial) {
  92971. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  92972. if (skyboxMaterial) {
  92973. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material && skyboxConifguration.material.imageProcessingConfiguration) {
  92974. this.extendClassWithConfig(skyboxMaterial.imageProcessingConfiguration, skyboxConifguration.material.imageProcessingConfiguration);
  92975. }
  92976. }
  92977. }
  92978. };
  92979. AbstractViewer.prototype.configureScene = function (sceneConfig, optimizerConfig) {
  92980. if (!this.scene) {
  92981. return;
  92982. }
  92983. if (sceneConfig.debug) {
  92984. this.scene.debugLayer.show();
  92985. }
  92986. else {
  92987. if (this.scene.debugLayer.isVisible()) {
  92988. this.scene.debugLayer.hide();
  92989. }
  92990. }
  92991. if (sceneConfig.clearColor) {
  92992. var cc = sceneConfig.clearColor;
  92993. var oldcc = this.scene.clearColor;
  92994. if (cc.r !== undefined) {
  92995. oldcc.r = cc.r;
  92996. }
  92997. if (cc.g !== undefined) {
  92998. oldcc.g = cc.g;
  92999. }
  93000. if (cc.b !== undefined) {
  93001. oldcc.b = cc.b;
  93002. }
  93003. if (cc.a !== undefined) {
  93004. oldcc.a = cc.a;
  93005. }
  93006. }
  93007. if (sceneConfig.imageProcessingConfiguration) {
  93008. this.extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  93009. }
  93010. if (sceneConfig.environmentTexture) {
  93011. if (this.scene.environmentTexture) {
  93012. this.scene.environmentTexture.dispose();
  93013. }
  93014. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  93015. this.scene.environmentTexture = environmentTexture;
  93016. }
  93017. if (sceneConfig.autoRotate) {
  93018. this.camera.useAutoRotationBehavior = true;
  93019. }
  93020. };
  93021. AbstractViewer.prototype.configureOptimizer = function (optimizerConfig) {
  93022. if (typeof optimizerConfig === 'boolean') {
  93023. if (this.sceneOptimizer) {
  93024. this.sceneOptimizer.stop();
  93025. this.sceneOptimizer.dispose();
  93026. delete this.sceneOptimizer;
  93027. }
  93028. if (optimizerConfig) {
  93029. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  93030. this.sceneOptimizer.start();
  93031. }
  93032. }
  93033. else {
  93034. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  93035. if (optimizerConfig.degradation) {
  93036. switch (optimizerConfig.degradation) {
  93037. case "low":
  93038. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  93039. break;
  93040. case "moderate":
  93041. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  93042. break;
  93043. case "hight":
  93044. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  93045. break;
  93046. }
  93047. }
  93048. if (this.sceneOptimizer) {
  93049. this.sceneOptimizer.stop();
  93050. this.sceneOptimizer.dispose();
  93051. }
  93052. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  93053. this.sceneOptimizer.start();
  93054. }
  93055. };
  93056. AbstractViewer.prototype.configureObservers = function (observersConfiguration) {
  93057. if (observersConfiguration.onEngineInit) {
  93058. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  93059. }
  93060. else {
  93061. if (observersConfiguration.onEngineInit === '' && this.configuration.observers && this.configuration.observers.onEngineInit) {
  93062. this.onEngineInitObservable.removeCallback(window[this.configuration.observers.onEngineInit]);
  93063. }
  93064. }
  93065. if (observersConfiguration.onSceneInit) {
  93066. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  93067. }
  93068. else {
  93069. if (observersConfiguration.onSceneInit === '' && this.configuration.observers && this.configuration.observers.onSceneInit) {
  93070. this.onSceneInitObservable.removeCallback(window[this.configuration.observers.onSceneInit]);
  93071. }
  93072. }
  93073. if (observersConfiguration.onModelLoaded) {
  93074. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  93075. }
  93076. else {
  93077. if (observersConfiguration.onModelLoaded === '' && this.configuration.observers && this.configuration.observers.onModelLoaded) {
  93078. this.onModelLoadedObservable.removeCallback(window[this.configuration.observers.onModelLoaded]);
  93079. }
  93080. }
  93081. };
  93082. AbstractViewer.prototype.configureCamera = function (cameraConfig, model) {
  93083. var _this = this;
  93084. var focusMeshes = model ? model.meshes : this.scene.meshes;
  93085. if (!this.scene.activeCamera) {
  93086. this.scene.createDefaultCamera(true, true, true);
  93087. this.camera = this.scene.activeCamera;
  93088. }
  93089. if (cameraConfig.position) {
  93090. this.camera.position.copyFromFloats(cameraConfig.position.x || 0, cameraConfig.position.y || 0, cameraConfig.position.z || 0);
  93091. }
  93092. if (cameraConfig.rotation) {
  93093. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  93094. }
  93095. this.extendClassWithConfig(this.camera, cameraConfig);
  93096. this.camera.minZ = cameraConfig.minZ || this.camera.minZ;
  93097. this.camera.maxZ = cameraConfig.maxZ || this.camera.maxZ;
  93098. if (cameraConfig.behaviors) {
  93099. for (var name_1 in cameraConfig.behaviors) {
  93100. this.setCameraBehavior(cameraConfig.behaviors[name_1], focusMeshes);
  93101. }
  93102. }
  93103. ;
  93104. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  93105. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  93106. });
  93107. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  93108. var sceneDiagonalLenght = sceneDiagonal.length();
  93109. if (isFinite(sceneDiagonalLenght))
  93110. this.camera.upperRadiusLimit = sceneDiagonalLenght * 3;
  93111. };
  93112. AbstractViewer.prototype.configureLights = function (lightsConfiguration, model) {
  93113. var _this = this;
  93114. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  93115. var focusMeshes = model ? model.meshes : this.scene.meshes;
  93116. if (!Object.keys(lightsConfiguration).length)
  93117. return;
  93118. var lightsAvailable = this.scene.lights.map(function (light) { return light.name; });
  93119. var lightsToConfigure = Object.keys(this.configuration.lights || []);
  93120. if (Object.keys(lightsToConfigure).length !== lightsAvailable.length) {
  93121. lightsAvailable.forEach(function (lName) {
  93122. if (lightsToConfigure.indexOf(lName) === -1) {
  93123. _this.scene.getLightByName(lName).dispose();
  93124. }
  93125. });
  93126. }
  93127. Object.keys(lightsConfiguration).forEach(function (name, idx) {
  93128. var lightConfig = { type: 0 };
  93129. if (typeof lightsConfiguration[name] === 'object') {
  93130. lightConfig = lightsConfiguration[name];
  93131. }
  93132. lightConfig.name = name;
  93133. var light;
  93134. if (lightsAvailable.indexOf(name) === -1) {
  93135. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  93136. if (!constructor)
  93137. return;
  93138. light = constructor();
  93139. }
  93140. else {
  93141. light = _this.scene.getLightByName(name);
  93142. lightsAvailable = lightsAvailable.filter(function (ln) { return ln !== name; });
  93143. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  93144. light.dispose();
  93145. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  93146. if (!constructor)
  93147. return;
  93148. light = constructor();
  93149. }
  93150. }
  93151. if (lightsConfiguration[name] === false) {
  93152. light.dispose();
  93153. return;
  93154. }
  93155. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  93156. light.setEnabled(enabled);
  93157. _this.extendClassWithConfig(light, lightConfig);
  93158. if (light instanceof babylonjs_1.ShadowLight) {
  93159. if (lightConfig.target) {
  93160. if (light.setDirectionToTarget) {
  93161. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  93162. light.setDirectionToTarget(target);
  93163. }
  93164. }
  93165. else if (lightConfig.direction) {
  93166. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  93167. light.direction = direction;
  93168. }
  93169. var shadowGenerator = light.getShadowGenerator();
  93170. if (lightConfig.shadowEnabled && _this.maxShadows) {
  93171. if (!shadowGenerator) {
  93172. shadowGenerator = new babylonjs_1.ShadowGenerator(512, light);
  93173. }
  93174. _this.extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  93175. var shadownMap = shadowGenerator.getShadowMap();
  93176. if (!shadownMap)
  93177. return;
  93178. var renderList = shadownMap.renderList;
  93179. for (var index = 0; index < focusMeshes.length; index++) {
  93180. if (babylonjs_1.Tags.MatchesQuery(focusMeshes[index], 'castShadow')) {
  93181. renderList && renderList.push(focusMeshes[index]);
  93182. }
  93183. }
  93184. }
  93185. else if (shadowGenerator) {
  93186. shadowGenerator.dispose();
  93187. }
  93188. }
  93189. });
  93190. };
  93191. AbstractViewer.prototype.configureModel = function (modelConfiguration, model) {
  93192. var focusMeshes = model ? model.meshes : this.scene.meshes;
  93193. var meshesWithNoParent = focusMeshes.filter(function (m) { return !m.parent; });
  93194. var updateMeshesWithNoParent = function (variable, value, param) {
  93195. meshesWithNoParent.forEach(function (mesh) {
  93196. if (param) {
  93197. mesh[variable][param] = value;
  93198. }
  93199. else {
  93200. mesh[variable] = value;
  93201. }
  93202. });
  93203. };
  93204. var updateXYZ = function (variable, configValues) {
  93205. if (configValues.x !== undefined) {
  93206. updateMeshesWithNoParent(variable, configValues.x, 'x');
  93207. }
  93208. if (configValues.y !== undefined) {
  93209. updateMeshesWithNoParent(variable, configValues.y, 'y');
  93210. }
  93211. if (configValues.z !== undefined) {
  93212. updateMeshesWithNoParent(variable, configValues.z, 'z');
  93213. }
  93214. if (configValues.w !== undefined) {
  93215. updateMeshesWithNoParent(variable, configValues.w, 'w');
  93216. }
  93217. };
  93218. if (modelConfiguration.position) {
  93219. updateXYZ('position', modelConfiguration.position);
  93220. }
  93221. if (modelConfiguration.rotation) {
  93222. if (modelConfiguration.rotation.w) {
  93223. meshesWithNoParent.forEach(function (mesh) {
  93224. if (!mesh.rotationQuaternion) {
  93225. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  93226. }
  93227. });
  93228. updateXYZ('rotationQuaternion', modelConfiguration.rotation);
  93229. }
  93230. else {
  93231. updateXYZ('rotation', modelConfiguration.rotation);
  93232. }
  93233. }
  93234. if (modelConfiguration.scaling) {
  93235. updateXYZ('scaling', modelConfiguration.scaling);
  93236. }
  93237. if (modelConfiguration.castShadow) {
  93238. focusMeshes.forEach(function (mesh) {
  93239. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  93240. });
  93241. }
  93242. if (modelConfiguration.normalize) {
  93243. var center = false;
  93244. var unitSize = false;
  93245. var parentIndex = void 0;
  93246. if (modelConfiguration.normalize === true) {
  93247. center = true;
  93248. unitSize = true;
  93249. parentIndex = 0;
  93250. }
  93251. else {
  93252. center = !!modelConfiguration.normalize.center;
  93253. unitSize = !!modelConfiguration.normalize.unitSize;
  93254. parentIndex = modelConfiguration.normalize.parentIndex;
  93255. }
  93256. var meshesToNormalize = [];
  93257. if (parentIndex !== undefined) {
  93258. meshesToNormalize.push(focusMeshes[parentIndex]);
  93259. }
  93260. else {
  93261. meshesToNormalize = meshesWithNoParent;
  93262. }
  93263. if (unitSize) {
  93264. meshesToNormalize.forEach(function (mesh) {
  93265. mesh.normalizeToUnitCube(true);
  93266. mesh.computeWorldMatrix(true);
  93267. });
  93268. }
  93269. if (center) {
  93270. meshesToNormalize.forEach(function (mesh) {
  93271. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  93272. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  93273. var halfSizeVec = sizeVec.scale(0.5);
  93274. var center = boundingInfo.min.add(halfSizeVec);
  93275. mesh.position = center.scale(-1);
  93276. mesh.position.y += halfSizeVec.y;
  93277. mesh.computeWorldMatrix(true);
  93278. });
  93279. }
  93280. }
  93281. };
  93282. AbstractViewer.prototype.dispose = function () {
  93283. window.removeEventListener('resize', this.resize);
  93284. if (this.sceneOptimizer) {
  93285. this.sceneOptimizer.stop();
  93286. this.sceneOptimizer.dispose();
  93287. }
  93288. if (this.scene.activeCamera) {
  93289. this.scene.activeCamera.detachControl(this.canvas);
  93290. }
  93291. this.scene.dispose();
  93292. this.engine.dispose();
  93293. this.templateManager.dispose();
  93294. };
  93295. AbstractViewer.prototype.onTemplatesLoaded = function () {
  93296. return Promise.resolve(this);
  93297. };
  93298. AbstractViewer.prototype._onTemplateLoaded = function () {
  93299. var _this = this;
  93300. return this.onTemplatesLoaded().then(function () {
  93301. var autoLoadModel = !!_this.configuration.model;
  93302. return _this.initEngine().then(function (engine) {
  93303. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  93304. }).then(function () {
  93305. if (autoLoadModel) {
  93306. return _this.loadModel().then(function () { return _this.scene; });
  93307. }
  93308. else {
  93309. return _this.scene || _this.initScene();
  93310. }
  93311. }).then(function (scene) {
  93312. return _this.onSceneInitObservable.notifyObserversWithPromise(scene);
  93313. }).then(function () {
  93314. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  93315. });
  93316. });
  93317. };
  93318. AbstractViewer.prototype.initEngine = function () {
  93319. this.injectCustomShaders();
  93320. var canvasElement = this.templateManager.getCanvas();
  93321. if (!canvasElement) {
  93322. return Promise.reject('Canvas element not found!');
  93323. }
  93324. var config = this.configuration.engine || {};
  93325. this.engine = new babylonjs_1.Engine(canvasElement, !!config.antialiasing, config.engineOptions);
  93326. babylonjs_1.Database.IDBStorageEnabled = false;
  93327. if (!config.disableResize) {
  93328. window.addEventListener('resize', this.resize);
  93329. }
  93330. this.engine.runRenderLoop(this.render);
  93331. if (this.configuration.engine && this.configuration.engine.adaptiveQuality) {
  93332. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  93333. this.engine.setHardwareScalingLevel(scale);
  93334. }
  93335. this.handleHardwareLimitations();
  93336. return Promise.resolve(this.engine);
  93337. };
  93338. AbstractViewer.prototype.initScene = function () {
  93339. if (this.scene) {
  93340. this.scene.dispose();
  93341. }
  93342. this.scene = new babylonjs_1.Scene(this.engine);
  93343. this.scene.createDefaultLight(true);
  93344. if (this.configuration.scene) {
  93345. this.configureScene(this.configuration.scene);
  93346. if (this.configuration.optimizer) {
  93347. this.configureOptimizer(this.configuration.optimizer);
  93348. }
  93349. }
  93350. return Promise.resolve(this.scene);
  93351. };
  93352. AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) {
  93353. var _this = this;
  93354. if (modelConfig === void 0) { modelConfig = this.configuration.model; }
  93355. if (clearScene === void 0) { clearScene = true; }
  93356. var modelUrl = (typeof modelConfig === 'string') ? modelConfig : modelConfig.url;
  93357. if (!modelUrl) {
  93358. return Promise.reject("no model configuration found");
  93359. }
  93360. if (this.isLoading) {
  93361. return Promise.reject("sanother model is curently being loaded.");
  93362. }
  93363. this.isLoading = true;
  93364. if ((typeof modelConfig === 'string')) {
  93365. if (this.configuration.model && typeof this.configuration.model === 'object') {
  93366. this.configuration.model.url = modelConfig;
  93367. }
  93368. }
  93369. else {
  93370. if (this.configuration.model) {
  93371. deepmerge(this.configuration.model, modelConfig);
  93372. }
  93373. else {
  93374. this.configuration.model = modelConfig;
  93375. }
  93376. }
  93377. return Promise.resolve(this.scene).then(function (scene) {
  93378. if (!scene)
  93379. return _this.initScene();
  93380. if (clearScene) {
  93381. _this.models.forEach(function (m) { return m.dispose(); });
  93382. _this.models.length = 0;
  93383. }
  93384. return scene;
  93385. }).then(function () {
  93386. return new Promise(function (resolve, reject) {
  93387. var model = new viewerModel_1.ViewerModel(_this.configuration.model, _this.scene);
  93388. _this.models.push(model);
  93389. _this.lastUsedLoader = model.loader;
  93390. model.onLoadedObservable.add(function (model) {
  93391. resolve(model);
  93392. });
  93393. model.onLoadErrorObservable.add(function (errorObject) {
  93394. _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject).then(function () {
  93395. reject(errorObject.exception);
  93396. });
  93397. });
  93398. model.onLoadProgressObservable.add(function (progressEvent) {
  93399. return _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  93400. });
  93401. _this.onLoaderInitObservable.notifyObserversWithPromise(_this.lastUsedLoader);
  93402. });
  93403. }).then(function (model) {
  93404. return _this.onModelLoadedObservable.notifyObserversWithPromise(model)
  93405. .then(function () {
  93406. _this.configureModel(_this.configuration.model || modelConfig, model);
  93407. _this.configureLights(_this.configuration.lights);
  93408. if (_this.configuration.camera) {
  93409. _this.configureCamera(_this.configuration.camera, model);
  93410. }
  93411. return _this.initEnvironment(model);
  93412. }).then(function () {
  93413. _this.isLoading = false;
  93414. return model;
  93415. });
  93416. });
  93417. };
  93418. AbstractViewer.prototype.initEnvironment = function (model) {
  93419. this.configureEnvironment(this.configuration.skybox, this.configuration.ground);
  93420. return Promise.resolve(this.scene);
  93421. };
  93422. AbstractViewer.prototype.handleHardwareLimitations = function () {
  93423. var maxVaryingRows = this.engine.getCaps().maxVaryingVectors;
  93424. var maxFragmentSamplers = this.engine.getCaps().maxTexturesImageUnits;
  93425. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  93426. this.maxShadows = 0;
  93427. }
  93428. else {
  93429. this.maxShadows = 3;
  93430. }
  93431. var caps = this.engine.getCaps();
  93432. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  93433. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  93434. this._hdrSupport = !!(linearFloatTargets || linearHalfFloatTargets);
  93435. if (linearHalfFloatTargets) {
  93436. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  93437. this.shadowGeneratorBias = 0.002;
  93438. }
  93439. else if (linearFloatTargets) {
  93440. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  93441. this.shadowGeneratorBias = 0.001;
  93442. }
  93443. else {
  93444. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  93445. this.shadowGeneratorBias = 0.001;
  93446. }
  93447. this.defaultPipelineTextureType = this._hdrSupport ? this.defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  93448. };
  93449. AbstractViewer.prototype.injectCustomShaders = function () {
  93450. var customShaders = this.configuration.customShaders;
  93451. if (!customShaders) {
  93452. return;
  93453. }
  93454. if (customShaders.shaders) {
  93455. Object.keys(customShaders.shaders).forEach(function (key) {
  93456. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  93457. });
  93458. }
  93459. if (customShaders.includes) {
  93460. Object.keys(customShaders.includes).forEach(function (key) {
  93461. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  93462. });
  93463. }
  93464. };
  93465. AbstractViewer.prototype.extendClassWithConfig = function (object, config) {
  93466. var _this = this;
  93467. if (!config)
  93468. return;
  93469. Object.keys(config).forEach(function (key) {
  93470. if (key in object && typeof object[key] !== 'function') {
  93471. if (typeof object[key] === 'object') {
  93472. _this.extendClassWithConfig(object[key], config[key]);
  93473. }
  93474. else {
  93475. if (config[key] !== undefined) {
  93476. object[key] = config[key];
  93477. }
  93478. }
  93479. }
  93480. });
  93481. };
  93482. AbstractViewer.prototype.setCameraBehavior = function (behaviorConfig, payload) {
  93483. var behavior;
  93484. var type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  93485. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  93486. switch (type) {
  93487. case 0:
  93488. this.camera.useAutoRotationBehavior = true;
  93489. behavior = this.camera.autoRotationBehavior;
  93490. break;
  93491. case 1:
  93492. this.camera.useBouncingBehavior = true;
  93493. behavior = this.camera.bouncingBehavior;
  93494. break;
  93495. case 2:
  93496. this.camera.useFramingBehavior = true;
  93497. behavior = this.camera.framingBehavior;
  93498. break;
  93499. default:
  93500. behavior = null;
  93501. break;
  93502. }
  93503. if (behavior) {
  93504. if (typeof behaviorConfig === "object") {
  93505. this.extendClassWithConfig(behavior, behaviorConfig);
  93506. }
  93507. }
  93508. switch (type) {
  93509. case 0:
  93510. break;
  93511. case 1:
  93512. break;
  93513. case 2:
  93514. if (config.zoomOnBoundingInfo) {
  93515. var meshes = payload;
  93516. var bounding = meshes[0].getHierarchyBoundingVectors();
  93517. behavior.zoomOnBoundingInfo(bounding.min, bounding.max);
  93518. }
  93519. break;
  93520. }
  93521. };
  93522. return AbstractViewer;
  93523. }());
  93524. exports.AbstractViewer = AbstractViewer;
  93525. /***/ }),
  93526. /* 6 */
  93527. /***/ (function(module, exports) {
  93528. module.exports = "<viewer></viewer> <loading-screen></loading-screen> <overlay></overlay>";
  93529. /***/ }),
  93530. /* 7 */
  93531. /***/ (function(module, exports) {
  93532. 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}}>";
  93533. /***/ }),
  93534. /* 8 */
  93535. /***/ (function(module, exports) {
  93536. 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=="
  93537. /***/ }),
  93538. /* 9 */
  93539. /***/ (function(module, exports) {
  93540. 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>";
  93541. /***/ }),
  93542. /* 10 */
  93543. /***/ (function(module, exports) {
  93544. 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>";
  93545. /***/ }),
  93546. /* 11 */
  93547. /***/ (function(module, exports) {
  93548. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  93549. /***/ }),
  93550. /* 12 */
  93551. /***/ (function(module, exports) {
  93552. module.exports = "Error loading the model";
  93553. /***/ }),
  93554. /* 13 */
  93555. /***/ (function(module, exports, __webpack_require__) {
  93556. (function (global, factory) {
  93557. true ? module.exports = factory() :
  93558. typeof define === 'function' && define.amd ? define(factory) :
  93559. (global.deepmerge = factory());
  93560. }(this, (function () { 'use strict';
  93561. var isMergeableObject = function isMergeableObject(value) {
  93562. return isNonNullObject(value)
  93563. && !isSpecial(value)
  93564. };
  93565. function isNonNullObject(value) {
  93566. return !!value && typeof value === 'object'
  93567. }
  93568. function isSpecial(value) {
  93569. var stringValue = Object.prototype.toString.call(value);
  93570. return stringValue === '[object RegExp]'
  93571. || stringValue === '[object Date]'
  93572. || isReactElement(value)
  93573. }
  93574. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  93575. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  93576. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  93577. function isReactElement(value) {
  93578. return value.$$typeof === REACT_ELEMENT_TYPE
  93579. }
  93580. function emptyTarget(val) {
  93581. return Array.isArray(val) ? [] : {}
  93582. }
  93583. function cloneUnlessOtherwiseSpecified(value, optionsArgument) {
  93584. var clone = !optionsArgument || optionsArgument.clone !== false;
  93585. return (clone && isMergeableObject(value))
  93586. ? deepmerge(emptyTarget(value), value, optionsArgument)
  93587. : value
  93588. }
  93589. function defaultArrayMerge(target, source, optionsArgument) {
  93590. return target.concat(source).map(function(element) {
  93591. return cloneUnlessOtherwiseSpecified(element, optionsArgument)
  93592. })
  93593. }
  93594. function mergeObject(target, source, optionsArgument) {
  93595. var destination = {};
  93596. if (isMergeableObject(target)) {
  93597. Object.keys(target).forEach(function(key) {
  93598. destination[key] = cloneUnlessOtherwiseSpecified(target[key], optionsArgument);
  93599. });
  93600. }
  93601. Object.keys(source).forEach(function(key) {
  93602. if (!isMergeableObject(source[key]) || !target[key]) {
  93603. destination[key] = cloneUnlessOtherwiseSpecified(source[key], optionsArgument);
  93604. } else {
  93605. destination[key] = deepmerge(target[key], source[key], optionsArgument);
  93606. }
  93607. });
  93608. return destination
  93609. }
  93610. function deepmerge(target, source, optionsArgument) {
  93611. var sourceIsArray = Array.isArray(source);
  93612. var targetIsArray = Array.isArray(target);
  93613. var options = optionsArgument || { arrayMerge: defaultArrayMerge };
  93614. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  93615. if (!sourceAndTargetTypesMatch) {
  93616. return cloneUnlessOtherwiseSpecified(source, optionsArgument)
  93617. } else if (sourceIsArray) {
  93618. var arrayMerge = options.arrayMerge || defaultArrayMerge;
  93619. return arrayMerge(target, source, optionsArgument)
  93620. } else {
  93621. return mergeObject(target, source, optionsArgument)
  93622. }
  93623. }
  93624. deepmerge.all = function deepmergeAll(array, optionsArgument) {
  93625. if (!Array.isArray(array)) {
  93626. throw new Error('first argument should be an array')
  93627. }
  93628. return array.reduce(function(prev, next) {
  93629. return deepmerge(prev, next, optionsArgument)
  93630. }, {})
  93631. };
  93632. var deepmerge_1 = deepmerge;
  93633. return deepmerge_1;
  93634. })));
  93635. /***/ }),
  93636. /* 14 */
  93637. /***/ (function(module, exports, __webpack_require__) {
  93638. module.exports = __webpack_require__(15);
  93639. /***/ }),
  93640. /* 15 */
  93641. /***/ (function(module, exports, __webpack_require__) {
  93642. "use strict";
  93643. Object.defineProperty(exports, "__esModule", { value: true });
  93644. var mappers_1 = __webpack_require__(1);
  93645. exports.mapperManager = mappers_1.mapperManager;
  93646. var viewerManager_1 = __webpack_require__(3);
  93647. exports.viewerManager = viewerManager_1.viewerManager;
  93648. var defaultViewer_1 = __webpack_require__(4);
  93649. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  93650. var viewer_1 = __webpack_require__(5);
  93651. exports.AbstractViewer = viewer_1.AbstractViewer;
  93652. var babylonjs_1 = __webpack_require__(0);
  93653. __webpack_require__(32);
  93654. __webpack_require__(33);
  93655. var initializer_1 = __webpack_require__(34);
  93656. exports.InitTags = initializer_1.InitTags;
  93657. babylonjs_1.PromisePolyfill.Apply();
  93658. exports.disableInit = false;
  93659. document.addEventListener("DOMContentLoaded", function (event) {
  93660. if (exports.disableInit)
  93661. return;
  93662. initializer_1.InitTags();
  93663. });
  93664. /***/ }),
  93665. /* 16 */
  93666. /***/ (function(module, exports) {
  93667. var g;
  93668. // This works in non-strict mode
  93669. g = (function() {
  93670. return this;
  93671. })();
  93672. try {
  93673. // This works if eval is allowed (see CSP)
  93674. g = g || Function("return this")() || (1,eval)("this");
  93675. } catch(e) {
  93676. // This works if the window reference is available
  93677. if(typeof window === "object")
  93678. g = window;
  93679. }
  93680. // g can still be undefined, but nothing to do about it...
  93681. // We return undefined, instead of nothing here, so it's
  93682. // easier to handle this case. if(!global) { ...}
  93683. module.exports = g;
  93684. /***/ }),
  93685. /* 17 */
  93686. /***/ (function(module, exports) {
  93687. module.exports = cannon;
  93688. /***/ }),
  93689. /* 18 */
  93690. /***/ (function(module, exports, __webpack_require__) {
  93691. /**
  93692. * from OimoPhysics DEV 1.1.0a AS3
  93693. * @author Saharan / http://el-ement.com/
  93694. *
  93695. * to Oimo.js 2015 JAVASCRIPT
  93696. * @author LoTh / http://lo-th.github.io/labs/
  93697. */
  93698. var OIMO = {
  93699. REVISION: "1.2",
  93700. // Global identification of next shape.
  93701. // This will be incremented every time a shape is created.
  93702. nextID: 0,
  93703. proxyID: 0,
  93704. // BroadPhase
  93705. BR_NULL: 0,
  93706. BR_BRUTE_FORCE: 1,
  93707. BR_SWEEP_AND_PRUNE: 2,
  93708. BR_BOUNDING_VOLUME_TREE: 3,
  93709. // body type
  93710. BODY_NULL: 0,
  93711. BODY_DYNAMIC: 1,
  93712. BODY_STATIC: 2,
  93713. // shape type
  93714. SHAPE_NULL: 0,
  93715. SHAPE_SPHERE: 1,
  93716. SHAPE_BOX: 2,
  93717. SHAPE_CYLINDER: 3,
  93718. SHAPE_TETRA: 4,
  93719. // joint type
  93720. JOINT_NULL: 0,
  93721. JOINT_DISTANCE: 1,
  93722. JOINT_BALL_AND_SOCKET: 2,
  93723. JOINT_HINGE: 3,
  93724. JOINT_WHEEL: 4,
  93725. JOINT_SLIDER: 5,
  93726. JOINT_PRISMATIC: 6,
  93727. // this world scale defaut is 0.1 to 10 meters max for dynamique body
  93728. // scale all by 100 so object is between 10 to 10000 three unit.
  93729. WORLD_SCALE: 100,
  93730. INV_SCALE: 0.01,
  93731. // AABB aproximation
  93732. AABB_PROX: 0.005,
  93733. // Math function
  93734. sqrt: Math.sqrt,
  93735. abs: Math.abs,
  93736. floor: Math.floor,
  93737. cos: Math.cos,
  93738. sin: Math.sin,
  93739. acos: Math.acos,
  93740. asin: Math.asin,
  93741. atan2: Math.atan2,
  93742. round: Math.round,
  93743. pow: Math.pow,
  93744. max: Math.max,
  93745. min: Math.min,
  93746. random: Math.random,
  93747. lerp: function (a, b, percent) { return a + (b - a) * percent; },
  93748. rand: function (a, b) { return OIMO.lerp(a, b, OIMO.random()); },
  93749. randInt: function (a, b, n) { return OIMO.lerp(a, b, OIMO.random()).toFixed(n || 0) * 1; },
  93750. int: function (x) { return ~~x; },
  93751. fix: function (x, n) { return x.toFixed(n || 3, 10); },
  93752. clamp: function (value, min, max) { return OIMO.max(min, OIMO.min(max, value)); },
  93753. degtorad: 0.0174532925199432957,
  93754. radtodeg: 57.295779513082320876,
  93755. PI: 3.141592653589793,
  93756. TwoPI: 6.283185307179586,
  93757. PI90: 1.570796326794896,
  93758. PI270: 4.712388980384689,
  93759. CustomError: null,
  93760. Error: function (Class, Msg) {
  93761. if (OIMO.CustomError == null) console.error(Class, Msg);
  93762. else OIMO.CustomError.innerHTML += Class + " - " + Msg + '<br>';
  93763. }
  93764. };
  93765. var OIMO_ARRAY_TYPE;
  93766. if (!OIMO_ARRAY_TYPE) { OIMO_ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array; }
  93767. try {
  93768. (function (w) {
  93769. var perfNow;
  93770. var perfNowNames = ['now', 'webkitNow', 'msNow', 'mozNow'];
  93771. if (!!w['performance']) for (var i = 0; i < perfNowNames.length; ++i) {
  93772. var n = perfNowNames[i];
  93773. if (!!w['performance'][n]) {
  93774. perfNow = function () { return w['performance'][n]() };
  93775. break;
  93776. }
  93777. }
  93778. if (!perfNow) perfNow = Date.now;
  93779. //w.perfNow = perfNow;
  93780. OIMO.now = perfNow;
  93781. })(window);
  93782. } catch (e) { OIMO.now = function () { return 0; }; }
  93783. /**
  93784. * The class of physical computing world.
  93785. * You must be added to the world physical all computing objects
  93786. * @author saharan
  93787. * @author lo-th
  93788. */
  93789. OIMO.World = function (TimeStep, BroadPhaseType, Iterations, NoStat) {
  93790. // The time between each step
  93791. this.timeStep = TimeStep || 0.01666; // 1/60;
  93792. // The number of iterations for constraint solvers.
  93793. this.numIterations = Iterations || 8;
  93794. // It is a wide-area collision judgment that is used in order to reduce as much as possible a detailed collision judgment.
  93795. switch (BroadPhaseType || 2) {
  93796. case 1: this.broadPhase = new OIMO.BruteForceBroadPhase(); break;
  93797. case 2: default: this.broadPhase = new OIMO.SAPBroadPhase(); break;
  93798. case 3: this.broadPhase = new OIMO.DBVTBroadPhase(); break;
  93799. }
  93800. // This is the detailed information of the performance.
  93801. this.performance = null;
  93802. this.isNoStat = NoStat || false;
  93803. if (!this.isNoStat) this.performance = new OIMO.Performance(this);
  93804. // Whether the constraints randomizer is enabled or not.
  93805. this.enableRandomizer = true;
  93806. // The rigid body list
  93807. this.rigidBodies = null;
  93808. // number of rigid body
  93809. this.numRigidBodies = 0;
  93810. // The contact list
  93811. this.contacts = null;
  93812. this.unusedContacts = null;
  93813. // The number of contact
  93814. this.numContacts = 0;
  93815. // The number of contact points
  93816. this.numContactPoints = 0;
  93817. // The joint list
  93818. this.joints = null;
  93819. // The number of joints.
  93820. this.numJoints = 0;
  93821. // The number of simulation islands.
  93822. this.numIslands = 0;
  93823. // The gravity in the world.
  93824. this.gravity = new OIMO.Vec3(0, -9.80665, 0);
  93825. var numShapeTypes = 5;//4;//3;
  93826. this.detectors = [];
  93827. this.detectors.length = numShapeTypes;
  93828. var i = numShapeTypes;
  93829. while (i--) {
  93830. this.detectors[i] = [];
  93831. this.detectors[i].length = numShapeTypes;
  93832. }
  93833. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_SPHERE] = new OIMO.SphereSphereCollisionDetector();
  93834. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_BOX] = new OIMO.SphereBoxCollisionDetector(false);
  93835. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_SPHERE] = new OIMO.SphereBoxCollisionDetector(true);
  93836. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_BOX] = new OIMO.BoxBoxCollisionDetector();
  93837. // CYLINDER add
  93838. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_CYLINDER] = new OIMO.CylinderCylinderCollisionDetector();
  93839. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_BOX] = new OIMO.BoxCylinderCollisionDetector(true);
  93840. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_CYLINDER] = new OIMO.BoxCylinderCollisionDetector(false);
  93841. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_SPHERE] = new OIMO.SphereCylinderCollisionDetector(true);
  93842. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_CYLINDER] = new OIMO.SphereCylinderCollisionDetector(false);
  93843. // TETRA add
  93844. this.detectors[OIMO.SHAPE_TETRA][OIMO.SHAPE_TETRA] = new OIMO.TetraTetraCollisionDetector();
  93845. this.randX = 65535;
  93846. this.randA = 98765;
  93847. this.randB = 123456789;
  93848. //this.maxIslandRigidBodies = 64;
  93849. this.islandRigidBodies = [];
  93850. //this.islandRigidBodies.length = this.maxIslandRigidBodies;
  93851. this.islandStack = [];
  93852. //this.islandStack.length = this.maxIslandRigidBodies;
  93853. //this.maxIslandConstraints = 128;
  93854. this.islandConstraints = [];
  93855. //this.islandConstraints.length = this.maxIslandConstraints;
  93856. };
  93857. OIMO.World.prototype = {
  93858. constructor: OIMO.World,
  93859. /**
  93860. * Reset the randomizer and remove all rigid bodies, shapes, joints and any object from the world.
  93861. */
  93862. clear: function () {
  93863. this.randX = 65535;
  93864. while (this.joints !== null) {
  93865. this.removeJoint(this.joints);
  93866. }
  93867. while (this.contacts !== null) {
  93868. this.removeContact(this.contacts);
  93869. }
  93870. while (this.rigidBodies !== null) {
  93871. this.removeRigidBody(this.rigidBodies);
  93872. }
  93873. OIMO.nextID = 0;
  93874. OIMO.proxyID = 0;
  93875. },
  93876. /**
  93877. * I'll add a rigid body to the world.
  93878. * Rigid body that has been added will be the operands of each step.
  93879. * @param rigidBody Rigid body that you want to add
  93880. */
  93881. addRigidBody: function (rigidBody) {
  93882. if (rigidBody.parent) {
  93883. OIMO.Error("World", "It is not possible to be added to more than one world one of the rigid body");
  93884. }
  93885. rigidBody.parent = this;
  93886. rigidBody.awake();
  93887. for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
  93888. this.addShape(shape);
  93889. }
  93890. if (this.rigidBodies !== null) (this.rigidBodies.prev = rigidBody).next = this.rigidBodies;
  93891. this.rigidBodies = rigidBody;
  93892. this.numRigidBodies++;
  93893. },
  93894. /**
  93895. * I will remove the rigid body from the world.
  93896. * Rigid body that has been deleted is excluded from the calculation on a step-by-step basis.
  93897. * @param rigidBody Rigid body to be removed
  93898. */
  93899. removeRigidBody: function (rigidBody) {
  93900. var remove = rigidBody;
  93901. if (remove.parent !== this) return;
  93902. remove.awake();
  93903. var js = remove.jointLink;
  93904. while (js != null) {
  93905. var joint = js.joint;
  93906. js = js.next;
  93907. this.removeJoint(joint);
  93908. }
  93909. for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
  93910. this.removeShape(shape);
  93911. }
  93912. var prev = remove.prev;
  93913. var next = remove.next;
  93914. if (prev !== null) prev.next = next;
  93915. if (next !== null) next.prev = prev;
  93916. if (this.rigidBodies == remove) this.rigidBodies = next;
  93917. remove.prev = null;
  93918. remove.next = null;
  93919. remove.parent = null;
  93920. this.numRigidBodies--;
  93921. },
  93922. getByName: function (name) {
  93923. var result = null;
  93924. var body = this.rigidBodies;
  93925. while (body !== null) {
  93926. if (body.name !== " " && body.name === name) result = body;
  93927. body = body.next;
  93928. }
  93929. var joint = this.joints;
  93930. while (joint !== null) {
  93931. if (joint.name !== "" && joint.name === name) result = joint;
  93932. joint = joint.next;
  93933. }
  93934. return result;
  93935. },
  93936. /**
  93937. * I'll add a shape to the world..
  93938. * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world,
  93939. * Shape will be added to the world automatically, please do not call from outside this method.
  93940. * @param shape Shape you want to add
  93941. */
  93942. addShape: function (shape) {
  93943. if (!shape.parent || !shape.parent.parent) {
  93944. OIMO.Error("World", "It is not possible to be added alone to shape world");
  93945. }
  93946. shape.proxy = this.broadPhase.createProxy(shape);
  93947. shape.updateProxy();
  93948. this.broadPhase.addProxy(shape.proxy);
  93949. },
  93950. /**
  93951. * I will remove the shape from the world.
  93952. * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world,
  93953. * Shape will be added to the world automatically, please do not call from outside this method.
  93954. * @param shape Shape you want to delete
  93955. */
  93956. removeShape: function (shape) {
  93957. this.broadPhase.removeProxy(shape.proxy);
  93958. shape.proxy = null;
  93959. },
  93960. /**
  93961. * I'll add a joint to the world.
  93962. * Joint that has been added will be the operands of each step.
  93963. * @param shape Joint to be added
  93964. */
  93965. addJoint: function (joint) {
  93966. if (joint.parent) {
  93967. OIMO.Error("World", "It is not possible to be added to more than one world one of the joint");
  93968. }
  93969. if (this.joints != null) (this.joints.prev = joint).next = this.joints;
  93970. this.joints = joint;
  93971. joint.parent = this;
  93972. this.numJoints++;
  93973. joint.awake();
  93974. joint.attach();
  93975. },
  93976. /**
  93977. * I will remove the joint from the world.
  93978. * Joint that has been added will be the operands of each step.
  93979. * @param shape Joint to be deleted
  93980. */
  93981. removeJoint: function (joint) {
  93982. var remove = joint;
  93983. var prev = remove.prev;
  93984. var next = remove.next;
  93985. if (prev !== null) prev.next = next;
  93986. if (next !== null) next.prev = prev;
  93987. if (this.joints == remove) this.joints = next;
  93988. remove.prev = null;
  93989. remove.next = null;
  93990. this.numJoints--;
  93991. remove.awake();
  93992. remove.detach();
  93993. remove.parent = null;
  93994. },
  93995. worldscale: function (scale) {
  93996. OIMO.WORLD_SCALE = scale || 100;
  93997. OIMO.INV_SCALE = 1 / OIMO.WORLD_SCALE;
  93998. },
  93999. addContact: function (s1, s2) {
  94000. var newContact;
  94001. if (this.unusedContacts !== null) {
  94002. newContact = this.unusedContacts;
  94003. this.unusedContacts = this.unusedContacts.next;
  94004. } else {
  94005. newContact = new OIMO.Contact();
  94006. }
  94007. newContact.attach(s1, s2);
  94008. newContact.detector = this.detectors[s1.type][s2.type];
  94009. if (this.contacts) (this.contacts.prev = newContact).next = this.contacts;
  94010. this.contacts = newContact;
  94011. this.numContacts++;
  94012. },
  94013. removeContact: function (contact) {
  94014. var prev = contact.prev;
  94015. var next = contact.next;
  94016. if (next) next.prev = prev;
  94017. if (prev) prev.next = next;
  94018. if (this.contacts == contact) this.contacts = next;
  94019. contact.prev = null;
  94020. contact.next = null;
  94021. contact.detach();
  94022. contact.next = this.unusedContacts;
  94023. this.unusedContacts = contact;
  94024. this.numContacts--;
  94025. },
  94026. checkContact: function (name1, name2) {
  94027. var n1, n2;
  94028. var contact = this.contacts;
  94029. while (contact !== null) {
  94030. n1 = contact.body1.name || ' ';
  94031. n2 = contact.body2.name || ' ';
  94032. if ((n1 == name1 && n2 == name2) || (n2 == name1 && n1 == name2)) { if (contact.touching) return true; else return false; }
  94033. else contact = contact.next;
  94034. }
  94035. return false;
  94036. },
  94037. callSleep: function (body) {
  94038. if (!body.allowSleep) return false;
  94039. if (body.linearVelocity.lengthSq() > 0.04) return false;
  94040. if (body.angularVelocity.lengthSq() > 0.25) return false;
  94041. return true;
  94042. },
  94043. /**
  94044. * I will proceed only time step seconds time of World.
  94045. */
  94046. step: function () {
  94047. var time0, time1, time2, time3;
  94048. var stat = !this.isNoStat ? true : false;
  94049. if (stat) time0 = OIMO.now();
  94050. var body = this.rigidBodies;
  94051. while (body !== null) {
  94052. body.addedToIsland = false;
  94053. if (body.sleeping) {
  94054. if (
  94055. body.linearVelocity.testZero() ||
  94056. body.angularVelocity.testZero() ||
  94057. body.position.testDiff(body.sleepPosition) ||
  94058. body.orientation.testDiff(body.sleepOrientation)
  94059. ) body.awake(); // awake the body
  94060. }
  94061. body = body.next;
  94062. }
  94063. //------------------------------------------------------
  94064. // UPDATE CONTACT
  94065. //------------------------------------------------------
  94066. // broad phase
  94067. if (stat) time1 = OIMO.now();
  94068. this.broadPhase.detectPairs();
  94069. var pairs = this.broadPhase.pairs;
  94070. var i = this.broadPhase.numPairs;
  94071. //do{
  94072. while (i--) {
  94073. //for(var i=0, l=numPairs; i<l; i++){
  94074. var pair = pairs[i];
  94075. var s1;
  94076. var s2;
  94077. if (pair.shape1.id < pair.shape2.id) {
  94078. s1 = pair.shape1;
  94079. s2 = pair.shape2;
  94080. } else {
  94081. s1 = pair.shape2;
  94082. s2 = pair.shape1;
  94083. }
  94084. var link;
  94085. if (s1.numContacts < s2.numContacts) link = s1.contactLink;
  94086. else link = s2.contactLink;
  94087. var exists = false;
  94088. while (link) {
  94089. var contact = link.contact;
  94090. if (contact.shape1 == s1 && contact.shape2 == s2) {
  94091. contact.persisting = true;
  94092. exists = true;// contact already exists
  94093. break;
  94094. }
  94095. link = link.next;
  94096. }
  94097. if (!exists) {
  94098. this.addContact(s1, s2);
  94099. }
  94100. }// while(i-- >0);
  94101. if (stat) {
  94102. time2 = OIMO.now();
  94103. this.performance.broadPhaseTime = time2 - time1;
  94104. }
  94105. // update & narrow phase
  94106. this.numContactPoints = 0;
  94107. contact = this.contacts;
  94108. while (contact !== null) {
  94109. if (!contact.persisting) {
  94110. if (contact.shape1.aabb.intersectTest(contact.shape2.aabb)) {
  94111. /*var aabb1=contact.shape1.aabb;
  94112. var aabb2=contact.shape2.aabb;
  94113. if(
  94114. aabb1.minX>aabb2.maxX || aabb1.maxX<aabb2.minX ||
  94115. aabb1.minY>aabb2.maxY || aabb1.maxY<aabb2.minY ||
  94116. aabb1.minZ>aabb2.maxZ || aabb1.maxZ<aabb2.minZ
  94117. ){*/
  94118. var next = contact.next;
  94119. this.removeContact(contact);
  94120. contact = next;
  94121. continue;
  94122. }
  94123. }
  94124. var b1 = contact.body1;
  94125. var b2 = contact.body2;
  94126. if (b1.isDynamic && !b1.sleeping || b2.isDynamic && !b2.sleeping) {
  94127. contact.updateManifold();
  94128. }
  94129. this.numContactPoints += contact.manifold.numPoints;
  94130. contact.persisting = false;
  94131. contact.constraint.addedToIsland = false;
  94132. contact = contact.next;
  94133. }
  94134. if (stat) {
  94135. time3 = OIMO.now();
  94136. this.performance.narrowPhaseTime = time3 - time2;
  94137. }
  94138. //------------------------------------------------------
  94139. // SOLVE ISLANDS
  94140. //------------------------------------------------------
  94141. var invTimeStep = 1 / this.timeStep;
  94142. //var body;
  94143. var joint;
  94144. var constraint;
  94145. //var num;
  94146. for (joint = this.joints; joint !== null; joint = joint.next) {
  94147. joint.addedToIsland = false;
  94148. }
  94149. // clear old island array
  94150. this.islandRigidBodies = [];
  94151. this.islandConstraints = [];
  94152. this.islandStack = [];
  94153. // expand island buffers
  94154. /*if(this.maxIslandRigidBodies<this.numRigidBodies){
  94155. this.maxIslandRigidBodies=this.numRigidBodies<<1;
  94156. //this.maxIslandRigidBodies=this.numRigidBodies*2;
  94157. this.islandRigidBodies=[];
  94158. this.islandStack=[];
  94159. this.islandRigidBodies.length = this.maxIslandRigidBodies;
  94160. this.islandStack.length = this.maxIslandRigidBodies;
  94161. }
  94162. var numConstraints=this.numJoints+this.numContacts;
  94163. if(this.maxIslandConstraints<numConstraints){
  94164. this.maxIslandConstraints=numConstraints<<1;
  94165. //this.maxIslandConstraints=numConstraints*2;
  94166. this.islandConstraints=[];
  94167. this.islandConstraints.length = this.maxIslandConstraints;
  94168. }*/
  94169. time1 = OIMO.now();
  94170. this.numIslands = 0;
  94171. // build and solve simulation islands
  94172. for (var base = this.rigidBodies; base !== null; base = base.next) {
  94173. if (base.addedToIsland || base.isStatic || base.sleeping) continue;// ignore
  94174. if (base.isLonely()) {// update single body
  94175. if (base.isDynamic) {
  94176. base.linearVelocity.addTime(this.gravity, this.timeStep);
  94177. /*base.linearVelocity.x+=this.gravity.x*this.timeStep;
  94178. base.linearVelocity.y+=this.gravity.y*this.timeStep;
  94179. base.linearVelocity.z+=this.gravity.z*this.timeStep;*/
  94180. }
  94181. if (this.callSleep(base)) {
  94182. base.sleepTime += this.timeStep;
  94183. if (base.sleepTime > 0.5) base.sleep();
  94184. else base.updatePosition(this.timeStep);
  94185. } else {
  94186. base.sleepTime = 0;
  94187. base.updatePosition(this.timeStep);
  94188. }
  94189. this.numIslands++;
  94190. continue;
  94191. }
  94192. var islandNumRigidBodies = 0;
  94193. var islandNumConstraints = 0;
  94194. var stackCount = 1;
  94195. // add rigid body to stack
  94196. this.islandStack[0] = base;
  94197. base.addedToIsland = true;
  94198. // build an island
  94199. do {
  94200. // get rigid body from stack
  94201. body = this.islandStack[--stackCount];
  94202. this.islandStack[stackCount] = null;
  94203. body.sleeping = false;
  94204. // add rigid body to the island
  94205. this.islandRigidBodies[islandNumRigidBodies++] = body;
  94206. if (body.isStatic) continue;
  94207. // search connections
  94208. for (var cs = body.contactLink; cs !== null; cs = cs.next) {
  94209. var contact = cs.contact;
  94210. constraint = contact.constraint;
  94211. if (constraint.addedToIsland || !contact.touching) continue;// ignore
  94212. // add constraint to the island
  94213. this.islandConstraints[islandNumConstraints++] = constraint;
  94214. constraint.addedToIsland = true;
  94215. var next = cs.body;
  94216. if (next.addedToIsland) continue;
  94217. // add rigid body to stack
  94218. this.islandStack[stackCount++] = next;
  94219. next.addedToIsland = true;
  94220. }
  94221. for (var js = body.jointLink; js !== null; js = js.next) {
  94222. constraint = js.joint;
  94223. if (constraint.addedToIsland) continue;// ignore
  94224. // add constraint to the island
  94225. this.islandConstraints[islandNumConstraints++] = constraint;
  94226. constraint.addedToIsland = true;
  94227. next = js.body;
  94228. if (next.addedToIsland || !next.isDynamic) continue;
  94229. // add rigid body to stack
  94230. this.islandStack[stackCount++] = next;
  94231. next.addedToIsland = true;
  94232. }
  94233. } while (stackCount != 0);
  94234. // update velocities
  94235. var gVel = new OIMO.Vec3().addTime(this.gravity, this.timeStep);
  94236. /*var gx=this.gravity.x*this.timeStep;
  94237. var gy=this.gravity.y*this.timeStep;
  94238. var gz=this.gravity.z*this.timeStep;*/
  94239. var j = islandNumRigidBodies;
  94240. while (j--) {
  94241. //or(var j=0, l=islandNumRigidBodies; j<l; j++){
  94242. body = this.islandRigidBodies[j];
  94243. if (body.isDynamic) {
  94244. body.linearVelocity.addEqual(gVel);
  94245. /*body.linearVelocity.x+=gx;
  94246. body.linearVelocity.y+=gy;
  94247. body.linearVelocity.z+=gz;*/
  94248. }
  94249. }
  94250. // randomizing order
  94251. if (this.enableRandomizer) {
  94252. //for(var j=1, l=islandNumConstraints; j<l; j++){
  94253. j = islandNumConstraints;
  94254. while (j--) {
  94255. if (j !== 0) {
  94256. var swap = (this.randX = (this.randX * this.randA + this.randB & 0x7fffffff)) / 2147483648.0 * j | 0;
  94257. constraint = this.islandConstraints[j];
  94258. this.islandConstraints[j] = this.islandConstraints[swap];
  94259. this.islandConstraints[swap] = constraint;
  94260. }
  94261. }
  94262. }
  94263. // solve contraints
  94264. j = islandNumConstraints;
  94265. while (j--) {
  94266. //for(j=0, l=islandNumConstraints; j<l; j++){
  94267. this.islandConstraints[j].preSolve(this.timeStep, invTimeStep);// pre-solve
  94268. }
  94269. var k = this.numIterations;
  94270. while (k--) {
  94271. //for(var k=0, l=this.numIterations; k<l; k++){
  94272. j = islandNumConstraints;
  94273. while (j--) {
  94274. //for(j=0, m=islandNumConstraints; j<m; j++){
  94275. this.islandConstraints[j].solve();// main-solve
  94276. }
  94277. }
  94278. j = islandNumConstraints;
  94279. while (j--) {
  94280. //for(j=0, l=islandNumConstraints; j<l; j++){
  94281. this.islandConstraints[j].postSolve();// post-solve
  94282. this.islandConstraints[j] = null;// gc
  94283. }
  94284. // sleeping check
  94285. var sleepTime = 10;
  94286. j = islandNumRigidBodies;
  94287. while (j--) {
  94288. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  94289. body = this.islandRigidBodies[j];
  94290. if (this.callSleep(body)) {
  94291. body.sleepTime += this.timeStep;
  94292. if (body.sleepTime < sleepTime) sleepTime = body.sleepTime;
  94293. } else {
  94294. body.sleepTime = 0;
  94295. sleepTime = 0;
  94296. continue;
  94297. }
  94298. }
  94299. if (sleepTime > 0.5) {
  94300. // sleep the island
  94301. j = islandNumRigidBodies;
  94302. while (j--) {
  94303. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  94304. this.islandRigidBodies[j].sleep();
  94305. this.islandRigidBodies[j] = null;// gc
  94306. }
  94307. } else {
  94308. // update positions
  94309. j = islandNumRigidBodies;
  94310. while (j--) {
  94311. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  94312. this.islandRigidBodies[j].updatePosition(this.timeStep);
  94313. this.islandRigidBodies[j] = null;// gc
  94314. }
  94315. }
  94316. this.numIslands++;
  94317. }
  94318. if (stat) {
  94319. time2 = OIMO.now();
  94320. this.performance.solvingTime = time2 - time1;
  94321. //------------------------------------------------------
  94322. // END SIMULATION
  94323. //------------------------------------------------------
  94324. time2 = OIMO.now();
  94325. // fps update
  94326. this.performance.upfps();
  94327. this.performance.totalTime = time2 - time0;
  94328. }
  94329. }
  94330. }
  94331. /**
  94332. * The class of rigid body.
  94333. * Rigid body has the shape of a single or multiple collision processing,
  94334. * I can set the parameters individually.
  94335. * @author saharan
  94336. */
  94337. OIMO.RigidBody = function (x, y, z, rad, ax, ay, az) {
  94338. this.name = " ";
  94339. // The maximum number of shapes that can be added to a one rigid.
  94340. this.MAX_SHAPES = 64;//64;
  94341. this.prev = null;
  94342. this.next = null;
  94343. // I represent the kind of rigid body.
  94344. // Please do not change from the outside this variable.
  94345. // If you want to change the type of rigid body, always
  94346. // Please specify the type you want to set the arguments of setupMass method.
  94347. this.type = OIMO.BODY_NULL;
  94348. this.massInfo = new OIMO.MassInfo();
  94349. // It is the world coordinate of the center of gravity.
  94350. this.position = new OIMO.Vec3(x, y, z);
  94351. this.orientation = this.rotationAxisToQuad(rad || 0, ax || 0, ay || 0, az || 0);
  94352. this.newPosition = new OIMO.Vec3();
  94353. this.controlPos = false;
  94354. this.newOrientation = new OIMO.Quat();
  94355. this.newRotation = new OIMO.Vec3();
  94356. this.currentRotation = new OIMO.Vec3();
  94357. this.controlRot = false;
  94358. this.controlRotInTime = false;
  94359. // Is the translational velocity.
  94360. this.linearVelocity = new OIMO.Vec3();
  94361. // Is the angular velocity.
  94362. this.angularVelocity = new OIMO.Vec3();
  94363. // return matrix for three.js
  94364. this.matrix = new OIMO.Mat44();
  94365. //--------------------------------------------
  94366. // Please do not change from the outside this variables.
  94367. //--------------------------------------------
  94368. // It is a world that rigid body has been added.
  94369. this.parent = null;
  94370. this.contactLink = null;
  94371. this.numContacts = 0;
  94372. // An array of shapes that are included in the rigid body.
  94373. this.shapes = null;
  94374. // The number of shapes that are included in the rigid body.
  94375. this.numShapes = 0;
  94376. // It is the link array of joint that is connected to the rigid body.
  94377. this.jointLink = null;
  94378. // The number of joints that are connected to the rigid body.
  94379. this.numJoints = 0;
  94380. // It is the world coordinate of the center of gravity in the sleep just before.
  94381. this.sleepPosition = new OIMO.Vec3();
  94382. // It is a quaternion that represents the attitude of sleep just before.
  94383. this.sleepOrientation = new OIMO.Quat();
  94384. // I will show this rigid body to determine whether it is a rigid body static.
  94385. this.isStatic = false;
  94386. // I indicates that this rigid body to determine whether it is a rigid body dynamic.
  94387. this.isDynamic = false;
  94388. // It is a rotation matrix representing the orientation.
  94389. this.rotation = new OIMO.Mat33();
  94390. //--------------------------------------------
  94391. // It will be recalculated automatically from the shape, which is included.
  94392. //--------------------------------------------
  94393. // This is the weight.
  94394. this.mass = NaN;
  94395. // It is the reciprocal of the mass.
  94396. this.inverseMass = NaN;
  94397. // It is the inverse of the inertia tensor in the world system.
  94398. this.inverseInertia = new OIMO.Mat33();
  94399. // It is the inertia tensor in the initial state.
  94400. this.localInertia = new OIMO.Mat33();
  94401. // It is the inverse of the inertia tensor in the initial state.
  94402. this.inverseLocalInertia = new OIMO.Mat33();
  94403. // I indicates rigid body whether it has been added to the simulation Island.
  94404. this.addedToIsland = false;
  94405. // It shows how to sleep rigid body.
  94406. this.allowSleep = true;
  94407. // This is the time from when the rigid body at rest.
  94408. this.sleepTime = 0;
  94409. // I shows rigid body to determine whether it is a sleep state.
  94410. this.sleeping = false;
  94411. };
  94412. OIMO.RigidBody.prototype = {
  94413. constructor: OIMO.RigidBody,
  94414. /**
  94415. * I'll add a shape to rigid body.
  94416. * If you add a shape, please call the setupMass method to step up to the start of the next.
  94417. * @param shape shape to Add
  94418. */
  94419. addShape: function (shape) {
  94420. if (shape.parent) OIMO.Error("RigidBody", "It is not possible that you add to the multi-rigid body the shape of one");
  94421. if (this.shapes != null) (this.shapes.prev = shape).next = this.shapes;
  94422. this.shapes = shape;
  94423. shape.parent = this;
  94424. if (this.parent) this.parent.addShape(shape);
  94425. this.numShapes++;
  94426. },
  94427. /**
  94428. * I will delete the shape from the rigid body.
  94429. * If you delete a shape, please call the setupMass method to step up to the start of the next.
  94430. * @param shape shape to Delete
  94431. */
  94432. removeShape: function (shape) {
  94433. var remove = shape;
  94434. if (remove.parent != this) return;
  94435. var prev = remove.prev;
  94436. var next = remove.next;
  94437. if (prev != null) prev.next = next;
  94438. if (next != null) next.prev = prev;
  94439. if (this.shapes == remove) this.shapes = next;
  94440. remove.prev = null;
  94441. remove.next = null;
  94442. remove.parent = null;
  94443. if (this.parent) this.parent.removeShape(remove);
  94444. this.numShapes--;
  94445. },
  94446. remove: function () {
  94447. this.dispose();
  94448. },
  94449. dispose: function () {
  94450. this.parent.removeRigidBody(this);
  94451. },
  94452. checkContact: function (name) {
  94453. this.parent.checkContact(this.name, name);
  94454. },
  94455. /**
  94456. * Calulates mass datas(center of gravity, mass, moment inertia, etc...).
  94457. * If the parameter type is set to BODY_STATIC, the rigid body will be fixed to the space.
  94458. * If the parameter adjustPosition is set to true, the shapes' relative positions and
  94459. * the rigid body's position will be adjusted to the center of gravity.
  94460. * @param type
  94461. * @param adjustPosition
  94462. */
  94463. setupMass: function (type, AdjustPosition) {
  94464. var adjustPosition = (AdjustPosition !== undefined) ? AdjustPosition : true;
  94465. this.type = type || OIMO.BODY_DYNAMIC;
  94466. this.isDynamic = this.type == OIMO.BODY_DYNAMIC;
  94467. this.isStatic = this.type == OIMO.BODY_STATIC;
  94468. this.mass = 0;
  94469. this.localInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  94470. var te = this.localInertia.elements;
  94471. //
  94472. var tmpM = new OIMO.Mat33();
  94473. var tmpV = new OIMO.Vec3();
  94474. for (var shape = this.shapes; shape != null; shape = shape.next) {
  94475. shape.calculateMassInfo(this.massInfo);
  94476. var shapeMass = this.massInfo.mass;
  94477. var relX = shape.relativePosition.x;
  94478. var relY = shape.relativePosition.y;
  94479. var relZ = shape.relativePosition.z;
  94480. /*tmpV.x+=relX*shapeMass;
  94481. tmpV.y+=relY*shapeMass;
  94482. tmpV.z+=relZ*shapeMass;*/
  94483. tmpV.addScale(shape.relativePosition, shapeMass);
  94484. this.mass += shapeMass;
  94485. this.rotateInertia(shape.relativeRotation, this.massInfo.inertia, tmpM);
  94486. this.localInertia.addEqual(tmpM);
  94487. // add offset inertia
  94488. te[0] += shapeMass * (relY * relY + relZ * relZ);
  94489. te[4] += shapeMass * (relX * relX + relZ * relZ);
  94490. te[8] += shapeMass * (relX * relX + relY * relY);
  94491. var xy = shapeMass * relX * relY;
  94492. var yz = shapeMass * relY * relZ;
  94493. var zx = shapeMass * relZ * relX;
  94494. te[1] -= xy;
  94495. te[3] -= xy;
  94496. te[2] -= yz;
  94497. te[6] -= yz;
  94498. te[5] -= zx;
  94499. te[7] -= zx;
  94500. }
  94501. this.inverseMass = 1 / this.mass;
  94502. tmpV.scaleEqual(this.inverseMass);
  94503. if (adjustPosition) {
  94504. this.position.addEqual(tmpV);
  94505. for (shape = this.shapes; shape != null; shape = shape.next) {
  94506. shape.relativePosition.subEqual(tmpV);
  94507. }
  94508. // subtract offset inertia
  94509. relX = tmpV.x;
  94510. relY = tmpV.y;
  94511. relZ = tmpV.z;
  94512. //var te = this.localInertia.elements;
  94513. te[0] -= this.mass * (relY * relY + relZ * relZ);
  94514. te[4] -= this.mass * (relX * relX + relZ * relZ);
  94515. te[8] -= this.mass * (relX * relX + relY * relY);
  94516. xy = this.mass * relX * relY;
  94517. yz = this.mass * relY * relZ;
  94518. zx = this.mass * relZ * relX;
  94519. te[1] += xy;
  94520. te[3] += xy;
  94521. te[2] += yz;
  94522. te[6] += yz;
  94523. te[5] += zx;
  94524. te[7] += zx;
  94525. }
  94526. this.inverseLocalInertia.invert(this.localInertia);
  94527. if (this.type == OIMO.BODY_STATIC) {
  94528. this.inverseMass = 0;
  94529. this.inverseLocalInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  94530. }
  94531. this.syncShapes();
  94532. this.awake();
  94533. },
  94534. /**
  94535. * Awake the rigid body.
  94536. */
  94537. awake: function () {
  94538. if (!this.allowSleep || !this.sleeping) return;
  94539. this.sleeping = false;
  94540. this.sleepTime = 0;
  94541. // awake connected constraints
  94542. var cs = this.contactLink;
  94543. while (cs != null) {
  94544. cs.body.sleepTime = 0;
  94545. cs.body.sleeping = false;
  94546. cs = cs.next;
  94547. }
  94548. var js = this.jointLink;
  94549. while (js != null) {
  94550. js.body.sleepTime = 0;
  94551. js.body.sleeping = false;
  94552. js = js.next;
  94553. }
  94554. for (var shape = this.shapes; shape != null; shape = shape.next) {
  94555. shape.updateProxy();
  94556. }
  94557. },
  94558. /**
  94559. * Sleep the rigid body.
  94560. */
  94561. sleep: function () {
  94562. if (!this.allowSleep || this.sleeping) return;
  94563. this.linearVelocity.set(0, 0, 0);
  94564. this.angularVelocity.set(0, 0, 0);
  94565. this.sleepPosition.copy(this.position);
  94566. this.sleepOrientation.copy(this.orientation);
  94567. /*this.linearVelocity.x=0;
  94568. this.linearVelocity.y=0;
  94569. this.linearVelocity.z=0;
  94570. this.angularVelocity.x=0;
  94571. this.angularVelocity.y=0;
  94572. this.angularVelocity.z=0;
  94573. this.sleepPosition.x=this.position.x;
  94574. this.sleepPosition.y=this.position.y;
  94575. this.sleepPosition.z=this.position.z;*/
  94576. /*this.sleepOrientation.s=this.orientation.s;
  94577. this.sleepOrientation.x=this.orientation.x;
  94578. this.sleepOrientation.y=this.orientation.y;
  94579. this.sleepOrientation.z=this.orientation.z;*/
  94580. this.sleepTime = 0;
  94581. this.sleeping = true;
  94582. for (var shape = this.shapes; shape != null; shape = shape.next) {
  94583. shape.updateProxy();
  94584. }
  94585. },
  94586. /**
  94587. * Get whether the rigid body has not any connection with others.
  94588. * @return
  94589. */
  94590. isLonely: function () {
  94591. return this.numJoints == 0 && this.numContacts == 0;
  94592. },
  94593. /**
  94594. * The time integration of the motion of a rigid body, you can update the information such as the shape.
  94595. * This method is invoked automatically when calling the step of the World,
  94596. * There is no need to call from outside usually.
  94597. * @param timeStep time
  94598. */
  94599. updatePosition: function (timeStep) {
  94600. switch (this.type) {
  94601. case OIMO.BODY_STATIC:
  94602. this.linearVelocity.set(0, 0, 0);
  94603. this.angularVelocity.set(0, 0, 0);
  94604. // ONLY FOR TEST
  94605. if (this.controlPos) {
  94606. this.position.copy(this.newPosition);
  94607. this.controlPos = false;
  94608. }
  94609. if (this.controlRot) {
  94610. this.orientation.copy(this.newOrientation);
  94611. this.controlRot = false;
  94612. }
  94613. /*this.linearVelocity.x=0;
  94614. this.linearVelocity.y=0;
  94615. this.linearVelocity.z=0;
  94616. this.angularVelocity.x=0;
  94617. this.angularVelocity.y=0;
  94618. this.angularVelocity.z=0;*/
  94619. break;
  94620. case OIMO.BODY_DYNAMIC:
  94621. if (this.controlPos) {
  94622. this.angularVelocity.set(0, 0, 0);
  94623. this.linearVelocity.set(0, 0, 0);
  94624. this.linearVelocity.x = (this.newPosition.x - this.position.x) / timeStep;
  94625. this.linearVelocity.y = (this.newPosition.y - this.position.y) / timeStep;
  94626. this.linearVelocity.z = (this.newPosition.z - this.position.z) / timeStep;
  94627. this.controlPos = false;
  94628. }
  94629. if (this.controlRot) {
  94630. this.angularVelocity.set(0, 0, 0);
  94631. this.orientation.copy(this.newOrientation);
  94632. //var t=timeStep//*0.5;
  94633. //var q = new OIMO.Quat();
  94634. //q.sub(this.newOrientation, this.orientation);
  94635. //q.normalize(q);
  94636. /*q.s = (this.newOrientation.s - this.orientation.s)/t;
  94637. q.x = (this.newOrientation.x - this.orientation.x)/t;
  94638. q.y = (this.newOrientation.y - this.orientation.y)/t;
  94639. q.z = (this.newOrientation.z - this.orientation.z)/t;*/
  94640. //this.angularVelocity.applyQuaternion(q);
  94641. //this.angularVelocity.x = this.angularVelocity.x/t;
  94642. //this.angularVelocity.y = this.angularVelocity.y/t;
  94643. //this.angularVelocity.z = this.angularVelocity.z/t;
  94644. this.controlRot = false;
  94645. }
  94646. this.position.addTime(this.linearVelocity, timeStep);
  94647. this.orientation.addTime(this.angularVelocity, timeStep);
  94648. break;
  94649. default: OIMO.Error("RigidBody", "Invalid type.");
  94650. }
  94651. this.syncShapes();
  94652. },
  94653. rotateInertia: function (rot, inertia, out) {
  94654. var tm1 = rot.elements;
  94655. var tm2 = inertia.elements;
  94656. var a0 = tm1[0], a3 = tm1[3], a6 = tm1[6];
  94657. var a1 = tm1[1], a4 = tm1[4], a7 = tm1[7];
  94658. var a2 = tm1[2], a5 = tm1[5], a8 = tm1[8];
  94659. var b0 = tm2[0], b3 = tm2[3], b6 = tm2[6];
  94660. var b1 = tm2[1], b4 = tm2[4], b7 = tm2[7];
  94661. var b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
  94662. var e00 = a0 * b0 + a1 * b3 + a2 * b6;
  94663. var e01 = a0 * b1 + a1 * b4 + a2 * b7;
  94664. var e02 = a0 * b2 + a1 * b5 + a2 * b8;
  94665. var e10 = a3 * b0 + a4 * b3 + a5 * b6;
  94666. var e11 = a3 * b1 + a4 * b4 + a5 * b7;
  94667. var e12 = a3 * b2 + a4 * b5 + a5 * b8;
  94668. var e20 = a6 * b0 + a7 * b3 + a8 * b6;
  94669. var e21 = a6 * b1 + a7 * b4 + a8 * b7;
  94670. var e22 = a6 * b2 + a7 * b5 + a8 * b8;
  94671. var oe = out.elements;
  94672. oe[0] = e00 * a0 + e01 * a1 + e02 * a2;
  94673. oe[1] = e00 * a3 + e01 * a4 + e02 * a5;
  94674. oe[2] = e00 * a6 + e01 * a7 + e02 * a8;
  94675. oe[3] = e10 * a0 + e11 * a1 + e12 * a2;
  94676. oe[4] = e10 * a3 + e11 * a4 + e12 * a5;
  94677. oe[5] = e10 * a6 + e11 * a7 + e12 * a8;
  94678. oe[6] = e20 * a0 + e21 * a1 + e22 * a2;
  94679. oe[7] = e20 * a3 + e21 * a4 + e22 * a5;
  94680. oe[8] = e20 * a6 + e21 * a7 + e22 * a8;
  94681. },
  94682. syncShapes: function () {
  94683. var s = this.orientation.s;
  94684. var x = this.orientation.x;
  94685. var y = this.orientation.y;
  94686. var z = this.orientation.z;
  94687. var x2 = 2 * x;
  94688. var y2 = 2 * y;
  94689. var z2 = 2 * z;
  94690. var xx = x * x2;
  94691. var yy = y * y2;
  94692. var zz = z * z2;
  94693. var xy = x * y2;
  94694. var yz = y * z2;
  94695. var xz = x * z2;
  94696. var sx = s * x2;
  94697. var sy = s * y2;
  94698. var sz = s * z2;
  94699. var tr = this.rotation.elements;
  94700. tr[0] = 1 - yy - zz;
  94701. tr[1] = xy - sz;
  94702. tr[2] = xz + sy;
  94703. tr[3] = xy + sz;
  94704. tr[4] = 1 - xx - zz;
  94705. tr[5] = yz - sx;
  94706. tr[6] = xz - sy;
  94707. tr[7] = yz + sx;
  94708. tr[8] = 1 - xx - yy;
  94709. this.rotateInertia(this.rotation, this.inverseLocalInertia, this.inverseInertia);
  94710. for (var shape = this.shapes; shape != null; shape = shape.next) {
  94711. //var relPos=shape.relativePosition;
  94712. //var relRot=shape.relativeRotation;
  94713. //var rot=shape.rotation;
  94714. /*var lx=relPos.x;
  94715. var ly=relPos.y;
  94716. var lz=relPos.z;
  94717. shape.position.x=this.position.x+lx*tr[0]+ly*tr[1]+lz*tr[2];
  94718. shape.position.y=this.position.y+lx*tr[3]+ly*tr[4]+lz*tr[5];
  94719. shape.position.z=this.position.z+lx*tr[6]+ly*tr[7]+lz*tr[8];*/
  94720. shape.position.mul(this.position, shape.relativePosition, this.rotation);
  94721. //shape.rotation.mul(shape.relativeRotation,this.rotation);
  94722. // add by QuaziKb
  94723. shape.rotation.mul(this.rotation, shape.relativeRotation);
  94724. shape.updateProxy();
  94725. }
  94726. },
  94727. applyImpulse: function (position, force) {
  94728. this.linearVelocity.addScale(force, this.inverseMass);
  94729. /*this.linearVelocity.x+=force.x*this.inverseMass;
  94730. this.linearVelocity.y+=force.y*this.inverseMass;
  94731. this.linearVelocity.z+=force.z*this.inverseMass;*/
  94732. var rel = new OIMO.Vec3();
  94733. rel.sub(position, this.position).cross(rel, force).mulMat(this.inverseInertia, rel);
  94734. this.angularVelocity.addEqual(rel);
  94735. /*this.angularVelocity.x+=rel.x;
  94736. this.angularVelocity.y+=rel.y;
  94737. this.angularVelocity.z+=rel.z;*/
  94738. },
  94739. //---------------------------------------------
  94740. //
  94741. // FOR THREE JS
  94742. //
  94743. //---------------------------------------------
  94744. rotationVectToQuad: function (rot) {
  94745. var r = OIMO.EulerToAxis(rot.x * OIMO.degtorad, rot.y * OIMO.degtorad, rot.z * OIMO.degtorad);
  94746. return this.rotationAxisToQuad(r[0], r[1], r[2], r[3]);
  94747. },
  94748. rotationAxisToQuad: function (rad, ax, ay, az) { // in radian
  94749. var len = ax * ax + ay * ay + az * az;
  94750. if (len > 0) {
  94751. len = 1 / OIMO.sqrt(len);
  94752. ax *= len;
  94753. ay *= len;
  94754. az *= len;
  94755. }
  94756. var sin = OIMO.sin(rad * 0.5);
  94757. var cos = OIMO.cos(rad * 0.5);
  94758. return new OIMO.Quat(cos, sin * ax, sin * ay, sin * az);
  94759. },
  94760. //---------------------------------------------
  94761. // SET DYNAMIQUE POSITION AND ROTATION
  94762. //---------------------------------------------
  94763. setPosition: function (pos) {
  94764. this.newPosition.copy(pos).multiplyScalar(OIMO.INV_SCALE);
  94765. //this.newPosition.set(pos.x*OIMO.INV_SCALE,pos.y*OIMO.INV_SCALE,pos.z*OIMO.INV_SCALE);
  94766. this.controlPos = true;
  94767. },
  94768. setQuaternion: function (q) {
  94769. //if(this.type == this.BODY_STATIC)this.orientation.init(q.w,q.x,q.y,q.z);
  94770. this.newOrientation.set(q.x, q.y, q.z, q.w);
  94771. this.controlRot = true;
  94772. },
  94773. setRotation: function (rot) {
  94774. this.newOrientation = this.rotationVectToQuad(rot);
  94775. this.controlRot = true;
  94776. },
  94777. //---------------------------------------------
  94778. // RESET DYNAMIQUE POSITION AND ROTATION
  94779. //---------------------------------------------
  94780. resetPosition: function (x, y, z) {
  94781. this.linearVelocity.set(0, 0, 0);
  94782. this.angularVelocity.set(0, 0, 0);
  94783. this.position.set(x, y, z).multiplyScalar(OIMO.INV_SCALE);
  94784. //this.position.set( x*OIMO.INV_SCALE, y*OIMO.INV_SCALE, z*OIMO.INV_SCALE );
  94785. this.awake();
  94786. },
  94787. resetQuaternion: function (q) {
  94788. this.angularVelocity.set(0, 0, 0);
  94789. this.orientation = new OIMO.Quat(q.w, q.x, q.y, q.z);
  94790. this.awake();
  94791. },
  94792. resetRotation: function (x, y, z) {
  94793. this.angularVelocity.set(0, 0, 0);
  94794. this.orientation = this.rotationVectToQuad(new OIMO.Vec3(x, y, z));
  94795. this.awake();
  94796. },
  94797. //---------------------------------------------
  94798. // GET POSITION AND ROTATION
  94799. //---------------------------------------------
  94800. getPosition: function () {
  94801. return new OIMO.Vec3().scale(this.position, OIMO.WORLD_SCALE);
  94802. },
  94803. getRotation: function () {
  94804. return new OIMO.Euler().setFromRotationMatrix(this.rotation);
  94805. },
  94806. getQuaternion: function () {
  94807. return new OIMO.Quaternion().setFromRotationMatrix(this.rotation);
  94808. },
  94809. getMatrix: function () {
  94810. var m = this.matrix.elements;
  94811. var r, p;
  94812. if (!this.sleeping) {
  94813. // rotation matrix
  94814. r = this.rotation.elements;
  94815. m[0] = r[0]; m[1] = r[3]; m[2] = r[6]; m[3] = 0;
  94816. m[4] = r[1]; m[5] = r[4]; m[6] = r[7]; m[7] = 0;
  94817. m[8] = r[2]; m[9] = r[5]; m[10] = r[8]; m[11] = 0;
  94818. // position matrix
  94819. p = this.position;
  94820. m[12] = p.x * OIMO.WORLD_SCALE;
  94821. m[13] = p.y * OIMO.WORLD_SCALE;
  94822. m[14] = p.z * OIMO.WORLD_SCALE;
  94823. // sleep or not ?
  94824. m[15] = 0;
  94825. } else {
  94826. m[15] = 1;
  94827. }
  94828. return m;
  94829. }
  94830. };
  94831. /**
  94832. * The main class of body.
  94833. * is for simplify creation process and data access of rigidRody
  94834. * Rigid body has the shape of a single or multiple collision processing,
  94835. * all setting in object
  94836. *
  94837. * @author loth
  94838. */
  94839. OIMO.Body = function (Obj) {
  94840. var obj = Obj || {};
  94841. if (!obj.world) return;
  94842. if (obj.type === undefined) obj.type = "box";
  94843. this.name = obj.name || '';
  94844. // obsolete use world.add(obj)
  94845. this.body = obj.world.add(obj);
  94846. /*
  94847. // the world where i am
  94848. this.parent = obj.world;
  94849. // Yep my name
  94850. this.name = obj.name || '';
  94851. // I'm dynamique or not
  94852. var move = obj.move || false;
  94853. // I can sleep or not
  94854. var noSleep = obj.noSleep || false;
  94855. // My start position
  94856. var p = obj.pos || [0,0,0];
  94857. p = p.map(function(x) { return x * OIMO.INV_SCALE; });
  94858. // My size
  94859. var s = obj.size || [1,1,1];
  94860. s = s.map(function(x) { return x * OIMO.INV_SCALE; });
  94861. // My rotation in degre
  94862. var rot = obj.rot || [0,0,0];
  94863. rot = rot.map(function(x) { return x * OIMO.TO_RAD; });
  94864. var r = [];
  94865. for (var i=0; i<rot.length/3; i++){
  94866. var tmp = OIMO.EulerToAxis(rot[i+0], rot[i+1], rot[i+2]);
  94867. r.push(tmp[0]); r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
  94868. }
  94869. // My physics setting
  94870. var sc = obj.sc || new OIMO.ShapeConfig();
  94871. if(obj.config){
  94872. // The density of the shape.
  94873. sc.density = obj.config[0] || 1;
  94874. // The coefficient of friction of the shape.
  94875. sc.friction = obj.config[1] || 0.4;
  94876. // The coefficient of restitution of the shape.
  94877. sc.restitution = obj.config[2] || 0.2;
  94878. // The bits of the collision groups to which the shape belongs.
  94879. sc.belongsTo = obj.config[3] || 1;
  94880. // The bits of the collision groups with which the shape collides.
  94881. sc.collidesWith = obj.config[4] || 0xffffffff;
  94882. }
  94883. if(obj.massPos){
  94884. obj.massPos = obj.massPos.map(function(x) { return x * OIMO.INV_SCALE; });
  94885. sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
  94886. }
  94887. if(obj.massRot){
  94888. obj.massRot = obj.massRot.map(function(x) { return x * OIMO.TO_RAD; });
  94889. sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
  94890. }
  94891. // My rigidbody
  94892. this.body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
  94893. // My shapes
  94894. var shapes = [];
  94895. var type = obj.type || "box";
  94896. if( typeof type === 'string' ) type = [type];// single shape
  94897. var n, n2;
  94898. for(var i=0; i<type.length; i++){
  94899. n = i*3;
  94900. n2 = i*4;
  94901. switch(type[i]){
  94902. case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n+0]); break;
  94903. case "cylinder": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break; // fake cylinder
  94904. case "box": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break;
  94905. }
  94906. this.body.addShape(shapes[i]);
  94907. if(i>0){
  94908. //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
  94909. shapes[i].relativePosition = new OIMO.Vec3( p[n+0], p[n+1], p[n+2] );
  94910. if(r[n2+0]) shapes[i].relativeRotation = [ r[n2+0], r[n2+1], r[n2+2], r[n2+3] ];
  94911. }
  94912. }
  94913. // I'm static or i move
  94914. if(move){
  94915. if(obj.massPos || obj.massRot)this.body.setupMass(0x1, false);
  94916. else this.body.setupMass(0x1, true);
  94917. if(noSleep) this.body.allowSleep = false;
  94918. else this.body.allowSleep = true;
  94919. } else {
  94920. this.body.setupMass(0x2);
  94921. }
  94922. this.body.name = this.name;
  94923. this.sleeping = this.body.sleeping;
  94924. // finaly add to physics world
  94925. this.parent.addRigidBody(this.body);*/
  94926. }
  94927. OIMO.Body.prototype = {
  94928. constructor: OIMO.Body,
  94929. // SET
  94930. setPosition: function (pos) {
  94931. this.body.setPosition(pos);
  94932. },
  94933. setQuaternion: function (q) {
  94934. this.body.setQuaternion(q);
  94935. },
  94936. setRotation: function (rot) {
  94937. this.body.setRotation(rot);
  94938. },
  94939. // GET
  94940. getPosition: function () {
  94941. return this.body.getPosition();
  94942. },
  94943. getRotation: function () {
  94944. return this.body.getRotation();
  94945. },
  94946. getQuaternion: function () {
  94947. return this.body.getQuaternion();
  94948. },
  94949. getMatrix: function () {
  94950. return this.body.getMatrix();
  94951. },
  94952. getSleep: function () {
  94953. return this.body.sleeping;
  94954. },
  94955. // RESET
  94956. resetPosition: function (x, y, z) {
  94957. this.body.resetPosition(x, y, z);
  94958. },
  94959. resetRotation: function (x, y, z) {
  94960. this.body.resetRotation(x, y, z);
  94961. },
  94962. // force wakeup
  94963. awake: function () {
  94964. this.body.awake();
  94965. },
  94966. // remove rigidbody
  94967. remove: function () {
  94968. this.body.dispose();
  94969. //this.parent.removeRigidBody(this.body);
  94970. },
  94971. // test if this object hit another
  94972. checkContact: function (name) {
  94973. this.body.checkContact(name);
  94974. //this.parent.checkContact(this.name, name);
  94975. }
  94976. }
  94977. /**
  94978. * The main class of link.
  94979. * is for simplify creation process and data access of Joint
  94980. * all setting in object
  94981. *
  94982. * @author loth
  94983. */
  94984. OIMO.Link = function (Obj) {
  94985. var obj = Obj || {};
  94986. if (!obj.world) return;
  94987. if (obj.type === undefined) obj.type = "jointHinge";
  94988. this.name = obj.name || '';
  94989. // obsolete use world.add(obj)
  94990. this.joint = obj.world.add(obj);
  94991. // the world where i am
  94992. /*this.parent = obj.world;
  94993. this.name = obj.name || '';
  94994. var type = obj.type || "jointHinge";
  94995. var axe1 = obj.axe1 || [1,0,0];
  94996. var axe2 = obj.axe2 || [1,0,0];
  94997. var pos1 = obj.pos1 || [0,0,0];
  94998. var pos2 = obj.pos2 || [0,0,0];
  94999. pos1 = pos1.map(function(x){ return x * OIMO.INV_SCALE; });
  95000. pos2 = pos2.map(function(x){ return x * OIMO.INV_SCALE; });
  95001. var min, max;
  95002. if(type==="jointDistance"){
  95003. min = obj.min || 0;
  95004. max = obj.max || 10;
  95005. min = min*OIMO.INV_SCALE;
  95006. max = max*OIMO.INV_SCALE;
  95007. }else{
  95008. min = obj.min || 57.29578;
  95009. max = obj.max || 0;
  95010. min = min*OIMO.TO_RAD;
  95011. max = max*OIMO.TO_RAD;
  95012. }
  95013. var limit = obj.limit || null;
  95014. var spring = obj.spring || null;
  95015. var motor = obj.motor || null;
  95016. // joint setting
  95017. var jc = new OIMO.JointConfig();
  95018. jc.allowCollision = obj.collision || false;;
  95019. jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
  95020. jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
  95021. jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
  95022. jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
  95023. if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = obj.world.getByName(obj.body1);
  95024. if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = obj.world.getByName(obj.body2);
  95025. jc.body1 = obj.body1;
  95026. jc.body2 = obj.body2;
  95027. switch(type){
  95028. case "jointDistance": this.joint = new OIMO.DistanceJoint(jc, min, max);
  95029. if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);
  95030. if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
  95031. break;
  95032. case "jointHinge": this.joint = new OIMO.HingeJoint(jc, min, max);
  95033. if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
  95034. if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
  95035. break;
  95036. case "jointPrisme": this.joint = new OIMO.PrismaticJoint(jc, min, max); break;
  95037. case "jointSlide": this.joint = new OIMO.SliderJoint(jc, min, max); break;
  95038. case "jointBall": this.joint = new OIMO.BallAndSocketJoint(jc); break;
  95039. case "jointWheel": this.joint = new OIMO.WheelJoint(jc);
  95040. if(limit !== null) this.joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
  95041. if(spring !== null) this.joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
  95042. if(motor !== null) this.joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
  95043. break;
  95044. }
  95045. this.joint.name = this.name;
  95046. // finaly add to physics world
  95047. this.parent.addJoint(this.joint);*/
  95048. }
  95049. OIMO.Link.prototype = {
  95050. constructor: OIMO.Link,
  95051. getPosition: function () {
  95052. // array of two vect3 [point1, point2]
  95053. return this.joint.getPosition();
  95054. },
  95055. getMatrix: function () {
  95056. return this.joint.getMatrix();
  95057. },
  95058. // remove joint
  95059. remove: function () {
  95060. this.joint.dispose();
  95061. //this.parent.removeJoint(this.joint);
  95062. },
  95063. // force wakeup linked body
  95064. awake: function () {
  95065. this.joint.awake();
  95066. }
  95067. }
  95068. /**
  95069. * The Dictionary class for testing
  95070. * @author lo-th
  95071. */
  95072. OIMO.Dictionary = function () {
  95073. this.data = {};
  95074. this.keys = [];
  95075. };
  95076. OIMO.Dictionary.prototype = {
  95077. constructor: OIMO.Dictionary,
  95078. set: function (value) {
  95079. var key = value.id;
  95080. if (!this.get[key]) this.keys.push(key);
  95081. this.data[key] = value;
  95082. },
  95083. get: function (id) {
  95084. return this.data[id];
  95085. },
  95086. del: function (value) {
  95087. var k = this.keys;
  95088. var n = k.indexOf(value.id);
  95089. if (n > -1) {
  95090. delete this.data[k[n]];
  95091. k.splice(n, 1);
  95092. }
  95093. },
  95094. reset: function () {
  95095. var data = this.data, keys = this.keys, key;
  95096. while (keys.length > 0) {
  95097. key = keys.pop();
  95098. delete data[key];
  95099. }
  95100. }
  95101. };
  95102. OIMO.Performance = function (world) {
  95103. this.parent = world;
  95104. this.infos = new OIMO_ARRAY_TYPE(13);
  95105. this.f = [0, 0, 0];
  95106. this.types = ['None', 'BruteForce', 'Sweep & Prune', 'Bounding Volume Tree'];
  95107. this.broadPhase = this.types[this.parent.broadPhase.types];
  95108. this.version = OIMO.REVISION;
  95109. this.fps = 0;
  95110. this.broadPhaseTime = 0;
  95111. this.narrowPhaseTime = 0;
  95112. this.solvingTime = 0;
  95113. //this.updatingTime = 0;
  95114. this.totalTime = 0;
  95115. };
  95116. OIMO.Performance.prototype = {
  95117. upfps: function () {
  95118. this.f[1] = Date.now();
  95119. 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]++;
  95120. },
  95121. updatingTime: function () {
  95122. return OIMO.fix(this.totalTime - (this.broadPhaseTime + this.narrowPhaseTime + this.solvingTime));
  95123. },
  95124. show: function () {
  95125. var info = [
  95126. "Oimo.js " + this.version + "<br>",
  95127. this.broadPhase + "<br><br>",
  95128. "FPS: " + this.fps + " fps<br><br>",
  95129. "rigidbody " + this.parent.numRigidBodies + "<br>",
  95130. "contact &nbsp;&nbsp;" + this.parent.numContacts + "<br>",
  95131. "ct-point &nbsp;" + this.parent.numContactPoints + "<br>",
  95132. "paircheck " + this.parent.broadPhase.numPairChecks + "<br>",
  95133. "island &nbsp;&nbsp;&nbsp;" + this.parent.numIslands + "<br><br>",
  95134. "Time in milliseconde<br><br>",
  95135. "broad-phase &nbsp;" + OIMO.fix(this.broadPhaseTime) + "<br>",
  95136. "narrow-phase " + OIMO.fix(this.narrowPhaseTime) + "<br>",
  95137. "solving &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.solvingTime) + "<br>",
  95138. "total &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.totalTime) + "<br>",
  95139. "updating &nbsp;&nbsp;&nbsp;&nbsp;" + this.updatingTime() + "<br>"
  95140. ].join("\n");
  95141. return info;
  95142. },
  95143. toArray: function () {
  95144. this.infos[0] = this.parent.broadPhase.types;
  95145. this.infos[1] = this.parent.numRigidBodies;
  95146. this.infos[2] = this.parent.numContacts;
  95147. this.infos[3] = this.parent.broadPhase.numPairChecks;
  95148. this.infos[4] = this.parent.numContactPoints;
  95149. this.infos[5] = this.parent.numIslands;
  95150. this.infos[6] = this.broadPhaseTime;
  95151. this.infos[7] = this.narrowPhaseTime;
  95152. this.infos[8] = this.solvingTime;
  95153. this.infos[9] = this.updatingTime();
  95154. this.infos[10] = this.totalTime;
  95155. this.infos[11] = this.fps;
  95156. return this.infos;
  95157. }
  95158. };
  95159. OIMO.Mat44 = function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  95160. this.elements = new OIMO_ARRAY_TYPE(16);
  95161. var te = this.elements;
  95162. te[0] = (n11 !== undefined) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  95163. te[1] = n21 || 0; te[5] = (n22 !== undefined) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  95164. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = (n33 !== undefined) ? n33 : 1; te[14] = n34 || 0;
  95165. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = (n44 !== undefined) ? n44 : 1;
  95166. };
  95167. OIMO.Mat44.prototype = {
  95168. constructor: OIMO.Mat44,
  95169. set: function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  95170. var te = this.elements;
  95171. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  95172. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  95173. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  95174. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  95175. return this;
  95176. }/*,
  95177. extractRotation: function () {
  95178. var v1 = new THREE.Vector3();
  95179. return function ( m ) {
  95180. var te = this.elements;
  95181. var me = m.elements;
  95182. var scaleX = 1 / v1.set( me[ 0 ], me[ 1 ], me[ 2 ] ).length();
  95183. var scaleY = 1 / v1.set( me[ 4 ], me[ 5 ], me[ 6 ] ).length();
  95184. var scaleZ = 1 / v1.set( me[ 8 ], me[ 9 ], me[ 10 ] ).length();
  95185. te[ 0 ] = me[ 0 ] * scaleX;
  95186. te[ 1 ] = me[ 1 ] * scaleX;
  95187. te[ 2 ] = me[ 2 ] * scaleX;
  95188. te[ 4 ] = me[ 4 ] * scaleY;
  95189. te[ 5 ] = me[ 5 ] * scaleY;
  95190. te[ 6 ] = me[ 6 ] * scaleY;
  95191. te[ 8 ] = me[ 8 ] * scaleZ;
  95192. te[ 9 ] = me[ 9 ] * scaleZ;
  95193. te[ 10 ] = me[ 10 ] * scaleZ;
  95194. return this;
  95195. };
  95196. }() */
  95197. }
  95198. OIMO.Mat33 = function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  95199. this.elements = new OIMO_ARRAY_TYPE(9);
  95200. var te = this.elements;
  95201. this.init(
  95202. (e00 !== undefined) ? e00 : 1, e01 || 0, e02 || 0,
  95203. e10 || 0, (e11 !== undefined) ? e11 : 1, e12 || 0,
  95204. e20 || 0, e21 || 0, (e22 !== undefined) ? e22 : 1
  95205. );
  95206. };
  95207. OIMO.Mat33.prototype = {
  95208. constructor: OIMO.Mat33,
  95209. set: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  95210. var te = this.elements;
  95211. te[0] = e00; te[1] = e01; te[2] = e02;
  95212. te[3] = e10; te[4] = e11; te[5] = e12;
  95213. te[6] = e20; te[7] = e21; te[8] = e22;
  95214. return this;
  95215. },
  95216. init: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  95217. var te = this.elements;
  95218. te[0] = e00; te[1] = e01; te[2] = e02;
  95219. te[3] = e10; te[4] = e11; te[5] = e12;
  95220. te[6] = e20; te[7] = e21; te[8] = e22;
  95221. return this;
  95222. },
  95223. multiply: function (s) {
  95224. var te = this.elements;
  95225. te[0] *= s; te[1] *= s; te[2] *= s;
  95226. te[3] *= s; te[4] *= s; te[5] *= s;
  95227. te[6] *= s; te[7] *= s; te[8] *= s;
  95228. return this;
  95229. },
  95230. add: function (m1, m2) {
  95231. var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
  95232. te[0] = tem1[0] + tem2[0]; te[1] = tem1[1] + tem2[1]; te[2] = tem1[2] + tem2[2];
  95233. te[3] = tem1[3] + tem2[3]; te[4] = tem1[4] + tem2[4]; te[5] = tem1[5] + tem2[5];
  95234. te[6] = tem1[6] + tem2[6]; te[7] = tem1[7] + tem2[7]; te[8] = tem1[8] + tem2[8];
  95235. return this;
  95236. },
  95237. addEqual: function (m) {
  95238. var te = this.elements, tem = m.elements;
  95239. te[0] += tem[0]; te[1] += tem[1]; te[2] += tem[2];
  95240. te[3] += tem[3]; te[4] += tem[4]; te[5] += tem[5];
  95241. te[6] += tem[6]; te[7] += tem[7]; te[8] += tem[8];
  95242. return this;
  95243. },
  95244. sub: function (m1, m2) {
  95245. var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
  95246. te[0] = tem1[0] - tem2[0]; te[1] = tem1[1] - tem2[1]; te[2] = tem1[2] - tem2[2];
  95247. te[3] = tem1[3] - tem2[3]; te[4] = tem1[4] - tem2[4]; te[5] = tem1[5] - tem2[5];
  95248. te[6] = tem1[6] - tem2[6]; te[7] = tem1[7] - tem2[7]; te[8] = tem1[8] - tem2[8];
  95249. return this;
  95250. },
  95251. subEqual: function (m) {
  95252. var te = this.elements, tem = m.elements;
  95253. te[0] -= tem[0]; te[1] -= tem[1]; te[2] -= tem[2];
  95254. te[3] -= tem[3]; te[4] -= tem[4]; te[5] -= tem[5];
  95255. te[6] -= tem[6]; te[7] -= tem[7]; te[8] -= tem[8];
  95256. return this;
  95257. },
  95258. scale: function (m, s) {
  95259. var te = this.elements, tm = m.elements;
  95260. te[0] = tm[0] * s; te[1] = tm[1] * s; te[2] = tm[2] * s;
  95261. te[3] = tm[3] * s; te[4] = tm[4] * s; te[5] = tm[5] * s;
  95262. te[6] = tm[6] * s; te[7] = tm[7] * s; te[8] = tm[8] * s;
  95263. return this;
  95264. },
  95265. scaleEqual: function (s) {
  95266. var te = this.elements;
  95267. te[0] *= s; te[1] *= s; te[2] *= s;
  95268. te[3] *= s; te[4] *= s; te[5] *= s;
  95269. te[6] *= s; te[7] *= s; te[8] *= s;
  95270. return this;
  95271. },
  95272. mul: function (m1, m2) {
  95273. var te = this.elements, tm1 = m1.elements, tm2 = m2.elements,
  95274. a0 = tm1[0], a3 = tm1[3], a6 = tm1[6],
  95275. a1 = tm1[1], a4 = tm1[4], a7 = tm1[7],
  95276. a2 = tm1[2], a5 = tm1[5], a8 = tm1[8],
  95277. b0 = tm2[0], b3 = tm2[3], b6 = tm2[6],
  95278. b1 = tm2[1], b4 = tm2[4], b7 = tm2[7],
  95279. b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
  95280. te[0] = a0 * b0 + a1 * b3 + a2 * b6;
  95281. te[1] = a0 * b1 + a1 * b4 + a2 * b7;
  95282. te[2] = a0 * b2 + a1 * b5 + a2 * b8;
  95283. te[3] = a3 * b0 + a4 * b3 + a5 * b6;
  95284. te[4] = a3 * b1 + a4 * b4 + a5 * b7;
  95285. te[5] = a3 * b2 + a4 * b5 + a5 * b8;
  95286. te[6] = a6 * b0 + a7 * b3 + a8 * b6;
  95287. te[7] = a6 * b1 + a7 * b4 + a8 * b7;
  95288. te[8] = a6 * b2 + a7 * b5 + a8 * b8;
  95289. return this;
  95290. },
  95291. mulScale: function (m, sx, sy, sz, Prepend) {
  95292. var prepend = Prepend || false;
  95293. var te = this.elements, tm = m.elements;
  95294. if (prepend) {
  95295. te[0] = sx * tm[0]; te[1] = sx * tm[1]; te[2] = sx * tm[2];
  95296. te[3] = sy * tm[3]; te[4] = sy * tm[4]; te[5] = sy * tm[5];
  95297. te[6] = sz * tm[6]; te[7] = sz * tm[7]; te[8] = sz * tm[8];
  95298. } else {
  95299. te[0] = tm[0] * sx; te[1] = tm[1] * sy; te[2] = tm[2] * sz;
  95300. te[3] = tm[3] * sx; te[4] = tm[4] * sy; te[5] = tm[5] * sz;
  95301. te[6] = tm[6] * sx; te[7] = tm[7] * sy; te[8] = tm[8] * sz;
  95302. }
  95303. return this;
  95304. },
  95305. mulRotate: function (m, rad, ax, ay, az, Prepend) {
  95306. var prepend = Prepend || false;
  95307. var s = OIMO.sin(rad);
  95308. var c = OIMO.cos(rad);
  95309. var c1 = 1 - c;
  95310. var r00 = ax * ax * c1 + c;
  95311. var r01 = ax * ay * c1 - az * s;
  95312. var r02 = ax * az * c1 + ay * s;
  95313. var r10 = ay * ax * c1 + az * s;
  95314. var r11 = ay * ay * c1 + c;
  95315. var r12 = ay * az * c1 - ax * s;
  95316. var r20 = az * ax * c1 - ay * s;
  95317. var r21 = az * ay * c1 + ax * s;
  95318. var r22 = az * az * c1 + c;
  95319. var tm = m.elements;
  95320. var a0 = tm[0], a3 = tm[3], a6 = tm[6];
  95321. var a1 = tm[1], a4 = tm[4], a7 = tm[7];
  95322. var a2 = tm[2], a5 = tm[5], a8 = tm[8];
  95323. var te = this.elements;
  95324. if (prepend) {
  95325. te[0] = r00 * a0 + r01 * a3 + r02 * a6;
  95326. te[1] = r00 * a1 + r01 * a4 + r02 * a7;
  95327. te[2] = r00 * a2 + r01 * a5 + r02 * a8;
  95328. te[3] = r10 * a0 + r11 * a3 + r12 * a6;
  95329. te[4] = r10 * a1 + r11 * a4 + r12 * a7;
  95330. te[5] = r10 * a2 + r11 * a5 + r12 * a8;
  95331. te[6] = r20 * a0 + r21 * a3 + r22 * a6;
  95332. te[7] = r20 * a1 + r21 * a4 + r22 * a7;
  95333. te[8] = r20 * a2 + r21 * a5 + r22 * a8;
  95334. } else {
  95335. te[0] = a0 * r00 + a1 * r10 + a2 * r20;
  95336. te[1] = a0 * r01 + a1 * r11 + a2 * r21;
  95337. te[2] = a0 * r02 + a1 * r12 + a2 * r22;
  95338. te[3] = a3 * r00 + a4 * r10 + a5 * r20;
  95339. te[4] = a3 * r01 + a4 * r11 + a5 * r21;
  95340. te[5] = a3 * r02 + a4 * r12 + a5 * r22;
  95341. te[6] = a6 * r00 + a7 * r10 + a8 * r20;
  95342. te[7] = a6 * r01 + a7 * r11 + a8 * r21;
  95343. te[8] = a6 * r02 + a7 * r12 + a8 * r22;
  95344. }
  95345. return this;
  95346. },
  95347. transpose: function (m) {
  95348. var te = this.elements, tm = m.elements;
  95349. te[0] = tm[0]; te[1] = tm[3]; te[2] = tm[6];
  95350. te[3] = tm[1]; te[4] = tm[4]; te[5] = tm[7];
  95351. te[6] = tm[2]; te[7] = tm[5]; te[8] = tm[8];
  95352. return this;
  95353. },
  95354. setQuat: function (q) {
  95355. var te = this.elements,
  95356. x2 = 2 * q.x, y2 = 2 * q.y, z2 = 2 * q.z,
  95357. xx = q.x * x2, yy = q.y * y2, zz = q.z * z2,
  95358. xy = q.x * y2, yz = q.y * z2, xz = q.x * z2,
  95359. sx = q.s * x2, sy = q.s * y2, sz = q.s * z2;
  95360. te[0] = 1 - yy - zz;
  95361. te[1] = xy - sz;
  95362. te[2] = xz + sy;
  95363. te[3] = xy + sz;
  95364. te[4] = 1 - xx - zz;
  95365. te[5] = yz - sx;
  95366. te[6] = xz - sy;
  95367. te[7] = yz + sx;
  95368. te[8] = 1 - xx - yy;
  95369. return this;
  95370. },
  95371. invert: function (m) {
  95372. var te = this.elements, tm = m.elements,
  95373. a0 = tm[0], a3 = tm[3], a6 = tm[6],
  95374. a1 = tm[1], a4 = tm[4], a7 = tm[7],
  95375. a2 = tm[2], a5 = tm[5], a8 = tm[8],
  95376. b01 = a4 * a8 - a7 * a5,
  95377. b11 = a7 * a2 - a1 * a8,
  95378. b21 = a1 * a5 - a4 * a2,
  95379. dt = a0 * (b01) + a3 * (b11) + a6 * (b21);
  95380. if (dt != 0) { dt = 1.0 / dt; }
  95381. te[0] = dt * b01;//(a4*a8 - a5*a7);
  95382. te[1] = dt * b11;//(a2*a7 - a1*a8);
  95383. te[2] = dt * b21;//(a1*a5 - a2*a4);
  95384. te[3] = dt * (a5 * a6 - a3 * a8);
  95385. te[4] = dt * (a0 * a8 - a2 * a6);
  95386. te[5] = dt * (a2 * a3 - a0 * a5);
  95387. te[6] = dt * (a3 * a7 - a4 * a6);
  95388. te[7] = dt * (a1 * a6 - a0 * a7);
  95389. te[8] = dt * (a0 * a4 - a1 * a3);
  95390. return this;
  95391. },
  95392. /*copy: function(m){
  95393. var te = this.elements, tem = m.elements;
  95394. te[0] = tem[0]; te[1] = tem[1]; te[2] = tem[2];
  95395. te[3] = tem[3]; te[4] = tem[4]; te[5] = tem[5];
  95396. te[6] = tem[6]; te[7] = tem[7]; te[8] = tem[8];
  95397. return this;
  95398. },*/
  95399. toEuler: function () { // not work !!
  95400. function clamp(x) {
  95401. return OIMO.min(OIMO.max(x, -1), 1);
  95402. }
  95403. var te = this.elements;
  95404. var m11 = te[0], m12 = te[3], m13 = te[6];
  95405. var m21 = te[1], m22 = te[4], m23 = te[7];
  95406. var m31 = te[2], m32 = te[5], m33 = te[8];
  95407. var p = new OIMO.Vec3();
  95408. var d = new OIMO.Quat();
  95409. var s;
  95410. p.y = OIMO.asin(clamp(m13));
  95411. if (OIMO.abs(m13) < 0.99999) {
  95412. p.x = OIMO.atan2(-m23, m33);
  95413. p.z = OIMO.atan2(-m12, m11);
  95414. } else {
  95415. p.x = OIMO.atan2(m32, m22);
  95416. p.z = 0;
  95417. }
  95418. return p;
  95419. },
  95420. /*clone: function(){
  95421. var te = this.elements;
  95422. return new OIMO.Mat33(
  95423. te[0], te[1], te[2],
  95424. te[3], te[4], te[5],
  95425. te[6], te[7], te[8]
  95426. );
  95427. },*/
  95428. toString: function () {
  95429. var te = this.elements;
  95430. var text =
  95431. "Mat33|" + te[0].toFixed(4) + ", " + te[1].toFixed(4) + ", " + te[2].toFixed(4) + "|\n" +
  95432. " |" + te[3].toFixed(4) + ", " + te[4].toFixed(4) + ", " + te[5].toFixed(4) + "|\n" +
  95433. " |" + te[6].toFixed(4) + ", " + te[7].toFixed(4) + ", " + te[8].toFixed(4) + "|";
  95434. return text;
  95435. },
  95436. // OK
  95437. multiplyScalar: function (s) {
  95438. var te = this.elements;
  95439. te[0] *= s; te[3] *= s; te[6] *= s;
  95440. te[1] *= s; te[4] *= s; te[7] *= s;
  95441. te[2] *= s; te[5] *= s; te[8] *= s;
  95442. return this;
  95443. },
  95444. identity: function () {
  95445. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  95446. return this;
  95447. },
  95448. clone: function () {
  95449. return new this.constructor().fromArray(this.elements);
  95450. },
  95451. copy: function (m) {
  95452. var me = m.elements;
  95453. this.set(
  95454. me[0], me[3], me[6],
  95455. me[1], me[4], me[7],
  95456. me[2], me[5], me[8]
  95457. );
  95458. return this;
  95459. },
  95460. fromArray: function (array) {
  95461. this.elements.set(array);
  95462. return this;
  95463. },
  95464. toArray: function () {
  95465. var te = this.elements;
  95466. return [
  95467. te[0], te[1], te[2],
  95468. te[3], te[4], te[5],
  95469. te[6], te[7], te[8]
  95470. ];
  95471. }
  95472. };
  95473. OIMO.Quat = function (s, x, y, z) {
  95474. this.s = (s !== undefined) ? s : 1;
  95475. this.x = x || 0;
  95476. this.y = y || 0;
  95477. this.z = z || 0;
  95478. };
  95479. OIMO.Quat.prototype = {
  95480. constructor: OIMO.Quat,
  95481. set: function (x, y, z, w) {
  95482. this.x = x;
  95483. this.y = y;
  95484. this.z = z;
  95485. this.s = w;
  95486. return this;
  95487. },
  95488. init: function (s, x, y, z) {
  95489. this.s = (s !== undefined) ? s : 1;
  95490. this.x = x || 0;
  95491. this.y = y || 0;
  95492. this.z = z || 0;
  95493. return this;
  95494. },
  95495. add: function (q1, q2) {
  95496. this.s = q1.s + q2.s;
  95497. this.x = q1.x + q2.x;
  95498. this.y = q1.y + q2.y;
  95499. this.z = q1.z + q2.z;
  95500. return this;
  95501. },
  95502. addTime: function (v, t) {
  95503. var x = v.x;
  95504. var y = v.y;
  95505. var z = v.z;
  95506. var qs = this.s;
  95507. var qx = this.x;
  95508. var qy = this.y;
  95509. var qz = this.z;
  95510. t *= 0.5;
  95511. var ns = (-x * qx - y * qy - z * qz) * t;
  95512. var nx = (x * qs + y * qz - z * qy) * t;
  95513. var ny = (-x * qz + y * qs + z * qx) * t;
  95514. var nz = (x * qy - y * qx + z * qs) * t;
  95515. qs += ns;
  95516. qx += nx;
  95517. qy += ny;
  95518. qz += nz;
  95519. var s = 1 / OIMO.sqrt(qs * qs + qx * qx + qy * qy + qz * qz);
  95520. this.s = qs * s;
  95521. this.x = qx * s;
  95522. this.y = qy * s;
  95523. this.z = qz * s;
  95524. return this;
  95525. },
  95526. sub: function (q1, q2) {
  95527. this.s = q1.s - q2.s;
  95528. this.x = q1.x - q2.x;
  95529. this.y = q1.y - q2.y;
  95530. this.z = q1.z - q2.z;
  95531. return this;
  95532. },
  95533. scale: function (q, s) {
  95534. this.s = q.s * s;
  95535. this.x = q.x * s;
  95536. this.y = q.y * s;
  95537. this.z = q.z * s;
  95538. return this;
  95539. },
  95540. mul: function (q1, q2) {
  95541. var ax = q1.x, ay = q1.y, az = q1.z, as = q1.s,
  95542. bx = q2.x, by = q2.y, bz = q2.z, bs = q2.s;
  95543. this.x = ax * bs + as * bx + ay * bz - az * by;
  95544. this.y = ay * bs + as * by + az * bx - ax * bz;
  95545. this.z = az * bs + as * bz + ax * by - ay * bx;
  95546. this.s = as * bs - ax * bx - ay * by - az * bz;
  95547. return this;
  95548. },
  95549. arc: function (v1, v2) {
  95550. var x1 = v1.x;
  95551. var y1 = v1.y;
  95552. var z1 = v1.z;
  95553. var x2 = v2.x;
  95554. var y2 = v2.y;
  95555. var z2 = v2.z;
  95556. var d = x1 * x2 + y1 * y2 + z1 * z2;
  95557. if (d == -1) {
  95558. x2 = y1 * x1 - z1 * z1;
  95559. y2 = -z1 * y1 - x1 * x1;
  95560. z2 = x1 * z1 + y1 * y1;
  95561. d = 1 / OIMO.sqrt(x2 * x2 + y2 * y2 + z2 * z2);
  95562. this.s = 0;
  95563. this.x = x2 * d;
  95564. this.y = y2 * d;
  95565. this.z = z2 * d;
  95566. return this;
  95567. }
  95568. var cx = y1 * z2 - z1 * y2;
  95569. var cy = z1 * x2 - x1 * z2;
  95570. var cz = x1 * y2 - y1 * x2;
  95571. this.s = OIMO.sqrt((1 + d) * 0.5);
  95572. d = 0.5 / this.s;
  95573. this.x = cx * d;
  95574. this.y = cy * d;
  95575. this.z = cz * d;
  95576. return this;
  95577. },
  95578. normalize: function (q) {
  95579. var len = OIMO.sqrt(q.s * q.s + q.x * q.x + q.y * q.y + q.z * q.z);
  95580. if (len > 0) { len = 1 / len; }
  95581. this.s = q.s * len;
  95582. this.x = q.x * len;
  95583. this.y = q.y * len;
  95584. this.z = q.z * len;
  95585. return this;
  95586. },
  95587. invert: function (q) {
  95588. this.s = q.s;
  95589. this.x = -q.x;
  95590. this.y = -q.y;
  95591. this.z = -q.z;
  95592. return this;
  95593. },
  95594. length: function () {
  95595. return OIMO.sqrt(this.s * this.s + this.x * this.x + this.y * this.y + this.z * this.z);
  95596. },
  95597. copy: function (q) {
  95598. this.s = q.s;
  95599. this.x = q.x;
  95600. this.y = q.y;
  95601. this.z = q.z;
  95602. return this;
  95603. },
  95604. testDiff: function (q) {
  95605. if (this.s !== q.s || this.x !== q.x || this.y !== q.y || this.z !== q.z) return true;
  95606. else return false;
  95607. },
  95608. clone: function (q) {
  95609. return new OIMO.Quat(this.s, this.x, this.y, this.z);
  95610. },
  95611. toString: function () {
  95612. return "Quat[" + this.s.toFixed(4) + ", (" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + ")]";
  95613. }
  95614. }
  95615. // for three easy export
  95616. OIMO.Quaternion = function (x, y, z, w) {
  95617. this.x = x || 0;
  95618. this.y = y || 0;
  95619. this.z = z || 0;
  95620. this.w = (w !== undefined) ? w : 1;
  95621. };
  95622. OIMO.Quaternion.prototype = {
  95623. constructor: OIMO.Quaternion,
  95624. setFromRotationMatrix: function (m) {
  95625. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  95626. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  95627. var te = m.elements,
  95628. m11 = te[0], m12 = te[1], m13 = te[2],
  95629. m21 = te[3], m22 = te[4], m23 = te[5],
  95630. m31 = te[6], m32 = te[7], m33 = te[8],
  95631. trace = m11 + m22 + m33,
  95632. s;
  95633. if (trace > 0) {
  95634. s = 0.5 / OIMO.sqrt(trace + 1.0);
  95635. this.w = 0.25 / s;
  95636. this.x = (m32 - m23) * s;
  95637. this.y = (m13 - m31) * s;
  95638. this.z = (m21 - m12) * s;
  95639. } else if (m11 > m22 && m11 > m33) {
  95640. s = 2.0 * OIMO.sqrt(1.0 + m11 - m22 - m33);
  95641. this.w = (m32 - m23) / s;
  95642. this.x = 0.25 * s;
  95643. this.y = (m12 + m21) / s;
  95644. this.z = (m13 + m31) / s;
  95645. } else if (m22 > m33) {
  95646. s = 2.0 * OIMO.sqrt(1.0 + m22 - m11 - m33);
  95647. this.w = (m13 - m31) / s;
  95648. this.x = (m12 + m21) / s;
  95649. this.y = 0.25 * s;
  95650. this.z = (m23 + m32) / s;
  95651. } else {
  95652. s = 2.0 * OIMO.sqrt(1.0 + m33 - m11 - m22);
  95653. this.w = (m21 - m12) / s;
  95654. this.x = (m13 + m31) / s;
  95655. this.y = (m23 + m32) / s;
  95656. this.z = 0.25 * s;
  95657. }
  95658. //this.onChangeCallback();
  95659. return this;
  95660. }
  95661. }
  95662. OIMO.Vec3 = function (x, y, z) {
  95663. this.x = x || 0;
  95664. this.y = y || 0;
  95665. this.z = z || 0;
  95666. };
  95667. OIMO.Vec3.prototype = {
  95668. constructor: OIMO.Vec3,
  95669. init: function (x, y, z) {
  95670. this.x = x || 0;
  95671. this.y = y || 0;
  95672. this.z = z || 0;
  95673. return this;
  95674. },
  95675. set: function (x, y, z) {
  95676. this.x = x;
  95677. this.y = y;
  95678. this.z = z;
  95679. return this;
  95680. },
  95681. add: function (v1, v2) {
  95682. this.x = v1.x + v2.x;
  95683. this.y = v1.y + v2.y;
  95684. this.z = v1.z + v2.z;
  95685. return this;
  95686. },
  95687. addEqual: function (v) {
  95688. this.x += v.x;
  95689. this.y += v.y;
  95690. this.z += v.z;
  95691. return this;
  95692. },
  95693. addTime: function (v, t) {
  95694. this.x += v.x * t;
  95695. this.y += v.y * t;
  95696. this.z += v.z * t;
  95697. return this;
  95698. },
  95699. sub: function (v1, v2) {
  95700. this.x = v1.x - v2.x;
  95701. this.y = v1.y - v2.y;
  95702. this.z = v1.z - v2.z;
  95703. return this;
  95704. },
  95705. subEqual: function (v) {
  95706. this.x -= v.x;
  95707. this.y -= v.y;
  95708. this.z -= v.z;
  95709. return this;
  95710. },
  95711. addScale: function (v, s) {
  95712. this.x += v.x * s;
  95713. this.y += v.y * s;
  95714. this.z += v.z * s;
  95715. return this;
  95716. },
  95717. scale: function (v, s) {
  95718. this.x = v.x * s;
  95719. this.y = v.y * s;
  95720. this.z = v.z * s;
  95721. return this;
  95722. },
  95723. scaleEqual: function (s) {
  95724. this.x *= s;
  95725. this.y *= s;
  95726. this.z *= s;
  95727. return this;
  95728. },
  95729. /*dot: function(v){
  95730. return this.x*v.x+this.y*v.y+this.z*v.z;
  95731. },*/
  95732. cross: function (v1, v2) {
  95733. var ax = v1.x, ay = v1.y, az = v1.z,
  95734. bx = v2.x, by = v2.y, bz = v2.z;
  95735. this.x = ay * bz - az * by;
  95736. this.y = az * bx - ax * bz;
  95737. this.z = ax * by - ay * bx;
  95738. return this;
  95739. },
  95740. mul: function (o, v, m) {
  95741. var te = m.elements;
  95742. this.x = o.x + v.x * te[0] + v.y * te[1] + v.z * te[2];
  95743. this.y = o.y + v.x * te[3] + v.y * te[4] + v.z * te[5];
  95744. this.z = o.z + v.x * te[6] + v.y * te[7] + v.z * te[8];
  95745. return this;
  95746. },
  95747. mulMat: function (m, v) {
  95748. var te = m.elements;
  95749. this.x = te[0] * v.x + te[1] * v.y + te[2] * v.z;
  95750. this.y = te[3] * v.x + te[4] * v.y + te[5] * v.z;
  95751. this.z = te[6] * v.x + te[7] * v.y + te[8] * v.z;
  95752. return this;
  95753. },
  95754. normalize: function (v) {
  95755. var x = v.x, y = v.y, z = v.z;
  95756. var l = x * x + y * y + z * z;
  95757. if (l > 0) {
  95758. l = 1 / OIMO.sqrt(l);
  95759. this.x = x * l;
  95760. this.y = y * l;
  95761. this.z = z * l;
  95762. }
  95763. return this;
  95764. },
  95765. /*norm: function(){
  95766. var x = this.x, y = this.y, z = this.z;
  95767. var l = x*x + y*y + z*z;
  95768. if (l > 0) {
  95769. l = 1 / OIMO.sqrt(l);
  95770. this.x = x*l;
  95771. this.y = y*l;
  95772. this.z = z*l;
  95773. }
  95774. return this;
  95775. },*/
  95776. invert: function (v) {
  95777. this.x = -v.x;
  95778. this.y = -v.y;
  95779. this.z = -v.z;
  95780. return this;
  95781. },
  95782. /*length: function(){
  95783. var x = this.x, y = this.y, z = this.z;
  95784. return OIMO.sqrt(x*x + y*y + z*z);
  95785. },*/
  95786. negate: function () {
  95787. this.x = -this.x;
  95788. this.y = -this.y;
  95789. this.z = -this.z;
  95790. return this;
  95791. },
  95792. dot: function (v) {
  95793. return this.x * v.x + this.y * v.y + this.z * v.z;
  95794. },
  95795. lengthSq: function () {
  95796. return this.x * this.x + this.y * this.y + this.z * this.z;
  95797. },
  95798. length: function () {
  95799. return OIMO.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  95800. },
  95801. /*len: function(){
  95802. var x = this.x, y = this.y, z = this.z;
  95803. return x*x + y*y + z*z;
  95804. },*/
  95805. copy: function (v) {
  95806. this.x = v.x;
  95807. this.y = v.y;
  95808. this.z = v.z;
  95809. return this;
  95810. },
  95811. applyQuaternion: function (q) {
  95812. var x = this.x;
  95813. var y = this.y;
  95814. var z = this.z;
  95815. var qx = q.x;
  95816. var qy = q.y;
  95817. var qz = q.z;
  95818. var qs = q.s;
  95819. // calculate quat * vector
  95820. var ix = qs * x + qy * z - qz * y;
  95821. var iy = qs * y + qz * x - qx * z;
  95822. var iz = qs * z + qx * y - qy * x;
  95823. var iw = -qx * x - qy * y - qz * z;
  95824. // calculate result * inverse quat
  95825. this.x = ix * qs + iw * -qx + iy * -qz - iz * -qy;
  95826. this.y = iy * qs + iw * -qy + iz * -qx - ix * -qz;
  95827. this.z = iz * qs + iw * -qz + ix * -qy - iy * -qx;
  95828. return this;
  95829. },
  95830. testZero: function () {
  95831. if (this.x !== 0 || this.y !== 0 || this.z !== 0) return true;
  95832. else return false;
  95833. },
  95834. testDiff: function (v) {
  95835. return ((v.x !== this.x) || (v.y !== this.y) || (v.z !== this.z));
  95836. //if(this.x!==v.x || this.y!==v.y || this.z!==v.z) return true;
  95837. //else return false;
  95838. },
  95839. equals: function (v) {
  95840. return ((v.x === this.x) && (v.y === this.y) && (v.z === this.z));
  95841. },
  95842. clone: function () {
  95843. return new this.constructor(this.x, this.y, this.z);
  95844. },
  95845. toString: function () {
  95846. return "Vec3[" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + "]";
  95847. },
  95848. multiplyScalar: function (scalar) {
  95849. if (isFinite(scalar)) {
  95850. this.x *= scalar;
  95851. this.y *= scalar;
  95852. this.z *= scalar;
  95853. } else {
  95854. this.x = 0;
  95855. this.y = 0;
  95856. this.z = 0;
  95857. }
  95858. return this;
  95859. },
  95860. divideScalar: function (scalar) {
  95861. return this.multiplyScalar(1 / scalar);
  95862. },
  95863. // TODO rename to normalize
  95864. norm: function () {
  95865. return this.divideScalar(this.length());
  95866. },
  95867. }
  95868. OIMO.Euler = function (x, y, z, order) {
  95869. this._x = x || 0;
  95870. this._y = y || 0;
  95871. this._z = z || 0;
  95872. this._order = order || OIMO.Euler.DefaultOrder;
  95873. };
  95874. OIMO.Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  95875. OIMO.Euler.DefaultOrder = 'XYZ';
  95876. OIMO.clamp = function (x, a, b) {
  95877. return (x < a) ? a : ((x > b) ? b : x);
  95878. }
  95879. OIMO.Euler.prototype = {
  95880. constructor: OIMO.Euler,
  95881. _x: 0, _y: 0, _z: 0, _order: OIMO.Euler.DefaultOrder,
  95882. get x() {
  95883. return this._x;
  95884. },
  95885. set x(value) {
  95886. this._x = value;
  95887. this.onChangeCallback();
  95888. },
  95889. get y() {
  95890. return this._y;
  95891. },
  95892. set y(value) {
  95893. this._y = value;
  95894. this.onChangeCallback();
  95895. },
  95896. get z() {
  95897. return this._z;
  95898. },
  95899. set z(value) {
  95900. this._z = value;
  95901. this.onChangeCallback();
  95902. },
  95903. get order() {
  95904. return this._order;
  95905. },
  95906. set order(value) {
  95907. this._order = value;
  95908. this.onChangeCallback();
  95909. },
  95910. set: function (x, y, z, order) {
  95911. this._x = x;
  95912. this._y = y;
  95913. this._z = z;
  95914. this._order = order || this._order;
  95915. this.onChangeCallback();
  95916. return this;
  95917. },
  95918. copy: function (euler) {
  95919. this._x = euler._x;
  95920. this._y = euler._y;
  95921. this._z = euler._z;
  95922. this._order = euler._order;
  95923. this.onChangeCallback();
  95924. return this;
  95925. },
  95926. setFromRotationMatrix: function (m, order) {
  95927. var clamp = OIMO.clamp;
  95928. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  95929. var te = m.elements;
  95930. /*var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  95931. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  95932. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];*/
  95933. var m11 = te[0], m12 = te[1], m13 = te[2],
  95934. m21 = te[3], m22 = te[4], m23 = te[5],
  95935. m31 = te[6], m32 = te[7], m33 = te[8];
  95936. order = order || this._order;
  95937. if (order === 'XYZ') {
  95938. this._y = OIMO.asin(clamp(m13, -1, 1));
  95939. if (OIMO.abs(m13) < 0.99999) {
  95940. this._x = OIMO.atan2(-m23, m33);
  95941. this._z = OIMO.atan2(-m12, m11);
  95942. } else {
  95943. this._x = OIMO.atan2(m32, m22);
  95944. this._z = 0;
  95945. }
  95946. } else if (order === 'YXZ') {
  95947. this._x = OIMO.asin(-clamp(m23, -1, 1));
  95948. if (OIMO.abs(m23) < 0.99999) {
  95949. this._y = OIMO.atan2(m13, m33);
  95950. this._z = OIMO.atan2(m21, m22);
  95951. } else {
  95952. this._y = OIMO.atan2(-m31, m11);
  95953. this._z = 0;
  95954. }
  95955. } else if (order === 'ZXY') {
  95956. this._x = OIMO.asin(clamp(m32, -1, 1));
  95957. if (OIMO.abs(m32) < 0.99999) {
  95958. this._y = OIMO.atan2(-m31, m33);
  95959. this._z = OIMO.atan2(-m12, m22);
  95960. } else {
  95961. this._y = 0;
  95962. this._z = OIMO.atan2(m21, m11);
  95963. }
  95964. } else if (order === 'ZYX') {
  95965. this._y = OIMO.asin(-clamp(m31, -1, 1));
  95966. if (OIMO.abs(m31) < 0.99999) {
  95967. this._x = OIMO.atan2(m32, m33);
  95968. this._z = OIMO.atan2(m21, m11);
  95969. } else {
  95970. this._x = 0;
  95971. this._z = OIMO.atan2(-m12, m22);
  95972. }
  95973. } else if (order === 'YZX') {
  95974. this._z = OIMO.asin(clamp(m21, -1, 1));
  95975. if (OIMO.abs(m21) < 0.99999) {
  95976. this._x = OIMO.atan2(-m23, m22);
  95977. this._y = OIMO.atan2(-m31, m11);
  95978. } else {
  95979. this._x = 0;
  95980. this._y = OIMO.atan2(m13, m33);
  95981. }
  95982. } else if (order === 'XZY') {
  95983. this._z = OIMO.asin(-clamp(m12, -1, 1));
  95984. if (OIMO.abs(m12) < 0.99999) {
  95985. this._x = OIMO.atan2(m32, m22);
  95986. this._y = OIMO.atan2(m13, m11);
  95987. } else {
  95988. this._x = OIMO.atan2(-m23, m33);
  95989. this._y = 0;
  95990. }
  95991. } else {
  95992. console.warn('THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order)
  95993. }
  95994. this._order = order;
  95995. this.onChangeCallback();
  95996. return this;
  95997. },
  95998. setFromQuaternion: function (q, order, update) {
  95999. var clamp = OIMO.clamp;
  96000. // q is assumed to be normalized
  96001. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  96002. var sqx = q.x * q.x;
  96003. var sqy = q.y * q.y;
  96004. var sqz = q.z * q.z;
  96005. var sqw = q.s * q.s;
  96006. order = order || this._order;
  96007. if (order === 'XYZ') {
  96008. this._x = OIMO.atan2(2 * (q.x * q.s - q.y * q.z), (sqw - sqx - sqy + sqz));
  96009. this._y = OIMO.asin(clamp(2 * (q.x * q.z + q.y * q.s), -1, 1));
  96010. this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw + sqx - sqy - sqz));
  96011. } else if (order === 'YXZ') {
  96012. this._x = OIMO.asin(clamp(2 * (q.x * q.s - q.y * q.z), -1, 1));
  96013. this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw - sqx - sqy + sqz));
  96014. this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw - sqx + sqy - sqz));
  96015. } else if (order === 'ZXY') {
  96016. this._x = OIMO.asin(clamp(2 * (q.x * q.s + q.y * q.z), -1, 1));
  96017. this._y = OIMO.atan2(2 * (q.y * q.s - q.z * q.x), (sqw - sqx - sqy + sqz));
  96018. this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw - sqx + sqy - sqz));
  96019. } else if (order === 'ZYX') {
  96020. this._x = OIMO.atan2(2 * (q.x * q.s + q.z * q.y), (sqw - sqx - sqy + sqz));
  96021. this._y = OIMO.asin(clamp(2 * (q.y * q.s - q.x * q.z), -1, 1));
  96022. this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw + sqx - sqy - sqz));
  96023. } else if (order === 'YZX') {
  96024. this._x = OIMO.atan2(2 * (q.x * q.s - q.z * q.y), (sqw - sqx + sqy - sqz));
  96025. this._y = OIMO.atan2(2 * (q.y * q.s - q.x * q.z), (sqw + sqx - sqy - sqz));
  96026. this._z = OIMO.asin(clamp(2 * (q.x * q.y + q.z * q.s), -1, 1));
  96027. } else if (order === 'XZY') {
  96028. this._x = OIMO.atan2(2 * (q.x * q.s + q.y * q.z), (sqw - sqx + sqy - sqz));
  96029. this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw + sqx - sqy - sqz));
  96030. this._z = OIMO.asin(clamp(2 * (q.z * q.s - q.x * q.y), -1, 1));
  96031. } else {
  96032. console.warn('OIMO.Euler: .setFromQuaternion() given unsupported order: ' + order)
  96033. }
  96034. this._order = order;
  96035. if (update !== false) this.onChangeCallback();
  96036. return this;
  96037. },
  96038. reorder: function () {
  96039. // WARNING: this discards revolution information -bhouston
  96040. var q = new OIMO.Quat();
  96041. return function (newOrder) {
  96042. q.setFromEuler(this);
  96043. this.setFromQuaternion(q, newOrder);
  96044. };
  96045. }(),
  96046. equals: function (euler) {
  96047. return (euler._x === this._x) && (euler._y === this._y) && (euler._z === this._z) && (euler._order === this._order);
  96048. },
  96049. fromArray: function (array) {
  96050. this._x = array[0];
  96051. this._y = array[1];
  96052. this._z = array[2];
  96053. if (array[3] !== undefined) this._order = array[3];
  96054. this.onChangeCallback();
  96055. return this;
  96056. },
  96057. toArray: function () {
  96058. return [this._x, this._y, this._z, this._order];
  96059. },
  96060. onChange: function (callback) {
  96061. this.onChangeCallback = callback;
  96062. return this;
  96063. },
  96064. onChangeCallback: function () { },
  96065. clone: function () {
  96066. return new OIMO.Euler(this._x, this._y, this._z, this._order);
  96067. }
  96068. };
  96069. OIMO.EulerToAxis = function (ox, oy, oz) {// angles in radians
  96070. var c1 = OIMO.cos(oy * 0.5);//heading
  96071. var s1 = OIMO.sin(oy * 0.5);
  96072. var c2 = OIMO.cos(oz * 0.5);//altitude
  96073. var s2 = OIMO.sin(oz * 0.5);
  96074. var c3 = OIMO.cos(ox * 0.5);//bank
  96075. var s3 = OIMO.sin(ox * 0.5);
  96076. var c1c2 = c1 * c2;
  96077. var s1s2 = s1 * s2;
  96078. var w = c1c2 * c3 - s1s2 * s3;
  96079. var x = c1c2 * s3 + s1s2 * c3;
  96080. var y = s1 * c2 * c3 + c1 * s2 * s3;
  96081. var z = c1 * s2 * c3 - s1 * c2 * s3;
  96082. var angle = 2 * OIMO.acos(w);
  96083. var norm = x * x + y * y + z * z;
  96084. if (norm < 0.001) {
  96085. x = 1;
  96086. y = z = 0;
  96087. } else {
  96088. norm = OIMO.sqrt(norm);
  96089. x /= norm;
  96090. y /= norm;
  96091. z /= norm;
  96092. }
  96093. return [angle, x, y, z];
  96094. }
  96095. OIMO.EulerToMatrix = function (ox, oy, oz) {// angles in radians
  96096. var ch = OIMO.cos(oy);//heading
  96097. var sh = OIMO.sin(oy);
  96098. var ca = OIMO.cos(oz);//altitude
  96099. var sa = OIMO.sin(oz);
  96100. var cb = OIMO.cos(ox);//bank
  96101. var sb = OIMO.sin(ox);
  96102. var mtx = new OIMO.Mat33();
  96103. var te = mtx.elements;
  96104. te[0] = ch * ca;
  96105. te[1] = sh * sb - ch * sa * cb;
  96106. te[2] = ch * sa * sb + sh * cb;
  96107. te[3] = sa;
  96108. te[4] = ca * cb;
  96109. te[5] = -ca * sb;
  96110. te[6] = -sh * ca;
  96111. te[7] = sh * sa * cb + ch * sb;
  96112. te[8] = -sh * sa * sb + ch * cb;
  96113. return mtx;
  96114. }
  96115. OIMO.MatrixToEuler = function (mtx) {// angles in radians
  96116. var te = mtx.elements;
  96117. var x, y, z;
  96118. if (te[3] > 0.998) { // singularity at north pole
  96119. y = OIMO.atan2(te[2], te[8]);
  96120. z = OIMO.PI / 2;
  96121. x = 0;
  96122. } else if (te[3] < -0.998) { // singularity at south pole
  96123. y = OIMO.atan2(te[2], te[8]);
  96124. z = -OIMO.PI / 2;
  96125. x = 0;
  96126. } else {
  96127. y = OIMO.atan2(-te[6], te[0]);
  96128. x = OIMO.atan2(-te[5], te[4]);
  96129. z = OIMO.asin(te[3]);
  96130. }
  96131. return [x, y, z];
  96132. }
  96133. OIMO.unwrapDegrees = function (r) {
  96134. r = r % 360;
  96135. if (r > 180) r -= 360;
  96136. if (r < -180) r += 360;
  96137. return r;
  96138. }
  96139. OIMO.unwrapRadian = function (r) {
  96140. r = r % OIMO.TwoPI;
  96141. if (r > OIMO.PI) r -= OIMO.TwoPI;
  96142. if (r < -OIMO.PI) r += OIMO.TwoPI;
  96143. return r;
  96144. }
  96145. OIMO.Distance3d = function (p1, p2) {
  96146. var xd = p2[0] - p1[0];
  96147. var yd = p2[1] - p1[1];
  96148. var zd = p2[2] - p1[2];
  96149. return OIMO.sqrt(xd * xd + yd * yd + zd * zd);
  96150. }
  96151. /**
  96152. * The base class of all type of the constraints.
  96153. * @author saharan
  96154. */
  96155. OIMO.Constraint = function () {
  96156. // The parent world of the constraint.
  96157. this.parent = null;
  96158. // The first body of the constraint.
  96159. this.body1 = null;
  96160. // The second body of the constraint.
  96161. this.body2 = null;
  96162. // Internal
  96163. this.addedToIsland = false;
  96164. }
  96165. OIMO.Constraint.prototype = {
  96166. constructor: OIMO.Constraint,
  96167. /**
  96168. * Prepare for solving the constraint.
  96169. * @param timeStep
  96170. * @param invTimeStep
  96171. */
  96172. preSolve: function (timeStep, invTimeStep) {
  96173. OIMO.Error("Constraint", "Inheritance error.");
  96174. },
  96175. /**
  96176. * Solve the constraint.
  96177. * This is usually called iteratively.
  96178. */
  96179. solve: function () {
  96180. OIMO.Error("Constraint", "Inheritance error.");
  96181. },
  96182. /**
  96183. * Do the post-processing.
  96184. */
  96185. postSolve: function () {
  96186. OIMO.Error("Constraint", "Inheritance error.");
  96187. }
  96188. }
  96189. /**
  96190. * Joints are used to constrain the motion between two rigid bodies.
  96191. * @author saharan
  96192. * @author lo-th
  96193. */
  96194. OIMO.Joint = function (config) {
  96195. OIMO.Constraint.call(this);
  96196. // joint name
  96197. this.name = "";
  96198. // The type of the joint.
  96199. this.type = OIMO.JOINT_NULL;
  96200. // The previous joint in the world.
  96201. this.prev = null;
  96202. // The next joint in the world.
  96203. this.next = null;
  96204. this.body1 = config.body1;
  96205. this.body2 = config.body2;
  96206. // The anchor point on the first rigid body in local coordinate system.
  96207. this.localAnchorPoint1 = new OIMO.Vec3().copy(config.localAnchorPoint1);
  96208. // The anchor point on the second rigid body in local coordinate system.
  96209. this.localAnchorPoint2 = new OIMO.Vec3().copy(config.localAnchorPoint2);
  96210. // The anchor point on the first rigid body in world coordinate system relative to the body's origin.
  96211. this.relativeAnchorPoint1 = new OIMO.Vec3();
  96212. // The anchor point on the second rigid body in world coordinate system relative to the body's origin.
  96213. this.relativeAnchorPoint2 = new OIMO.Vec3();
  96214. // The anchor point on the first rigid body in world coordinate system.
  96215. this.anchorPoint1 = new OIMO.Vec3();
  96216. // The anchor point on the second rigid body in world coordinate system.
  96217. this.anchorPoint2 = new OIMO.Vec3();
  96218. // Whether allow collision between connected rigid bodies or not.
  96219. this.allowCollision = config.allowCollision;
  96220. this.b1Link = new OIMO.JointLink(this);
  96221. this.b2Link = new OIMO.JointLink(this);
  96222. this.matrix = new OIMO.Mat44();
  96223. };
  96224. OIMO.Joint.prototype = Object.create(OIMO.Constraint.prototype);
  96225. OIMO.Joint.prototype.constructor = OIMO.Joint;
  96226. // Update all the anchor points.
  96227. OIMO.Joint.prototype.updateAnchorPoints = function () {
  96228. this.relativeAnchorPoint1.mulMat(this.body1.rotation, this.localAnchorPoint1);
  96229. this.relativeAnchorPoint2.mulMat(this.body2.rotation, this.localAnchorPoint2);
  96230. this.anchorPoint1.add(this.relativeAnchorPoint1, this.body1.position);
  96231. this.anchorPoint2.add(this.relativeAnchorPoint2, this.body2.position);
  96232. };
  96233. // Attach the joint from the bodies.
  96234. OIMO.Joint.prototype.attach = function () {
  96235. this.b1Link.body = this.body2;
  96236. this.b2Link.body = this.body1;
  96237. if (this.body1.jointLink != null) (this.b1Link.next = this.body1.jointLink).prev = this.b1Link;
  96238. else this.b1Link.next = null;
  96239. this.body1.jointLink = this.b1Link;
  96240. this.body1.numJoints++;
  96241. if (this.body2.jointLink != null) (this.b2Link.next = this.body2.jointLink).prev = this.b2Link;
  96242. else this.b2Link.next = null;
  96243. this.body2.jointLink = this.b2Link;
  96244. this.body2.numJoints++;
  96245. };
  96246. // Detach the joint from the bodies.
  96247. OIMO.Joint.prototype.detach = function () {
  96248. var prev = this.b1Link.prev;
  96249. var next = this.b1Link.next;
  96250. if (prev != null) prev.next = next;
  96251. if (next != null) next.prev = prev;
  96252. if (this.body1.jointLink == this.b1Link) this.body1.jointLink = next;
  96253. this.b1Link.prev = null;
  96254. this.b1Link.next = null;
  96255. this.b1Link.body = null;
  96256. this.body1.numJoints--;
  96257. prev = this.b2Link.prev;
  96258. next = this.b2Link.next;
  96259. if (prev != null) prev.next = next;
  96260. if (next != null) next.prev = prev;
  96261. if (this.body2.jointLink == this.b2Link) this.body2.jointLink = next;
  96262. this.b2Link.prev = null;
  96263. this.b2Link.next = null;
  96264. this.b2Link.body = null;
  96265. this.body2.numJoints--;
  96266. this.b1Link.body = null;
  96267. this.b2Link.body = null;
  96268. };
  96269. // Awake the bodies.
  96270. OIMO.Joint.prototype.awake = function () {
  96271. this.body1.awake();
  96272. this.body2.awake();
  96273. };
  96274. // calculation function
  96275. OIMO.Joint.prototype.preSolve = function (timeStep, invTimeStep) {
  96276. };
  96277. OIMO.Joint.prototype.solve = function () {
  96278. };
  96279. OIMO.Joint.prototype.postSolve = function () {
  96280. };
  96281. // Delete process
  96282. OIMO.Joint.prototype.remove = function () {
  96283. this.dispose();
  96284. };
  96285. OIMO.Joint.prototype.dispose = function () {
  96286. this.parent.removeJoint(this);
  96287. };
  96288. // Three js add
  96289. OIMO.Joint.prototype.getPosition = function () {
  96290. var p1 = new OIMO.Vec3().scale(this.anchorPoint1, OIMO.WORLD_SCALE);
  96291. var p2 = new OIMO.Vec3().scale(this.anchorPoint2, OIMO.WORLD_SCALE);
  96292. return [p1, p2];
  96293. };
  96294. OIMO.Joint.prototype.getMatrix = function () {
  96295. var m = this.matrix.elements;
  96296. var p1 = this.anchorPoint1;
  96297. var p2 = this.anchorPoint2;
  96298. m[0] = p1.x * OIMO.WORLD_SCALE;
  96299. m[1] = p1.y * OIMO.WORLD_SCALE;
  96300. m[2] = p1.z * OIMO.WORLD_SCALE;
  96301. m[3] = 0;
  96302. m[4] = p2.x * OIMO.WORLD_SCALE;
  96303. m[5] = p2.y * OIMO.WORLD_SCALE;
  96304. m[6] = p2.z * OIMO.WORLD_SCALE;
  96305. m[7] = 0;
  96306. return m;
  96307. };
  96308. /**
  96309. * A joint configuration holds all configuration data for constructing a joint.
  96310. * Joint configurations can be reused safely.
  96311. * @author saharan
  96312. */
  96313. OIMO.JointConfig = function () {
  96314. // The first rigid body of the joint.
  96315. this.body1 = null;
  96316. // The second rigid body of the joint.
  96317. this.body2 = null;
  96318. // The anchor point on the first rigid body in local coordinate system.
  96319. this.localAnchorPoint1 = new OIMO.Vec3();
  96320. // The anchor point on the second rigid body in local coordinate system.
  96321. this.localAnchorPoint2 = new OIMO.Vec3();
  96322. // The axis in the first body's coordinate system.
  96323. // his property is available in some joints.
  96324. this.localAxis1 = new OIMO.Vec3();
  96325. // The axis in the second body's coordinate system.
  96326. // This property is available in some joints.
  96327. this.localAxis2 = new OIMO.Vec3();
  96328. // Whether allow collision between connected rigid bodies or not.
  96329. this.allowCollision = false;
  96330. };
  96331. /**
  96332. * A link list of joints.
  96333. * @author saharan
  96334. */
  96335. OIMO.JointLink = function (joint) {
  96336. // The previous joint link.
  96337. this.prev = null;
  96338. // The next joint link.
  96339. this.next = null;
  96340. // The other rigid body connected to the joint.
  96341. this.body = null;
  96342. // The joint of the link.
  96343. this.joint = joint;
  96344. };
  96345. /**
  96346. * An information of limit and motor.
  96347. * @author saharan
  96348. */
  96349. OIMO.LimitMotor = function (axis, fixed) {
  96350. fixed = fixed || false;
  96351. // The axis of the constraint.
  96352. this.axis = axis;
  96353. // The current angle for rotational constraints.
  96354. this.angle = 0;
  96355. // The lower limit. Set lower > upper to disable
  96356. this.lowerLimit = fixed ? 0 : 1;
  96357. //if(fixed)this.lowerLimit = 0;
  96358. //else this.lowerLimit = 1;
  96359. // The upper limit. Set lower > upper to disable.
  96360. this.upperLimit = 0;
  96361. // The target motor speed.
  96362. this.motorSpeed = 0;
  96363. // The maximum motor force or torque. Set 0 to disable.
  96364. this.maxMotorForce = 0;
  96365. // The frequency of the spring. Set 0 to disable.
  96366. this.frequency = 0;
  96367. // The damping ratio of the spring. Set 0 for no damping, 1 for critical damping.
  96368. this.dampingRatio = 0;
  96369. };
  96370. OIMO.LimitMotor.prototype = {
  96371. constructor: OIMO.LimitMotor,
  96372. /**
  96373. * Set limit data into this constraint.
  96374. * @param lowerLimit
  96375. * @param upperLimit
  96376. */
  96377. setLimit: function (lowerLimit, upperLimit) {
  96378. this.lowerLimit = lowerLimit;
  96379. this.upperLimit = upperLimit;
  96380. },
  96381. /**
  96382. * Set motor data into this constraint.
  96383. * @param motorSpeed
  96384. * @param maxMotorForce
  96385. */
  96386. setMotor: function (motorSpeed, maxMotorForce) {
  96387. this.motorSpeed = motorSpeed;
  96388. this.maxMotorForce = maxMotorForce;
  96389. },
  96390. /**
  96391. * Set spring data into this constraint.
  96392. * @param frequency
  96393. * @param dampingRatio
  96394. */
  96395. setSpring: function (frequency, dampingRatio) {
  96396. this.frequency = frequency;
  96397. this.dampingRatio = dampingRatio;
  96398. }
  96399. };
  96400. /**
  96401. * A ball-and-socket joint limits relative translation on two anchor points on rigid bodies.
  96402. * @author saharan
  96403. * @author lo-th
  96404. */
  96405. OIMO.BallAndSocketJoint = function (config) {
  96406. OIMO.Joint.call(this, config);
  96407. this.type = OIMO.JOINT_BALL_AND_SOCKET;
  96408. this.lc = new OIMO.LinearConstraint(this);
  96409. };
  96410. OIMO.BallAndSocketJoint.prototype = Object.create(OIMO.Joint.prototype);
  96411. OIMO.BallAndSocketJoint.prototype.constructor = OIMO.BallAndSocketJoint;
  96412. OIMO.BallAndSocketJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  96413. this.updateAnchorPoints();
  96414. this.lc.preSolve(timeStep, invTimeStep);
  96415. };
  96416. OIMO.BallAndSocketJoint.prototype.solve = function () {
  96417. this.lc.solve();
  96418. };
  96419. OIMO.BallAndSocketJoint.prototype.postSolve = function () {
  96420. };
  96421. /**
  96422. * A distance joint limits the distance between two anchor points on rigid bodies.
  96423. * @author saharan
  96424. * @author lo-th
  96425. */
  96426. OIMO.DistanceJoint = function (config, minDistance, maxDistance) {
  96427. OIMO.Joint.call(this, config);
  96428. this.type = OIMO.JOINT_DISTANCE;
  96429. this.normal = new OIMO.Vec3();
  96430. this.nr = new OIMO.Vec3();
  96431. // The limit and motor information of the joint.
  96432. this.limitMotor = new OIMO.LimitMotor(this.normal, true);
  96433. this.limitMotor.lowerLimit = minDistance;
  96434. this.limitMotor.upperLimit = maxDistance;
  96435. this.t = new OIMO.TranslationalConstraint(this, this.limitMotor);
  96436. };
  96437. OIMO.DistanceJoint.prototype = Object.create(OIMO.Joint.prototype);
  96438. OIMO.DistanceJoint.prototype.constructor = OIMO.DistanceJoint;
  96439. OIMO.DistanceJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  96440. this.updateAnchorPoints();
  96441. //var nr = this.nr;
  96442. this.nr.sub(this.anchorPoint2, this.anchorPoint1);
  96443. //var len = OIMO.sqrt( nr.x*nr.x + nr.y*nr.y + nr.z*nr.z );
  96444. //if(len>0) len = 1/len;
  96445. //this.normal.scale( nr, len );
  96446. this.normal.normalize(this.nr);
  96447. this.t.preSolve(timeStep, invTimeStep);
  96448. };
  96449. OIMO.DistanceJoint.prototype.solve = function () {
  96450. this.t.solve();
  96451. };
  96452. OIMO.DistanceJoint.prototype.postSolve = function () {
  96453. };
  96454. /**
  96455. * A hinge joint allows only for relative rotation of rigid bodies along the axis.
  96456. * @author saharan
  96457. * @author lo-th
  96458. */
  96459. OIMO.HingeJoint = function (config, lowerAngleLimit, upperAngleLimit) {
  96460. OIMO.Joint.call(this, config);
  96461. this.type = OIMO.JOINT_HINGE;
  96462. // The axis in the first body's coordinate system.
  96463. this.localAxis1 = config.localAxis1.clone().norm();
  96464. // The axis in the second body's coordinate system.
  96465. this.localAxis2 = config.localAxis2.clone().norm();
  96466. // make angle axis 1
  96467. this.localAngle1 = new OIMO.Vec3(
  96468. this.localAxis1.y * this.localAxis1.x - this.localAxis1.z * this.localAxis1.z,
  96469. -this.localAxis1.z * this.localAxis1.y - this.localAxis1.x * this.localAxis1.x,
  96470. this.localAxis1.x * this.localAxis1.z + this.localAxis1.y * this.localAxis1.y
  96471. ).norm();
  96472. // make angle axis 2
  96473. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  96474. this.localAngle2 = new OIMO.Vec3().mulMat(arc, this.localAngle1);
  96475. this.nor = new OIMO.Vec3();
  96476. this.tan = new OIMO.Vec3();
  96477. this.bin = new OIMO.Vec3();
  96478. this.ax1 = new OIMO.Vec3();
  96479. this.ax2 = new OIMO.Vec3();
  96480. this.an1 = new OIMO.Vec3();
  96481. this.an2 = new OIMO.Vec3();
  96482. // The rotational limit and motor information of the joint.
  96483. this.limitMotor = new OIMO.LimitMotor(this.nor, false);
  96484. this.limitMotor.lowerLimit = lowerAngleLimit;
  96485. this.limitMotor.upperLimit = upperAngleLimit;
  96486. this.lc = new OIMO.LinearConstraint(this);
  96487. this.r3 = new OIMO.Rotational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  96488. };
  96489. OIMO.HingeJoint.prototype = Object.create(OIMO.Joint.prototype);
  96490. OIMO.HingeJoint.prototype.constructor = OIMO.HingeJoint;
  96491. OIMO.HingeJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  96492. var tmp1X, tmp1Y, tmp1Z, limite;//, nx, ny, nz, tx, ty, tz, bx, by, bz;
  96493. this.updateAnchorPoints();
  96494. this.ax1.mulMat(this.body1.rotation, this.localAxis1);
  96495. this.ax2.mulMat(this.body2.rotation, this.localAxis2);
  96496. this.an1.mulMat(this.body1.rotation, this.localAngle1);
  96497. this.an2.mulMat(this.body2.rotation, this.localAngle2);
  96498. this.nor.set(
  96499. this.ax1.x * this.body2.inverseMass + this.ax2.x * this.body1.inverseMass,
  96500. this.ax1.y * this.body2.inverseMass + this.ax2.y * this.body1.inverseMass,
  96501. this.ax1.z * this.body2.inverseMass + this.ax2.z * this.body1.inverseMass
  96502. ).norm();
  96503. this.tan.set(
  96504. this.nor.y * this.nor.x - this.nor.z * this.nor.z,
  96505. -this.nor.z * this.nor.y - this.nor.x * this.nor.x,
  96506. this.nor.x * this.nor.z + this.nor.y * this.nor.y
  96507. ).norm();
  96508. this.bin.set(
  96509. this.nor.y * this.tan.z - this.nor.z * this.tan.y,
  96510. this.nor.z * this.tan.x - this.nor.x * this.tan.z,
  96511. this.nor.x * this.tan.y - this.nor.y * this.tan.x
  96512. );
  96513. // calculate hinge angle
  96514. limite = this.acosClamp(this.an1.x * this.an2.x + this.an1.y * this.an2.y + this.an1.z * this.an2.z)
  96515. if (
  96516. this.nor.x * (this.an1.y * this.an2.z - this.an1.z * this.an2.y) +
  96517. this.nor.y * (this.an1.z * this.an2.x - this.an1.x * this.an2.z) +
  96518. this.nor.z * (this.an1.x * this.an2.y - this.an1.y * this.an2.x) < 0
  96519. ) {
  96520. this.limitMotor.angle = -limite;
  96521. } else {
  96522. this.limitMotor.angle = limite;
  96523. }
  96524. tmp1X = this.ax1.y * this.ax2.z - this.ax1.z * this.ax2.y;
  96525. tmp1Y = this.ax1.z * this.ax2.x - this.ax1.x * this.ax2.z;
  96526. tmp1Z = this.ax1.x * this.ax2.y - this.ax1.y * this.ax2.x;
  96527. this.r3.limitMotor2.angle = this.tan.x * tmp1X + this.tan.y * tmp1Y + this.tan.z * tmp1Z;
  96528. this.r3.limitMotor3.angle = this.bin.x * tmp1X + this.bin.y * tmp1Y + this.bin.z * tmp1Z;
  96529. this.r3.preSolve(timeStep, invTimeStep);
  96530. this.lc.preSolve(timeStep, invTimeStep);
  96531. };
  96532. OIMO.HingeJoint.prototype.solve = function () {
  96533. this.r3.solve();
  96534. this.lc.solve();
  96535. };
  96536. OIMO.HingeJoint.prototype.postSolve = function () {
  96537. };
  96538. OIMO.HingeJoint.prototype.acosClamp = function (cos) {
  96539. if (cos > 1) return 0;
  96540. else if (cos < -1) return OIMO.PI;
  96541. else return OIMO.acos(cos);
  96542. };
  96543. /**
  96544. * A prismatic joint allows only for relative translation of rigid bodies along the axis.
  96545. * @author saharan
  96546. * @author lo-th
  96547. */
  96548. OIMO.PrismaticJoint = function (config, lowerTranslation, upperTranslation) {
  96549. OIMO.Joint.call(this, config);
  96550. this.type = OIMO.JOINT_PRISMATIC;
  96551. // The axis in the first body's coordinate system.
  96552. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  96553. // The axis in the second body's coordinate system.
  96554. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  96555. this.localAxis1X = this.localAxis1.x;
  96556. this.localAxis1Y = this.localAxis1.y;
  96557. this.localAxis1Z = this.localAxis1.z;
  96558. this.localAxis2X = this.localAxis2.x;
  96559. this.localAxis2Y = this.localAxis2.y;
  96560. this.localAxis2Z = this.localAxis2.z;
  96561. this.nor = new OIMO.Vec3();
  96562. this.tan = new OIMO.Vec3();
  96563. this.bin = new OIMO.Vec3();
  96564. this.ac = new OIMO.AngularConstraint(this, new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  96565. // The translational limit and motor information of the joint.
  96566. this.limitMotor = new OIMO.LimitMotor(this.nor, true);
  96567. this.limitMotor.lowerLimit = lowerTranslation;
  96568. this.limitMotor.upperLimit = upperTranslation;
  96569. this.t3 = new OIMO.Translational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  96570. };
  96571. OIMO.PrismaticJoint.prototype = Object.create(OIMO.Joint.prototype);
  96572. OIMO.PrismaticJoint.prototype.constructor = OIMO.PrismaticJoint;
  96573. OIMO.PrismaticJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  96574. var tmpM;
  96575. var tmp1X;
  96576. var tmp1Y;
  96577. var tmp1Z;
  96578. this.updateAnchorPoints();
  96579. tmpM = this.body1.rotation.elements;
  96580. var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  96581. var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  96582. var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  96583. tmpM = this.body2.rotation.elements;
  96584. var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  96585. var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  96586. var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  96587. var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
  96588. var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
  96589. var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
  96590. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  96591. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  96592. nx *= tmp1X;
  96593. ny *= tmp1X;
  96594. nz *= tmp1X;
  96595. var tx = ny * nx - nz * nz;
  96596. var ty = -nz * ny - nx * nx;
  96597. var tz = nx * nz + ny * ny;
  96598. tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  96599. tx *= tmp1X;
  96600. ty *= tmp1X;
  96601. tz *= tmp1X;
  96602. var bx = ny * tz - nz * ty;
  96603. var by = nz * tx - nx * tz;
  96604. var bz = nx * ty - ny * tx;
  96605. this.nor.init(nx, ny, nz);
  96606. this.tan.init(tx, ty, tz);
  96607. this.bin.init(bx, by, bz);
  96608. this.ac.preSolve(timeStep, invTimeStep);
  96609. this.t3.preSolve(timeStep, invTimeStep);
  96610. };
  96611. OIMO.PrismaticJoint.prototype.solve = function () {
  96612. this.ac.solve();
  96613. this.t3.solve();
  96614. };
  96615. OIMO.PrismaticJoint.prototype.postSolve = function () {
  96616. };
  96617. /**
  96618. * A slider joint allows for relative translation and relative rotation between two rigid bodies along the axis.
  96619. * @author saharan
  96620. * @author lo-th
  96621. */
  96622. OIMO.SliderJoint = function (config, lowerTranslation, upperTranslation) {
  96623. OIMO.Joint.call(this, config);
  96624. this.type = OIMO.JOINT_SLIDER;
  96625. // The first axis in local coordinate system.
  96626. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  96627. // The second axis in local coordinate system.
  96628. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  96629. var len;
  96630. this.localAxis1X = this.localAxis1.x;
  96631. this.localAxis1Y = this.localAxis1.y;
  96632. this.localAxis1Z = this.localAxis1.z;
  96633. this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
  96634. this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
  96635. this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
  96636. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  96637. this.localAngAxis1X *= len;
  96638. this.localAngAxis1Y *= len;
  96639. this.localAngAxis1Z *= len;
  96640. this.localAxis2X = this.localAxis2.x;
  96641. this.localAxis2Y = this.localAxis2.y;
  96642. this.localAxis2Z = this.localAxis2.z;
  96643. // make angle axis 2
  96644. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  96645. var tarc = arc.elements;
  96646. this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
  96647. this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
  96648. this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
  96649. this.nor = new OIMO.Vec3();
  96650. this.tan = new OIMO.Vec3();
  96651. this.bin = new OIMO.Vec3();
  96652. // The limit and motor for the rotation
  96653. this.rotationalLimitMotor = new OIMO.LimitMotor(this.nor, false);
  96654. this.r3 = new OIMO.Rotational3Constraint(this, this.rotationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  96655. // The limit and motor for the translation.
  96656. this.translationalLimitMotor = new OIMO.LimitMotor(this.nor, true);
  96657. this.translationalLimitMotor.lowerLimit = lowerTranslation;
  96658. this.translationalLimitMotor.upperLimit = upperTranslation;
  96659. this.t3 = new OIMO.Translational3Constraint(this, this.translationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  96660. };
  96661. OIMO.SliderJoint.prototype = Object.create(OIMO.Joint.prototype);
  96662. OIMO.SliderJoint.prototype.constructor = OIMO.SliderJoint;
  96663. OIMO.SliderJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  96664. var tmpM;
  96665. var tmp1X;
  96666. var tmp1Y;
  96667. var tmp1Z;
  96668. this.updateAnchorPoints();
  96669. tmpM = this.body1.rotation.elements;
  96670. var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  96671. var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  96672. var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  96673. var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
  96674. var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
  96675. var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
  96676. tmpM = this.body2.rotation.elements;
  96677. var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  96678. var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  96679. var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  96680. var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
  96681. var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
  96682. var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
  96683. var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
  96684. var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
  96685. var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
  96686. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  96687. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  96688. nx *= tmp1X;
  96689. ny *= tmp1X;
  96690. nz *= tmp1X;
  96691. var tx = ny * nx - nz * nz;
  96692. var ty = -nz * ny - nx * nx;
  96693. var tz = nx * nz + ny * ny;
  96694. tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  96695. tx *= tmp1X;
  96696. ty *= tmp1X;
  96697. tz *= tmp1X;
  96698. var bx = ny * tz - nz * ty;
  96699. var by = nz * tx - nx * tz;
  96700. var bz = nx * ty - ny * tx;
  96701. this.nor.init(nx, ny, nz);
  96702. this.tan.init(tx, ty, tz);
  96703. this.bin.init(bx, by, bz);
  96704. // ----------------------------------------------
  96705. // calculate hinge angle
  96706. // ----------------------------------------------
  96707. if (
  96708. nx * (angAxis1Y * angAxis2Z - angAxis1Z * angAxis2Y) +
  96709. ny * (angAxis1Z * angAxis2X - angAxis1X * angAxis2Z) +
  96710. nz * (angAxis1X * angAxis2Y - angAxis1Y * angAxis2X) < 0
  96711. ) {
  96712. this.rotationalLimitMotor.angle = -this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
  96713. } else {
  96714. this.rotationalLimitMotor.angle = this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
  96715. }
  96716. // angular error
  96717. tmp1X = axis1Y * axis2Z - axis1Z * axis2Y;
  96718. tmp1Y = axis1Z * axis2X - axis1X * axis2Z;
  96719. tmp1Z = axis1X * axis2Y - axis1Y * axis2X;
  96720. this.r3.limitMotor2.angle = tx * tmp1X + ty * tmp1Y + tz * tmp1Z;
  96721. this.r3.limitMotor3.angle = bx * tmp1X + by * tmp1Y + bz * tmp1Z;
  96722. this.r3.preSolve(timeStep, invTimeStep);
  96723. this.t3.preSolve(timeStep, invTimeStep);
  96724. };
  96725. OIMO.SliderJoint.prototype.solve = function () {
  96726. this.r3.solve();
  96727. this.t3.solve();
  96728. };
  96729. OIMO.SliderJoint.prototype.postSolve = function () {
  96730. };
  96731. OIMO.SliderJoint.prototype.acosClamp = function (cos) {
  96732. if (cos > 1) return 0;
  96733. else if (cos < -1) return OIMO.PI;
  96734. else return OIMO.acos(cos);
  96735. };
  96736. /**
  96737. * A wheel joint allows for relative rotation between two rigid bodies along two axes.
  96738. * The wheel joint also allows for relative translation for the suspension.
  96739. * @author saharan
  96740. * @author lo-th
  96741. */
  96742. OIMO.WheelJoint = function (config) {
  96743. OIMO.Joint.call(this, config);
  96744. this.type = OIMO.JOINT_WHEEL;
  96745. // The first axis in local coordinate system.
  96746. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  96747. // The second axis in local coordinate system.
  96748. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  96749. var len;
  96750. this.localAxis1X = this.localAxis1.x;
  96751. this.localAxis1Y = this.localAxis1.y;
  96752. this.localAxis1Z = this.localAxis1.z;
  96753. this.localAxis2X = this.localAxis2.x;
  96754. this.localAxis2Y = this.localAxis2.y;
  96755. this.localAxis2Z = this.localAxis2.z;
  96756. var dot = this.localAxis1X * this.localAxis2X + this.localAxis1Y * this.localAxis2Y + this.localAxis1Z * this.localAxis2Z;
  96757. if (dot > -1 && dot < 1) {
  96758. this.localAngAxis1X = this.localAxis2X - dot * this.localAxis1X;
  96759. this.localAngAxis1Y = this.localAxis2Y - dot * this.localAxis1Y;
  96760. this.localAngAxis1Z = this.localAxis2Z - dot * this.localAxis1Z;
  96761. this.localAngAxis2X = this.localAxis1X - dot * this.localAxis2X;
  96762. this.localAngAxis2Y = this.localAxis1Y - dot * this.localAxis2Y;
  96763. this.localAngAxis2Z = this.localAxis1Z - dot * this.localAxis2Z;
  96764. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  96765. this.localAngAxis1X *= len;
  96766. this.localAngAxis1Y *= len;
  96767. this.localAngAxis1Z *= len;
  96768. len = 1 / OIMO.sqrt(this.localAngAxis2X * this.localAngAxis2X + this.localAngAxis2Y * this.localAngAxis2Y + this.localAngAxis2Z * this.localAngAxis2Z);
  96769. this.localAngAxis2X *= len;
  96770. this.localAngAxis2Y *= len;
  96771. this.localAngAxis2Z *= len;
  96772. } else {
  96773. this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
  96774. this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
  96775. this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
  96776. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  96777. this.localAngAxis1X *= len;
  96778. this.localAngAxis1Y *= len;
  96779. this.localAngAxis1Z *= len;
  96780. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  96781. var tarc = arc.elements;
  96782. this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
  96783. this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
  96784. this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
  96785. }
  96786. this.nor = new OIMO.Vec3();
  96787. this.tan = new OIMO.Vec3();
  96788. this.bin = new OIMO.Vec3();
  96789. // The translational limit and motor information of the joint.
  96790. this.translationalLimitMotor = new OIMO.LimitMotor(this.tan, true);
  96791. this.translationalLimitMotor.frequency = 8;
  96792. this.translationalLimitMotor.dampingRatio = 1;
  96793. // The first rotational limit and motor information of the joint.
  96794. this.rotationalLimitMotor1 = new OIMO.LimitMotor(this.tan, false);
  96795. // The second rotational limit and motor information of the joint.
  96796. this.rotationalLimitMotor2 = new OIMO.LimitMotor(this.bin, false);
  96797. this.t3 = new OIMO.Translational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.translationalLimitMotor, new OIMO.LimitMotor(this.bin, true));
  96798. this.t3.weight = 1;
  96799. this.r3 = new OIMO.Rotational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.rotationalLimitMotor1, this.rotationalLimitMotor2);
  96800. };
  96801. OIMO.WheelJoint.prototype = Object.create(OIMO.Joint.prototype);
  96802. OIMO.WheelJoint.prototype.constructor = OIMO.WheelJoint;
  96803. OIMO.WheelJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  96804. var tmpM;
  96805. var tmp1X;
  96806. var tmp1Y;
  96807. var tmp1Z;
  96808. this.updateAnchorPoints();
  96809. tmpM = this.body1.rotation.elements;
  96810. var x1 = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  96811. var y1 = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  96812. var z1 = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  96813. var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
  96814. var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
  96815. var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
  96816. tmpM = this.body2.rotation.elements;
  96817. var x2 = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  96818. var y2 = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  96819. var z2 = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  96820. var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
  96821. var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
  96822. var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
  96823. this.r3.limitMotor1.angle = x1 * x2 + y1 * y2 + z1 * z2;
  96824. if (x1 * (angAxis1Y * z2 - angAxis1Z * y2) + y1 * (angAxis1Z * x2 - angAxis1X * z2) + z1 * (angAxis1X * y2 - angAxis1Y * x2) < 0) {
  96825. this.rotationalLimitMotor1.angle = -this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
  96826. } else {
  96827. this.rotationalLimitMotor1.angle = this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
  96828. }
  96829. if (x2 * (angAxis2Y * z1 - angAxis2Z * y1) + y2 * (angAxis2Z * x1 - angAxis2X * z1) + z2 * (angAxis2X * y1 - angAxis2Y * x1) < 0) {
  96830. this.rotationalLimitMotor2.angle = this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
  96831. } else {
  96832. this.rotationalLimitMotor2.angle = -this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
  96833. }
  96834. var nx = y2 * z1 - z2 * y1;
  96835. var ny = z2 * x1 - x2 * z1;
  96836. var nz = x2 * y1 - y2 * x1;
  96837. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  96838. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  96839. nx *= tmp1X;
  96840. ny *= tmp1X;
  96841. nz *= tmp1X;
  96842. var tx = ny * z2 - nz * y2;
  96843. var ty = nz * x2 - nx * z2;
  96844. var tz = nx * y2 - ny * x2;
  96845. tmp1X = OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  96846. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  96847. tx *= tmp1X;
  96848. ty *= tmp1X;
  96849. tz *= tmp1X;
  96850. var bx = y1 * nz - z1 * ny;
  96851. var by = z1 * nx - x1 * nz;
  96852. var bz = x1 * ny - y1 * nx;
  96853. tmp1X = OIMO.sqrt(bx * bx + by * by + bz * bz);
  96854. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  96855. bx *= tmp1X;
  96856. by *= tmp1X;
  96857. bz *= tmp1X;
  96858. this.nor.init(nx, ny, nz);
  96859. this.tan.init(tx, ty, tz);
  96860. this.bin.init(bx, by, bz);
  96861. this.r3.preSolve(timeStep, invTimeStep);
  96862. this.t3.preSolve(timeStep, invTimeStep);
  96863. };
  96864. OIMO.WheelJoint.prototype.solve = function () {
  96865. this.r3.solve();
  96866. this.t3.solve();
  96867. };
  96868. OIMO.WheelJoint.prototype.postSolve = function () {
  96869. };
  96870. OIMO.WheelJoint.prototype.acosClamp = function (cos) {
  96871. if (cos > 1) return 0;
  96872. else if (cos < -1) return OIMO.PI;
  96873. else return OIMO.acos(cos);
  96874. };
  96875. /**
  96876. * An angular constraint for all axes for various joints.
  96877. * @author saharan
  96878. */
  96879. OIMO.AngularConstraint = function (joint, targetOrientation) {
  96880. this.joint = joint;
  96881. this.targetOrientation = new OIMO.Quat().invert(targetOrientation);
  96882. this.relativeOrientation = new OIMO.Quat();
  96883. this.ii1 = null;
  96884. this.ii2 = null;
  96885. this.dd = null;
  96886. this.vel = new OIMO.Vec3();
  96887. this.imp = new OIMO.Vec3();
  96888. this.rn0 = new OIMO.Vec3();
  96889. this.rn1 = new OIMO.Vec3();
  96890. this.rn2 = new OIMO.Vec3();
  96891. this.b1 = joint.body1;
  96892. this.b2 = joint.body2;
  96893. this.a1 = this.b1.angularVelocity;
  96894. this.a2 = this.b2.angularVelocity;
  96895. this.i1 = this.b1.inverseInertia;
  96896. this.i2 = this.b2.inverseInertia;
  96897. };
  96898. OIMO.AngularConstraint.prototype = {
  96899. constructor: OIMO.AngularConstraint,
  96900. preSolve: function (timeStep, invTimeStep) {
  96901. var inv, len, v, vv;
  96902. this.ii1 = this.i1.clone();
  96903. this.ii2 = this.i2.clone();
  96904. v = new OIMO.Mat33().add(this.ii1, this.ii2).elements;
  96905. 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]));
  96906. this.dd = new OIMO.Mat33(
  96907. v[4] * v[8] - v[5] * v[7], v[2] * v[7] - v[1] * v[8], v[1] * v[5] - v[2] * v[4],
  96908. v[5] * v[6] - v[3] * v[8], v[0] * v[8] - v[2] * v[6], v[2] * v[3] - v[0] * v[5],
  96909. v[3] * v[7] - v[4] * v[6], v[1] * v[6] - v[0] * v[7], v[0] * v[4] - v[1] * v[3]
  96910. ).multiply(inv);
  96911. this.relativeOrientation.invert(this.b1.orientation);
  96912. this.relativeOrientation.mul(this.targetOrientation, this.relativeOrientation);
  96913. this.relativeOrientation.mul(this.b2.orientation, this.relativeOrientation);
  96914. inv = this.relativeOrientation.s * 2;
  96915. this.vel.scale(this.relativeOrientation, inv);
  96916. len = this.vel.length();
  96917. if (len > 0.02) {
  96918. len = (0.02 - len) / len * invTimeStep * 0.05;
  96919. this.vel.scaleEqual(len);
  96920. } else {
  96921. this.vel.init();
  96922. }
  96923. this.rn1.mulMat(this.ii1, this.imp);
  96924. this.rn2.mulMat(this.ii2, this.imp);
  96925. this.a1.addEqual(this.rn1);
  96926. this.a2.subEqual(this.rn2);
  96927. },
  96928. solve: function () {
  96929. var r = this.a2.clone().subEqual(this.a1).subEqual(this.vel);
  96930. this.rn0.mulMat(this.dd, r);
  96931. this.rn1.mulMat(this.ii1, this.rn0);
  96932. this.rn2.mulMat(this.ii2, this.rn0);
  96933. this.imp.addEqual(this.rn0);
  96934. this.a1.addEqual(this.rn1);
  96935. this.a2.subEqual(this.rn2);
  96936. }
  96937. };
  96938. /**
  96939. * A linear constraint for all axes for various joints.
  96940. * @author saharan
  96941. */
  96942. OIMO.LinearConstraint = function (joint) {
  96943. this.m1 = NaN;
  96944. this.m2 = NaN;
  96945. this.ii1 = null;
  96946. this.ii2 = null;
  96947. this.dd = null;
  96948. this.r1x = NaN;
  96949. this.r1y = NaN;
  96950. this.r1z = NaN;
  96951. this.r2x = NaN;
  96952. this.r2y = NaN;
  96953. this.r2z = NaN;
  96954. this.ax1x = NaN;
  96955. this.ax1y = NaN;
  96956. this.ax1z = NaN;
  96957. this.ay1x = NaN;
  96958. this.ay1y = NaN;
  96959. this.ay1z = NaN;
  96960. this.az1x = NaN;
  96961. this.az1y = NaN;
  96962. this.az1z = NaN;
  96963. this.ax2x = NaN;
  96964. this.ax2y = NaN;
  96965. this.ax2z = NaN;
  96966. this.ay2x = NaN;
  96967. this.ay2y = NaN;
  96968. this.ay2z = NaN;
  96969. this.az2x = NaN;
  96970. this.az2y = NaN;
  96971. this.az2z = NaN;
  96972. this.vel = NaN;
  96973. this.velx = NaN;
  96974. this.vely = NaN;
  96975. this.velz = NaN;
  96976. this.joint = joint;
  96977. this.r1 = joint.relativeAnchorPoint1;
  96978. this.r2 = joint.relativeAnchorPoint2;
  96979. this.p1 = joint.anchorPoint1;
  96980. this.p2 = joint.anchorPoint2;
  96981. this.b1 = joint.body1;
  96982. this.b2 = joint.body2;
  96983. this.l1 = this.b1.linearVelocity;
  96984. this.l2 = this.b2.linearVelocity;
  96985. this.a1 = this.b1.angularVelocity;
  96986. this.a2 = this.b2.angularVelocity;
  96987. this.i1 = this.b1.inverseInertia;
  96988. this.i2 = this.b2.inverseInertia;
  96989. this.impx = 0;
  96990. this.impy = 0;
  96991. this.impz = 0;
  96992. }
  96993. OIMO.LinearConstraint.prototype = {
  96994. constructor: OIMO.LinearConstraint,
  96995. preSolve: function (timeStep, invTimeStep) {
  96996. this.r1x = this.r1.x;
  96997. this.r1y = this.r1.y;
  96998. this.r1z = this.r1.z;
  96999. this.r2x = this.r2.x;
  97000. this.r2y = this.r2.y;
  97001. this.r2z = this.r2.z;
  97002. this.m1 = this.b1.inverseMass;
  97003. this.m2 = this.b2.inverseMass;
  97004. this.ii1 = this.i1.clone();
  97005. this.ii2 = this.i2.clone();
  97006. var ii1 = this.ii1.elements;
  97007. var ii2 = this.ii2.elements;
  97008. this.ax1x = this.r1z * ii1[1] + -this.r1y * ii1[2];
  97009. this.ax1y = this.r1z * ii1[4] + -this.r1y * ii1[5];
  97010. this.ax1z = this.r1z * ii1[7] + -this.r1y * ii1[8];
  97011. this.ay1x = -this.r1z * ii1[0] + this.r1x * ii1[2];
  97012. this.ay1y = -this.r1z * ii1[3] + this.r1x * ii1[5];
  97013. this.ay1z = -this.r1z * ii1[6] + this.r1x * ii1[8];
  97014. this.az1x = this.r1y * ii1[0] + -this.r1x * ii1[1];
  97015. this.az1y = this.r1y * ii1[3] + -this.r1x * ii1[4];
  97016. this.az1z = this.r1y * ii1[6] + -this.r1x * ii1[7];
  97017. this.ax2x = this.r2z * ii2[1] + -this.r2y * ii2[2];
  97018. this.ax2y = this.r2z * ii2[4] + -this.r2y * ii2[5];
  97019. this.ax2z = this.r2z * ii2[7] + -this.r2y * ii2[8];
  97020. this.ay2x = -this.r2z * ii2[0] + this.r2x * ii2[2];
  97021. this.ay2y = -this.r2z * ii2[3] + this.r2x * ii2[5];
  97022. this.ay2z = -this.r2z * ii2[6] + this.r2x * ii2[8];
  97023. this.az2x = this.r2y * ii2[0] + -this.r2x * ii2[1];
  97024. this.az2y = this.r2y * ii2[3] + -this.r2x * ii2[4];
  97025. this.az2z = this.r2y * ii2[6] + -this.r2x * ii2[7];
  97026. // calculate point-to-point mass matrix
  97027. // from impulse equation
  97028. //
  97029. // M = ([/m] - [r^][/I][r^]) ^ -1
  97030. //
  97031. // where
  97032. //
  97033. // [/m] = |1/m, 0, 0|
  97034. // |0, 1/m, 0|
  97035. // |0, 0, 1/m|
  97036. //
  97037. // [r^] = |0, -rz, ry|
  97038. // |rz, 0, -rx|
  97039. // |-ry, rx, 0|
  97040. //
  97041. // [/I] = Inverted moment inertia
  97042. var rxx = this.m1 + this.m2;
  97043. var kk = new OIMO.Mat33(rxx, 0, 0, 0, rxx, 0, 0, 0, rxx);
  97044. var k = kk.elements;
  97045. k[0] += ii1[4] * this.r1z * this.r1z - (ii1[7] + ii1[5]) * this.r1y * this.r1z + ii1[8] * this.r1y * this.r1y;
  97046. k[1] += (ii1[6] * this.r1y + ii1[5] * this.r1x) * this.r1z - ii1[3] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
  97047. k[2] += (ii1[3] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[6] * this.r1y * this.r1y + ii1[7] * this.r1x * this.r1y;
  97048. k[3] += (ii1[2] * this.r1y + ii1[7] * this.r1x) * this.r1z - ii1[1] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
  97049. k[4] += ii1[0] * this.r1z * this.r1z - (ii1[6] + ii1[2]) * this.r1x * this.r1z + ii1[8] * this.r1x * this.r1x;
  97050. k[5] += (ii1[1] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[7] * this.r1x * this.r1x + ii1[6] * this.r1x * this.r1y;
  97051. k[6] += (ii1[1] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[2] * this.r1y * this.r1y + ii1[5] * this.r1x * this.r1y;
  97052. k[7] += (ii1[3] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[5] * this.r1x * this.r1x + ii1[2] * this.r1x * this.r1y;
  97053. k[8] += ii1[0] * this.r1y * this.r1y - (ii1[3] + ii1[1]) * this.r1x * this.r1y + ii1[4] * this.r1x * this.r1x;
  97054. k[0] += ii2[4] * this.r2z * this.r2z - (ii2[7] + ii2[5]) * this.r2y * this.r2z + ii2[8] * this.r2y * this.r2y;
  97055. k[1] += (ii2[6] * this.r2y + ii2[5] * this.r2x) * this.r2z - ii2[3] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
  97056. k[2] += (ii2[3] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[6] * this.r2y * this.r2y + ii2[7] * this.r2x * this.r2y;
  97057. k[3] += (ii2[2] * this.r2y + ii2[7] * this.r2x) * this.r2z - ii2[1] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
  97058. k[4] += ii2[0] * this.r2z * this.r2z - (ii2[6] + ii2[2]) * this.r2x * this.r2z + ii2[8] * this.r2x * this.r2x;
  97059. k[5] += (ii2[1] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[7] * this.r2x * this.r2x + ii2[6] * this.r2x * this.r2y;
  97060. k[6] += (ii2[1] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[2] * this.r2y * this.r2y + ii2[5] * this.r2x * this.r2y;
  97061. k[7] += (ii2[3] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[5] * this.r2x * this.r2x + ii2[2] * this.r2x * this.r2y;
  97062. k[8] += ii2[0] * this.r2y * this.r2y - (ii2[3] + ii2[1]) * this.r2x * this.r2y + ii2[4] * this.r2x * this.r2x;
  97063. 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]));
  97064. this.dd = new OIMO.Mat33(
  97065. k[4] * k[8] - k[5] * k[7], k[2] * k[7] - k[1] * k[8], k[1] * k[5] - k[2] * k[4],
  97066. k[5] * k[6] - k[3] * k[8], k[0] * k[8] - k[2] * k[6], k[2] * k[3] - k[0] * k[5],
  97067. k[3] * k[7] - k[4] * k[6], k[1] * k[6] - k[0] * k[7], k[0] * k[4] - k[1] * k[3]
  97068. ).multiply(inv);
  97069. this.velx = this.p2.x - this.p1.x;
  97070. this.vely = this.p2.y - this.p1.y;
  97071. this.velz = this.p2.z - this.p1.z;
  97072. var len = OIMO.sqrt(this.velx * this.velx + this.vely * this.vely + this.velz * this.velz);
  97073. if (len > 0.005) {
  97074. len = (0.005 - len) / len * invTimeStep * 0.05;
  97075. this.velx *= len;
  97076. this.vely *= len;
  97077. this.velz *= len;
  97078. } else {
  97079. this.velx = 0;
  97080. this.vely = 0;
  97081. this.velz = 0;
  97082. }
  97083. this.impx *= 0.95;
  97084. this.impy *= 0.95;
  97085. this.impz *= 0.95;
  97086. this.l1.x += this.impx * this.m1;
  97087. this.l1.y += this.impy * this.m1;
  97088. this.l1.z += this.impz * this.m1;
  97089. this.a1.x += this.impx * this.ax1x + this.impy * this.ay1x + this.impz * this.az1x;
  97090. this.a1.y += this.impx * this.ax1y + this.impy * this.ay1y + this.impz * this.az1y;
  97091. this.a1.z += this.impx * this.ax1z + this.impy * this.ay1z + this.impz * this.az1z;
  97092. this.l2.x -= this.impx * this.m2;
  97093. this.l2.y -= this.impy * this.m2;
  97094. this.l2.z -= this.impz * this.m2;
  97095. this.a2.x -= this.impx * this.ax2x + this.impy * this.ay2x + this.impz * this.az2x;
  97096. this.a2.y -= this.impx * this.ax2y + this.impy * this.ay2y + this.impz * this.az2y;
  97097. this.a2.z -= this.impx * this.ax2z + this.impy * this.ay2z + this.impz * this.az2z;
  97098. },
  97099. solve: function () {
  97100. var d = this.dd.elements;
  97101. 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;
  97102. 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;
  97103. 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;
  97104. var nimpx = rvx * d[0] + rvy * d[1] + rvz * d[2];
  97105. var nimpy = rvx * d[3] + rvy * d[4] + rvz * d[5];
  97106. var nimpz = rvx * d[6] + rvy * d[7] + rvz * d[8];
  97107. this.impx += nimpx;
  97108. this.impy += nimpy;
  97109. this.impz += nimpz;
  97110. this.l1.x += nimpx * this.m1;
  97111. this.l1.y += nimpy * this.m1;
  97112. this.l1.z += nimpz * this.m1;
  97113. this.a1.x += nimpx * this.ax1x + nimpy * this.ay1x + nimpz * this.az1x;
  97114. this.a1.y += nimpx * this.ax1y + nimpy * this.ay1y + nimpz * this.az1y;
  97115. this.a1.z += nimpx * this.ax1z + nimpy * this.ay1z + nimpz * this.az1z;
  97116. this.l2.x -= nimpx * this.m2;
  97117. this.l2.y -= nimpy * this.m2;
  97118. this.l2.z -= nimpz * this.m2;
  97119. this.a2.x -= nimpx * this.ax2x + nimpy * this.ay2x + nimpz * this.az2x;
  97120. this.a2.y -= nimpx * this.ax2y + nimpy * this.ay2y + nimpz * this.az2y;
  97121. this.a2.z -= nimpx * this.ax2z + nimpy * this.ay2z + nimpz * this.az2z;
  97122. }
  97123. }
  97124. /**
  97125. * A three-axis rotational constraint for various joints.
  97126. * @author saharan
  97127. */
  97128. OIMO.Rotational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
  97129. this.cfm1 = NaN;
  97130. this.cfm2 = NaN;
  97131. this.cfm3 = NaN;
  97132. this.i1e00 = NaN;
  97133. this.i1e01 = NaN;
  97134. this.i1e02 = NaN;
  97135. this.i1e10 = NaN;
  97136. this.i1e11 = NaN;
  97137. this.i1e12 = NaN;
  97138. this.i1e20 = NaN;
  97139. this.i1e21 = NaN;
  97140. this.i1e22 = NaN;
  97141. this.i2e00 = NaN;
  97142. this.i2e01 = NaN;
  97143. this.i2e02 = NaN;
  97144. this.i2e10 = NaN;
  97145. this.i2e11 = NaN;
  97146. this.i2e12 = NaN;
  97147. this.i2e20 = NaN;
  97148. this.i2e21 = NaN;
  97149. this.i2e22 = NaN;
  97150. this.ax1 = NaN;
  97151. this.ay1 = NaN;
  97152. this.az1 = NaN;
  97153. this.ax2 = NaN;
  97154. this.ay2 = NaN;
  97155. this.az2 = NaN;
  97156. this.ax3 = NaN;
  97157. this.ay3 = NaN;
  97158. this.az3 = NaN;
  97159. this.a1x1 = NaN; // jacoians
  97160. this.a1y1 = NaN;
  97161. this.a1z1 = NaN;
  97162. this.a2x1 = NaN;
  97163. this.a2y1 = NaN;
  97164. this.a2z1 = NaN;
  97165. this.a1x2 = NaN;
  97166. this.a1y2 = NaN;
  97167. this.a1z2 = NaN;
  97168. this.a2x2 = NaN;
  97169. this.a2y2 = NaN;
  97170. this.a2z2 = NaN;
  97171. this.a1x3 = NaN;
  97172. this.a1y3 = NaN;
  97173. this.a1z3 = NaN;
  97174. this.a2x3 = NaN;
  97175. this.a2y3 = NaN;
  97176. this.a2z3 = NaN;
  97177. this.lowerLimit1 = NaN;
  97178. this.upperLimit1 = NaN;
  97179. this.limitVelocity1 = NaN;
  97180. this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  97181. this.enableMotor1 = false;
  97182. this.motorSpeed1 = NaN;
  97183. this.maxMotorForce1 = NaN;
  97184. this.maxMotorImpulse1 = NaN;
  97185. this.lowerLimit2 = NaN;
  97186. this.upperLimit2 = NaN;
  97187. this.limitVelocity2 = NaN;
  97188. this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  97189. this.enableMotor2 = false;
  97190. this.motorSpeed2 = NaN;
  97191. this.maxMotorForce2 = NaN;
  97192. this.maxMotorImpulse2 = NaN;
  97193. this.lowerLimit3 = NaN;
  97194. this.upperLimit3 = NaN;
  97195. this.limitVelocity3 = NaN;
  97196. this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  97197. this.enableMotor3 = false;
  97198. this.motorSpeed3 = NaN;
  97199. this.maxMotorForce3 = NaN;
  97200. this.maxMotorImpulse3 = NaN;
  97201. this.k00 = NaN; // K = J*M*JT
  97202. this.k01 = NaN;
  97203. this.k02 = NaN;
  97204. this.k10 = NaN;
  97205. this.k11 = NaN;
  97206. this.k12 = NaN;
  97207. this.k20 = NaN;
  97208. this.k21 = NaN;
  97209. this.k22 = NaN;
  97210. this.kv00 = NaN; // diagonals without CFMs
  97211. this.kv11 = NaN;
  97212. this.kv22 = NaN;
  97213. this.dv00 = NaN; // ...inverted
  97214. this.dv11 = NaN;
  97215. this.dv22 = NaN;
  97216. this.d00 = NaN; // K^-1
  97217. this.d01 = NaN;
  97218. this.d02 = NaN;
  97219. this.d10 = NaN;
  97220. this.d11 = NaN;
  97221. this.d12 = NaN;
  97222. this.d20 = NaN;
  97223. this.d21 = NaN;
  97224. this.d22 = NaN;
  97225. this.limitMotor1 = limitMotor1;
  97226. this.limitMotor2 = limitMotor2;
  97227. this.limitMotor3 = limitMotor3;
  97228. this.b1 = joint.body1;
  97229. this.b2 = joint.body2;
  97230. this.a1 = this.b1.angularVelocity;
  97231. this.a2 = this.b2.angularVelocity;
  97232. this.i1 = this.b1.inverseInertia;
  97233. this.i2 = this.b2.inverseInertia;
  97234. this.limitImpulse1 = 0;
  97235. this.motorImpulse1 = 0;
  97236. this.limitImpulse2 = 0;
  97237. this.motorImpulse2 = 0;
  97238. this.limitImpulse3 = 0;
  97239. this.motorImpulse3 = 0;
  97240. }
  97241. OIMO.Rotational3Constraint.prototype = {
  97242. constructor: OIMO.Rotational3Constraint,
  97243. preSolve: function (timeStep, invTimeStep) {
  97244. this.ax1 = this.limitMotor1.axis.x;
  97245. this.ay1 = this.limitMotor1.axis.y;
  97246. this.az1 = this.limitMotor1.axis.z;
  97247. this.ax2 = this.limitMotor2.axis.x;
  97248. this.ay2 = this.limitMotor2.axis.y;
  97249. this.az2 = this.limitMotor2.axis.z;
  97250. this.ax3 = this.limitMotor3.axis.x;
  97251. this.ay3 = this.limitMotor3.axis.y;
  97252. this.az3 = this.limitMotor3.axis.z;
  97253. this.lowerLimit1 = this.limitMotor1.lowerLimit;
  97254. this.upperLimit1 = this.limitMotor1.upperLimit;
  97255. this.motorSpeed1 = this.limitMotor1.motorSpeed;
  97256. this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
  97257. this.enableMotor1 = this.maxMotorForce1 > 0;
  97258. this.lowerLimit2 = this.limitMotor2.lowerLimit;
  97259. this.upperLimit2 = this.limitMotor2.upperLimit;
  97260. this.motorSpeed2 = this.limitMotor2.motorSpeed;
  97261. this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
  97262. this.enableMotor2 = this.maxMotorForce2 > 0;
  97263. this.lowerLimit3 = this.limitMotor3.lowerLimit;
  97264. this.upperLimit3 = this.limitMotor3.upperLimit;
  97265. this.motorSpeed3 = this.limitMotor3.motorSpeed;
  97266. this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
  97267. this.enableMotor3 = this.maxMotorForce3 > 0;
  97268. var ti1 = this.i1.elements;
  97269. var ti2 = this.i2.elements;
  97270. this.i1e00 = ti1[0];
  97271. this.i1e01 = ti1[1];
  97272. this.i1e02 = ti1[2];
  97273. this.i1e10 = ti1[3];
  97274. this.i1e11 = ti1[4];
  97275. this.i1e12 = ti1[5];
  97276. this.i1e20 = ti1[6];
  97277. this.i1e21 = ti1[7];
  97278. this.i1e22 = ti1[8];
  97279. this.i2e00 = ti2[0];
  97280. this.i2e01 = ti2[1];
  97281. this.i2e02 = ti2[2];
  97282. this.i2e10 = ti2[3];
  97283. this.i2e11 = ti2[4];
  97284. this.i2e12 = ti2[5];
  97285. this.i2e20 = ti2[6];
  97286. this.i2e21 = ti2[7];
  97287. this.i2e22 = ti2[8];
  97288. var frequency1 = this.limitMotor1.frequency;
  97289. var frequency2 = this.limitMotor2.frequency;
  97290. var frequency3 = this.limitMotor3.frequency;
  97291. var enableSpring1 = frequency1 > 0;
  97292. var enableSpring2 = frequency2 > 0;
  97293. var enableSpring3 = frequency3 > 0;
  97294. var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
  97295. var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
  97296. var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
  97297. var angle1 = this.limitMotor1.angle;
  97298. if (enableLimit1) {
  97299. if (this.lowerLimit1 == this.upperLimit1) {
  97300. if (this.limitState1 != 0) {
  97301. this.limitState1 = 0;
  97302. this.limitImpulse1 = 0;
  97303. }
  97304. this.limitVelocity1 = this.lowerLimit1 - angle1;
  97305. } else if (angle1 < this.lowerLimit1) {
  97306. if (this.limitState1 != -1) {
  97307. this.limitState1 = -1;
  97308. this.limitImpulse1 = 0;
  97309. }
  97310. this.limitVelocity1 = this.lowerLimit1 - angle1;
  97311. } else if (angle1 > this.upperLimit1) {
  97312. if (this.limitState1 != 1) {
  97313. this.limitState1 = 1;
  97314. this.limitImpulse1 = 0;
  97315. }
  97316. this.limitVelocity1 = this.upperLimit1 - angle1;
  97317. } else {
  97318. this.limitState1 = 2;
  97319. this.limitImpulse1 = 0;
  97320. this.limitVelocity1 = 0;
  97321. }
  97322. if (!enableSpring1) {
  97323. if (this.limitVelocity1 > 0.02) this.limitVelocity1 -= 0.02;
  97324. else if (this.limitVelocity1 < -0.02) this.limitVelocity1 += 0.02;
  97325. else this.limitVelocity1 = 0;
  97326. }
  97327. } else {
  97328. this.limitState1 = 2;
  97329. this.limitImpulse1 = 0;
  97330. }
  97331. var angle2 = this.limitMotor2.angle;
  97332. if (enableLimit2) {
  97333. if (this.lowerLimit2 == this.upperLimit2) {
  97334. if (this.limitState2 != 0) {
  97335. this.limitState2 = 0;
  97336. this.limitImpulse2 = 0;
  97337. }
  97338. this.limitVelocity2 = this.lowerLimit2 - angle2;
  97339. } else if (angle2 < this.lowerLimit2) {
  97340. if (this.limitState2 != -1) {
  97341. this.limitState2 = -1;
  97342. this.limitImpulse2 = 0;
  97343. }
  97344. this.limitVelocity2 = this.lowerLimit2 - angle2;
  97345. } else if (angle2 > this.upperLimit2) {
  97346. if (this.limitState2 != 1) {
  97347. this.limitState2 = 1;
  97348. this.limitImpulse2 = 0;
  97349. }
  97350. this.limitVelocity2 = this.upperLimit2 - angle2;
  97351. } else {
  97352. this.limitState2 = 2;
  97353. this.limitImpulse2 = 0;
  97354. this.limitVelocity2 = 0;
  97355. }
  97356. if (!enableSpring2) {
  97357. if (this.limitVelocity2 > 0.02) this.limitVelocity2 -= 0.02;
  97358. else if (this.limitVelocity2 < -0.02) this.limitVelocity2 += 0.02;
  97359. else this.limitVelocity2 = 0;
  97360. }
  97361. } else {
  97362. this.limitState2 = 2;
  97363. this.limitImpulse2 = 0;
  97364. }
  97365. var angle3 = this.limitMotor3.angle;
  97366. if (enableLimit3) {
  97367. if (this.lowerLimit3 == this.upperLimit3) {
  97368. if (this.limitState3 != 0) {
  97369. this.limitState3 = 0;
  97370. this.limitImpulse3 = 0;
  97371. }
  97372. this.limitVelocity3 = this.lowerLimit3 - angle3;
  97373. } else if (angle3 < this.lowerLimit3) {
  97374. if (this.limitState3 != -1) {
  97375. this.limitState3 = -1;
  97376. this.limitImpulse3 = 0;
  97377. }
  97378. this.limitVelocity3 = this.lowerLimit3 - angle3;
  97379. } else if (angle3 > this.upperLimit3) {
  97380. if (this.limitState3 != 1) {
  97381. this.limitState3 = 1;
  97382. this.limitImpulse3 = 0;
  97383. }
  97384. this.limitVelocity3 = this.upperLimit3 - angle3;
  97385. } else {
  97386. this.limitState3 = 2;
  97387. this.limitImpulse3 = 0;
  97388. this.limitVelocity3 = 0;
  97389. }
  97390. if (!enableSpring3) {
  97391. if (this.limitVelocity3 > 0.02) this.limitVelocity3 -= 0.02;
  97392. else if (this.limitVelocity3 < -0.02) this.limitVelocity3 += 0.02;
  97393. else this.limitVelocity3 = 0;
  97394. }
  97395. } else {
  97396. this.limitState3 = 2;
  97397. this.limitImpulse3 = 0;
  97398. }
  97399. if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
  97400. this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
  97401. } else {
  97402. this.motorImpulse1 = 0;
  97403. this.maxMotorImpulse1 = 0;
  97404. }
  97405. if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
  97406. this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
  97407. } else {
  97408. this.motorImpulse2 = 0;
  97409. this.maxMotorImpulse2 = 0;
  97410. }
  97411. if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
  97412. this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
  97413. } else {
  97414. this.motorImpulse3 = 0;
  97415. this.maxMotorImpulse3 = 0;
  97416. }
  97417. // build jacobians
  97418. this.a1x1 = this.ax1 * this.i1e00 + this.ay1 * this.i1e01 + this.az1 * this.i1e02;
  97419. this.a1y1 = this.ax1 * this.i1e10 + this.ay1 * this.i1e11 + this.az1 * this.i1e12;
  97420. this.a1z1 = this.ax1 * this.i1e20 + this.ay1 * this.i1e21 + this.az1 * this.i1e22;
  97421. this.a2x1 = this.ax1 * this.i2e00 + this.ay1 * this.i2e01 + this.az1 * this.i2e02;
  97422. this.a2y1 = this.ax1 * this.i2e10 + this.ay1 * this.i2e11 + this.az1 * this.i2e12;
  97423. this.a2z1 = this.ax1 * this.i2e20 + this.ay1 * this.i2e21 + this.az1 * this.i2e22;
  97424. this.a1x2 = this.ax2 * this.i1e00 + this.ay2 * this.i1e01 + this.az2 * this.i1e02;
  97425. this.a1y2 = this.ax2 * this.i1e10 + this.ay2 * this.i1e11 + this.az2 * this.i1e12;
  97426. this.a1z2 = this.ax2 * this.i1e20 + this.ay2 * this.i1e21 + this.az2 * this.i1e22;
  97427. this.a2x2 = this.ax2 * this.i2e00 + this.ay2 * this.i2e01 + this.az2 * this.i2e02;
  97428. this.a2y2 = this.ax2 * this.i2e10 + this.ay2 * this.i2e11 + this.az2 * this.i2e12;
  97429. this.a2z2 = this.ax2 * this.i2e20 + this.ay2 * this.i2e21 + this.az2 * this.i2e22;
  97430. this.a1x3 = this.ax3 * this.i1e00 + this.ay3 * this.i1e01 + this.az3 * this.i1e02;
  97431. this.a1y3 = this.ax3 * this.i1e10 + this.ay3 * this.i1e11 + this.az3 * this.i1e12;
  97432. this.a1z3 = this.ax3 * this.i1e20 + this.ay3 * this.i1e21 + this.az3 * this.i1e22;
  97433. this.a2x3 = this.ax3 * this.i2e00 + this.ay3 * this.i2e01 + this.az3 * this.i2e02;
  97434. this.a2y3 = this.ax3 * this.i2e10 + this.ay3 * this.i2e11 + this.az3 * this.i2e12;
  97435. this.a2z3 = this.ax3 * this.i2e20 + this.ay3 * this.i2e21 + this.az3 * this.i2e22;
  97436. // build an impulse matrix
  97437. this.k00 = this.ax1 * (this.a1x1 + this.a2x1) + this.ay1 * (this.a1y1 + this.a2y1) + this.az1 * (this.a1z1 + this.a2z1);
  97438. this.k01 = this.ax1 * (this.a1x2 + this.a2x2) + this.ay1 * (this.a1y2 + this.a2y2) + this.az1 * (this.a1z2 + this.a2z2);
  97439. this.k02 = this.ax1 * (this.a1x3 + this.a2x3) + this.ay1 * (this.a1y3 + this.a2y3) + this.az1 * (this.a1z3 + this.a2z3);
  97440. this.k10 = this.ax2 * (this.a1x1 + this.a2x1) + this.ay2 * (this.a1y1 + this.a2y1) + this.az2 * (this.a1z1 + this.a2z1);
  97441. this.k11 = this.ax2 * (this.a1x2 + this.a2x2) + this.ay2 * (this.a1y2 + this.a2y2) + this.az2 * (this.a1z2 + this.a2z2);
  97442. this.k12 = this.ax2 * (this.a1x3 + this.a2x3) + this.ay2 * (this.a1y3 + this.a2y3) + this.az2 * (this.a1z3 + this.a2z3);
  97443. this.k20 = this.ax3 * (this.a1x1 + this.a2x1) + this.ay3 * (this.a1y1 + this.a2y1) + this.az3 * (this.a1z1 + this.a2z1);
  97444. this.k21 = this.ax3 * (this.a1x2 + this.a2x2) + this.ay3 * (this.a1y2 + this.a2y2) + this.az3 * (this.a1z2 + this.a2z2);
  97445. this.k22 = this.ax3 * (this.a1x3 + this.a2x3) + this.ay3 * (this.a1y3 + this.a2y3) + this.az3 * (this.a1z3 + this.a2z3);
  97446. this.kv00 = this.k00;
  97447. this.kv11 = this.k11;
  97448. this.kv22 = this.k22;
  97449. this.dv00 = 1 / this.kv00;
  97450. this.dv11 = 1 / this.kv11;
  97451. this.dv22 = 1 / this.kv22;
  97452. if (enableSpring1 && this.limitState1 != 2) {
  97453. var omega = 6.2831853 * frequency1;
  97454. var k = omega * omega * timeStep;
  97455. var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
  97456. this.cfm1 = this.kv00 * dmp;
  97457. this.limitVelocity1 *= k * dmp;
  97458. } else {
  97459. this.cfm1 = 0;
  97460. this.limitVelocity1 *= invTimeStep * 0.05;
  97461. }
  97462. if (enableSpring2 && this.limitState2 != 2) {
  97463. omega = 6.2831853 * frequency2;
  97464. k = omega * omega * timeStep;
  97465. dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
  97466. this.cfm2 = this.kv11 * dmp;
  97467. this.limitVelocity2 *= k * dmp;
  97468. } else {
  97469. this.cfm2 = 0;
  97470. this.limitVelocity2 *= invTimeStep * 0.05;
  97471. }
  97472. if (enableSpring3 && this.limitState3 != 2) {
  97473. omega = 6.2831853 * frequency3;
  97474. k = omega * omega * timeStep;
  97475. dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
  97476. this.cfm3 = this.kv22 * dmp;
  97477. this.limitVelocity3 *= k * dmp;
  97478. } else {
  97479. this.cfm3 = 0;
  97480. this.limitVelocity3 *= invTimeStep * 0.05;
  97481. }
  97482. this.k00 += this.cfm1;
  97483. this.k11 += this.cfm2;
  97484. this.k22 += this.cfm3;
  97485. var inv = 1 / (
  97486. this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
  97487. this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
  97488. this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
  97489. );
  97490. this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
  97491. this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
  97492. this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
  97493. this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
  97494. this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
  97495. this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
  97496. this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
  97497. this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
  97498. this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
  97499. this.limitImpulse1 *= 0.95;
  97500. this.motorImpulse1 *= 0.95;
  97501. this.limitImpulse2 *= 0.95;
  97502. this.motorImpulse2 *= 0.95;
  97503. this.limitImpulse3 *= 0.95;
  97504. this.motorImpulse3 *= 0.95;
  97505. var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
  97506. var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
  97507. var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
  97508. this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
  97509. this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
  97510. this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
  97511. this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
  97512. this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
  97513. this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
  97514. },
  97515. solve_: function () {
  97516. var rvx = this.a2.x - this.a1.x;
  97517. var rvy = this.a2.y - this.a1.y;
  97518. var rvz = this.a2.z - this.a1.z;
  97519. this.limitVelocity3 = 30;
  97520. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1 - this.limitVelocity1;
  97521. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2 - this.limitVelocity2;
  97522. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3 - this.limitVelocity3;
  97523. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  97524. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  97525. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  97526. this.limitImpulse1 += dLimitImpulse1;
  97527. this.limitImpulse2 += dLimitImpulse2;
  97528. this.limitImpulse3 += dLimitImpulse3;
  97529. this.a1.x += dLimitImpulse1 * this.a1x1 + dLimitImpulse2 * this.a1x2 + dLimitImpulse3 * this.a1x3;
  97530. this.a1.y += dLimitImpulse1 * this.a1y1 + dLimitImpulse2 * this.a1y2 + dLimitImpulse3 * this.a1y3;
  97531. this.a1.z += dLimitImpulse1 * this.a1z1 + dLimitImpulse2 * this.a1z2 + dLimitImpulse3 * this.a1z3;
  97532. this.a2.x -= dLimitImpulse1 * this.a2x1 + dLimitImpulse2 * this.a2x2 + dLimitImpulse3 * this.a2x3;
  97533. this.a2.y -= dLimitImpulse1 * this.a2y1 + dLimitImpulse2 * this.a2y2 + dLimitImpulse3 * this.a2y3;
  97534. this.a2.z -= dLimitImpulse1 * this.a2z1 + dLimitImpulse2 * this.a2z2 + dLimitImpulse3 * this.a2z3;
  97535. },
  97536. solve: function () {
  97537. var rvx = this.a2.x - this.a1.x;
  97538. var rvy = this.a2.y - this.a1.y;
  97539. var rvz = this.a2.z - this.a1.z;
  97540. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
  97541. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  97542. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
  97543. var oldMotorImpulse1 = this.motorImpulse1;
  97544. var oldMotorImpulse2 = this.motorImpulse2;
  97545. var oldMotorImpulse3 = this.motorImpulse3;
  97546. var dMotorImpulse1 = 0;
  97547. var dMotorImpulse2 = 0;
  97548. var dMotorImpulse3 = 0;
  97549. if (this.enableMotor1) {
  97550. dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
  97551. this.motorImpulse1 += dMotorImpulse1;
  97552. if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
  97553. this.motorImpulse1 = this.maxMotorImpulse1;
  97554. } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
  97555. this.motorImpulse1 = -this.maxMotorImpulse1;
  97556. }
  97557. dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
  97558. }
  97559. if (this.enableMotor2) {
  97560. dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
  97561. this.motorImpulse2 += dMotorImpulse2;
  97562. if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
  97563. this.motorImpulse2 = this.maxMotorImpulse2;
  97564. } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
  97565. this.motorImpulse2 = -this.maxMotorImpulse2;
  97566. }
  97567. dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
  97568. }
  97569. if (this.enableMotor3) {
  97570. dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
  97571. this.motorImpulse3 += dMotorImpulse3;
  97572. if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
  97573. this.motorImpulse3 = this.maxMotorImpulse3;
  97574. } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
  97575. this.motorImpulse3 = -this.maxMotorImpulse3;
  97576. }
  97577. dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
  97578. }
  97579. // apply motor impulse to relative velocity
  97580. rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
  97581. rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
  97582. rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
  97583. // subtract target velocity and applied impulse
  97584. rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
  97585. rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
  97586. rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
  97587. var oldLimitImpulse1 = this.limitImpulse1;
  97588. var oldLimitImpulse2 = this.limitImpulse2;
  97589. var oldLimitImpulse3 = this.limitImpulse3;
  97590. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  97591. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  97592. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  97593. this.limitImpulse1 += dLimitImpulse1;
  97594. this.limitImpulse2 += dLimitImpulse2;
  97595. this.limitImpulse3 += dLimitImpulse3;
  97596. // clamp
  97597. var clampState = 0;
  97598. if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
  97599. dLimitImpulse1 = -oldLimitImpulse1;
  97600. rvn2 += dLimitImpulse1 * this.k10;
  97601. rvn3 += dLimitImpulse1 * this.k20;
  97602. clampState |= 1;
  97603. }
  97604. if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
  97605. dLimitImpulse2 = -oldLimitImpulse2;
  97606. rvn1 += dLimitImpulse2 * this.k01;
  97607. rvn3 += dLimitImpulse2 * this.k21;
  97608. clampState |= 2;
  97609. }
  97610. if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
  97611. dLimitImpulse3 = -oldLimitImpulse3;
  97612. rvn1 += dLimitImpulse3 * this.k02;
  97613. rvn2 += dLimitImpulse3 * this.k12;
  97614. clampState |= 4;
  97615. }
  97616. // update un-clamped impulse
  97617. // TODO: isolate division
  97618. var det;
  97619. switch (clampState) {
  97620. case 1: // update 2 3
  97621. det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
  97622. dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
  97623. dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
  97624. break;
  97625. case 2: // update 1 3
  97626. det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
  97627. dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
  97628. dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
  97629. break;
  97630. case 3: // update 3
  97631. dLimitImpulse3 = rvn3 / this.k22;
  97632. break;
  97633. case 4: // update 1 2
  97634. det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
  97635. dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
  97636. dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
  97637. break;
  97638. case 5: // update 2
  97639. dLimitImpulse2 = rvn2 / this.k11;
  97640. break;
  97641. case 6: // update 1
  97642. dLimitImpulse1 = rvn1 / this.k00;
  97643. break;
  97644. }
  97645. this.limitImpulse1 = dLimitImpulse1 + oldLimitImpulse1;
  97646. this.limitImpulse2 = dLimitImpulse2 + oldLimitImpulse2;
  97647. this.limitImpulse3 = dLimitImpulse3 + oldLimitImpulse3;
  97648. var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
  97649. var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
  97650. var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
  97651. // apply impulse
  97652. this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
  97653. this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
  97654. this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
  97655. this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
  97656. this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
  97657. this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
  97658. rvx = this.a2.x - this.a1.x;
  97659. rvy = this.a2.y - this.a1.y;
  97660. rvz = this.a2.z - this.a1.z;
  97661. rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  97662. }
  97663. }
  97664. /**
  97665. * A rotational constraint for various joints.
  97666. * @author saharan
  97667. */
  97668. OIMO.RotationalConstraint = function (joint, limitMotor) {
  97669. this.cfm = NaN;
  97670. this.i1e00 = NaN;
  97671. this.i1e01 = NaN;
  97672. this.i1e02 = NaN;
  97673. this.i1e10 = NaN;
  97674. this.i1e11 = NaN;
  97675. this.i1e12 = NaN;
  97676. this.i1e20 = NaN;
  97677. this.i1e21 = NaN;
  97678. this.i1e22 = NaN;
  97679. this.i2e00 = NaN;
  97680. this.i2e01 = NaN;
  97681. this.i2e02 = NaN;
  97682. this.i2e10 = NaN;
  97683. this.i2e11 = NaN;
  97684. this.i2e12 = NaN;
  97685. this.i2e20 = NaN;
  97686. this.i2e21 = NaN;
  97687. this.i2e22 = NaN;
  97688. this.motorDenom = NaN;
  97689. this.invMotorDenom = NaN;
  97690. this.invDenom = NaN;
  97691. this.ax = NaN;
  97692. this.ay = NaN;
  97693. this.az = NaN;
  97694. this.a1x = NaN;
  97695. this.a1y = NaN;
  97696. this.a1z = NaN;
  97697. this.a2x = NaN;
  97698. this.a2y = NaN;
  97699. this.a2z = NaN;
  97700. this.enableLimit = false;
  97701. this.lowerLimit = NaN;
  97702. this.upperLimit = NaN;
  97703. this.limitVelocity = NaN;
  97704. this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  97705. this.enableMotor = false;
  97706. this.motorSpeed = NaN;
  97707. this.maxMotorForce = NaN;
  97708. this.maxMotorImpulse = NaN;
  97709. this.limitMotor = limitMotor;
  97710. this.b1 = joint.body1;
  97711. this.b2 = joint.body2;
  97712. this.a1 = this.b1.angularVelocity;
  97713. this.a2 = this.b2.angularVelocity;
  97714. this.i1 = this.b1.inverseInertia;
  97715. this.i2 = this.b2.inverseInertia;
  97716. this.limitImpulse = 0;
  97717. this.motorImpulse = 0;
  97718. }
  97719. OIMO.RotationalConstraint.prototype = {
  97720. constructor: OIMO.RotationalConstraint,
  97721. preSolve: function (timeStep, invTimeStep) {
  97722. this.ax = this.limitMotor.axis.x;
  97723. this.ay = this.limitMotor.axis.y;
  97724. this.az = this.limitMotor.axis.z;
  97725. this.lowerLimit = this.limitMotor.lowerLimit;
  97726. this.upperLimit = this.limitMotor.upperLimit;
  97727. this.motorSpeed = this.limitMotor.motorSpeed;
  97728. this.maxMotorForce = this.limitMotor.maxMotorForce;
  97729. this.enableMotor = this.maxMotorForce > 0;
  97730. var ti1 = this.i1.elements;
  97731. var ti2 = this.i2.elements;
  97732. this.i1e00 = ti1[0];
  97733. this.i1e01 = ti1[1];
  97734. this.i1e02 = ti1[2];
  97735. this.i1e10 = ti1[3];
  97736. this.i1e11 = ti1[4];
  97737. this.i1e12 = ti1[5];
  97738. this.i1e20 = ti1[6];
  97739. this.i1e21 = ti1[7];
  97740. this.i1e22 = ti1[8];
  97741. this.i2e00 = ti2[0];
  97742. this.i2e01 = ti2[1];
  97743. this.i2e02 = ti2[2];
  97744. this.i2e10 = ti2[3];
  97745. this.i2e11 = ti2[4];
  97746. this.i2e12 = ti2[5];
  97747. this.i2e20 = ti2[6];
  97748. this.i2e21 = ti2[7];
  97749. this.i2e22 = ti2[8];
  97750. var frequency = this.limitMotor.frequency;
  97751. var enableSpring = frequency > 0;
  97752. var enableLimit = this.lowerLimit <= this.upperLimit;
  97753. var angle = this.limitMotor.angle;
  97754. if (enableLimit) {
  97755. if (this.lowerLimit == this.upperLimit) {
  97756. if (this.limitState != 0) {
  97757. this.limitState = 0;
  97758. this.limitImpulse = 0;
  97759. }
  97760. this.limitVelocity = this.lowerLimit - angle;
  97761. } else if (angle < this.lowerLimit) {
  97762. if (this.limitState != -1) {
  97763. this.limitState = -1;
  97764. this.limitImpulse = 0;
  97765. }
  97766. this.limitVelocity = this.lowerLimit - angle;
  97767. } else if (angle > this.upperLimit) {
  97768. if (this.limitState != 1) {
  97769. this.limitState = 1;
  97770. this.limitImpulse = 0;
  97771. }
  97772. this.limitVelocity = this.upperLimit - angle;
  97773. } else {
  97774. this.limitState = 2;
  97775. this.limitImpulse = 0;
  97776. this.limitVelocity = 0;
  97777. }
  97778. if (!enableSpring) {
  97779. if (this.limitVelocity > 0.02) this.limitVelocity -= 0.02;
  97780. else if (this.limitVelocity < -0.02) this.limitVelocity += 0.02;
  97781. else this.limitVelocity = 0;
  97782. }
  97783. } else {
  97784. this.limitState = 2;
  97785. this.limitImpulse = 0;
  97786. }
  97787. if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
  97788. this.maxMotorImpulse = this.maxMotorForce * timeStep;
  97789. } else {
  97790. this.motorImpulse = 0;
  97791. this.maxMotorImpulse = 0;
  97792. }
  97793. this.a1x = this.ax * this.i1e00 + this.ay * this.i1e01 + this.az * this.i1e02;
  97794. this.a1y = this.ax * this.i1e10 + this.ay * this.i1e11 + this.az * this.i1e12;
  97795. this.a1z = this.ax * this.i1e20 + this.ay * this.i1e21 + this.az * this.i1e22;
  97796. this.a2x = this.ax * this.i2e00 + this.ay * this.i2e01 + this.az * this.i2e02;
  97797. this.a2y = this.ax * this.i2e10 + this.ay * this.i2e11 + this.az * this.i2e12;
  97798. this.a2z = this.ax * this.i2e20 + this.ay * this.i2e21 + this.az * this.i2e22;
  97799. this.motorDenom = this.ax * (this.a1x + this.a2x) + this.ay * (this.a1y + this.a2y) + this.az * (this.a1z + this.a2z);
  97800. this.invMotorDenom = 1 / this.motorDenom;
  97801. if (enableSpring && this.limitState != 2) {
  97802. var omega = 6.2831853 * frequency;
  97803. var k = omega * omega * timeStep;
  97804. var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
  97805. this.cfm = this.motorDenom * dmp;
  97806. this.limitVelocity *= k * dmp;
  97807. } else {
  97808. this.cfm = 0;
  97809. this.limitVelocity *= invTimeStep * 0.05;
  97810. }
  97811. this.invDenom = 1 / (this.motorDenom + this.cfm);
  97812. this.limitImpulse *= 0.95;
  97813. this.motorImpulse *= 0.95;
  97814. var totalImpulse = this.limitImpulse + this.motorImpulse;
  97815. this.a1.x += totalImpulse * this.a1x;
  97816. this.a1.y += totalImpulse * this.a1y;
  97817. this.a1.z += totalImpulse * this.a1z;
  97818. this.a2.x -= totalImpulse * this.a2x;
  97819. this.a2.y -= totalImpulse * this.a2y;
  97820. this.a2.z -= totalImpulse * this.a2z;
  97821. },
  97822. solve: function () {
  97823. 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);
  97824. // motor part
  97825. var newMotorImpulse;
  97826. if (this.enableMotor) {
  97827. newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
  97828. var oldMotorImpulse = this.motorImpulse;
  97829. this.motorImpulse += newMotorImpulse;
  97830. if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
  97831. else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
  97832. newMotorImpulse = this.motorImpulse - oldMotorImpulse;
  97833. rvn -= newMotorImpulse * this.motorDenom;
  97834. } else newMotorImpulse = 0;
  97835. // limit part
  97836. var newLimitImpulse;
  97837. if (this.limitState != 2) {
  97838. newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
  97839. var oldLimitImpulse = this.limitImpulse;
  97840. this.limitImpulse += newLimitImpulse;
  97841. if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
  97842. newLimitImpulse = this.limitImpulse - oldLimitImpulse;
  97843. } else newLimitImpulse = 0;
  97844. var totalImpulse = newLimitImpulse + newMotorImpulse;
  97845. this.a1.x += totalImpulse * this.a1x;
  97846. this.a1.y += totalImpulse * this.a1y;
  97847. this.a1.z += totalImpulse * this.a1z;
  97848. this.a2.x -= totalImpulse * this.a2x;
  97849. this.a2.y -= totalImpulse * this.a2y;
  97850. this.a2.z -= totalImpulse * this.a2z;
  97851. }
  97852. }
  97853. /**
  97854. * A three-axis translational constraint for various joints.
  97855. * @author saharan
  97856. */
  97857. OIMO.Translational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
  97858. this.m1 = NaN;
  97859. this.m2 = NaN;
  97860. this.i1e00 = NaN;
  97861. this.i1e01 = NaN;
  97862. this.i1e02 = NaN;
  97863. this.i1e10 = NaN;
  97864. this.i1e11 = NaN;
  97865. this.i1e12 = NaN;
  97866. this.i1e20 = NaN;
  97867. this.i1e21 = NaN;
  97868. this.i1e22 = NaN;
  97869. this.i2e00 = NaN;
  97870. this.i2e01 = NaN;
  97871. this.i2e02 = NaN;
  97872. this.i2e10 = NaN;
  97873. this.i2e11 = NaN;
  97874. this.i2e12 = NaN;
  97875. this.i2e20 = NaN;
  97876. this.i2e21 = NaN;
  97877. this.i2e22 = NaN;
  97878. this.ax1 = NaN;
  97879. this.ay1 = NaN;
  97880. this.az1 = NaN;
  97881. this.ax2 = NaN;
  97882. this.ay2 = NaN;
  97883. this.az2 = NaN;
  97884. this.ax3 = NaN;
  97885. this.ay3 = NaN;
  97886. this.az3 = NaN;
  97887. this.r1x = NaN;
  97888. this.r1y = NaN;
  97889. this.r1z = NaN;
  97890. this.r2x = NaN;
  97891. this.r2y = NaN;
  97892. this.r2z = NaN;
  97893. this.t1x1 = NaN;// jacobians
  97894. this.t1y1 = NaN;
  97895. this.t1z1 = NaN;
  97896. this.t2x1 = NaN;
  97897. this.t2y1 = NaN;
  97898. this.t2z1 = NaN;
  97899. this.l1x1 = NaN;
  97900. this.l1y1 = NaN;
  97901. this.l1z1 = NaN;
  97902. this.l2x1 = NaN;
  97903. this.l2y1 = NaN;
  97904. this.l2z1 = NaN;
  97905. this.a1x1 = NaN;
  97906. this.a1y1 = NaN;
  97907. this.a1z1 = NaN;
  97908. this.a2x1 = NaN;
  97909. this.a2y1 = NaN;
  97910. this.a2z1 = NaN;
  97911. this.t1x2 = NaN;
  97912. this.t1y2 = NaN;
  97913. this.t1z2 = NaN;
  97914. this.t2x2 = NaN;
  97915. this.t2y2 = NaN;
  97916. this.t2z2 = NaN;
  97917. this.l1x2 = NaN;
  97918. this.l1y2 = NaN;
  97919. this.l1z2 = NaN;
  97920. this.l2x2 = NaN;
  97921. this.l2y2 = NaN;
  97922. this.l2z2 = NaN;
  97923. this.a1x2 = NaN;
  97924. this.a1y2 = NaN;
  97925. this.a1z2 = NaN;
  97926. this.a2x2 = NaN;
  97927. this.a2y2 = NaN;
  97928. this.a2z2 = NaN;
  97929. this.t1x3 = NaN;
  97930. this.t1y3 = NaN;
  97931. this.t1z3 = NaN;
  97932. this.t2x3 = NaN;
  97933. this.t2y3 = NaN;
  97934. this.t2z3 = NaN;
  97935. this.l1x3 = NaN;
  97936. this.l1y3 = NaN;
  97937. this.l1z3 = NaN;
  97938. this.l2x3 = NaN;
  97939. this.l2y3 = NaN;
  97940. this.l2z3 = NaN;
  97941. this.a1x3 = NaN;
  97942. this.a1y3 = NaN;
  97943. this.a1z3 = NaN;
  97944. this.a2x3 = NaN;
  97945. this.a2y3 = NaN;
  97946. this.a2z3 = NaN;
  97947. this.lowerLimit1 = NaN;
  97948. this.upperLimit1 = NaN;
  97949. this.limitVelocity1 = NaN;
  97950. this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  97951. this.enableMotor1 = false;
  97952. this.motorSpeed1 = NaN;
  97953. this.maxMotorForce1 = NaN;
  97954. this.maxMotorImpulse1 = NaN;
  97955. this.lowerLimit2 = NaN;
  97956. this.upperLimit2 = NaN;
  97957. this.limitVelocity2 = NaN;
  97958. this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  97959. this.enableMotor2 = false;
  97960. this.motorSpeed2 = NaN;
  97961. this.maxMotorForce2 = NaN;
  97962. this.maxMotorImpulse2 = NaN;
  97963. this.lowerLimit3 = NaN;
  97964. this.upperLimit3 = NaN;
  97965. this.limitVelocity3 = NaN;
  97966. this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  97967. this.enableMotor3 = false;
  97968. this.motorSpeed3 = NaN;
  97969. this.maxMotorForce3 = NaN;
  97970. this.maxMotorImpulse3 = NaN;
  97971. this.k00 = NaN; // K = J*M*JT
  97972. this.k01 = NaN;
  97973. this.k02 = NaN;
  97974. this.k10 = NaN;
  97975. this.k11 = NaN;
  97976. this.k12 = NaN;
  97977. this.k20 = NaN;
  97978. this.k21 = NaN;
  97979. this.k22 = NaN;
  97980. this.kv00 = NaN; // diagonals without CFMs
  97981. this.kv11 = NaN;
  97982. this.kv22 = NaN;
  97983. this.dv00 = NaN; // ...inverted
  97984. this.dv11 = NaN;
  97985. this.dv22 = NaN;
  97986. this.d00 = NaN; // K^-1
  97987. this.d01 = NaN;
  97988. this.d02 = NaN;
  97989. this.d10 = NaN;
  97990. this.d11 = NaN;
  97991. this.d12 = NaN;
  97992. this.d20 = NaN;
  97993. this.d21 = NaN;
  97994. this.d22 = NaN;
  97995. this.limitMotor1 = limitMotor1;
  97996. this.limitMotor2 = limitMotor2;
  97997. this.limitMotor3 = limitMotor3;
  97998. this.b1 = joint.body1;
  97999. this.b2 = joint.body2;
  98000. this.p1 = joint.anchorPoint1;
  98001. this.p2 = joint.anchorPoint2;
  98002. this.r1 = joint.relativeAnchorPoint1;
  98003. this.r2 = joint.relativeAnchorPoint2;
  98004. this.l1 = this.b1.linearVelocity;
  98005. this.l2 = this.b2.linearVelocity;
  98006. this.a1 = this.b1.angularVelocity;
  98007. this.a2 = this.b2.angularVelocity;
  98008. this.i1 = this.b1.inverseInertia;
  98009. this.i2 = this.b2.inverseInertia;
  98010. this.limitImpulse1 = 0;
  98011. this.motorImpulse1 = 0;
  98012. this.limitImpulse2 = 0;
  98013. this.motorImpulse2 = 0;
  98014. this.limitImpulse3 = 0;
  98015. this.motorImpulse3 = 0;
  98016. this.cfm1 = 0;// Constraint Force Mixing
  98017. this.cfm2 = 0;
  98018. this.cfm3 = 0;
  98019. this.weight = -1;
  98020. }
  98021. OIMO.Translational3Constraint.prototype = {
  98022. constructor: OIMO.Translational3Constraint,
  98023. preSolve: function (timeStep, invTimeStep) {
  98024. this.ax1 = this.limitMotor1.axis.x;
  98025. this.ay1 = this.limitMotor1.axis.y;
  98026. this.az1 = this.limitMotor1.axis.z;
  98027. this.ax2 = this.limitMotor2.axis.x;
  98028. this.ay2 = this.limitMotor2.axis.y;
  98029. this.az2 = this.limitMotor2.axis.z;
  98030. this.ax3 = this.limitMotor3.axis.x;
  98031. this.ay3 = this.limitMotor3.axis.y;
  98032. this.az3 = this.limitMotor3.axis.z;
  98033. this.lowerLimit1 = this.limitMotor1.lowerLimit;
  98034. this.upperLimit1 = this.limitMotor1.upperLimit;
  98035. this.motorSpeed1 = this.limitMotor1.motorSpeed;
  98036. this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
  98037. this.enableMotor1 = this.maxMotorForce1 > 0;
  98038. this.lowerLimit2 = this.limitMotor2.lowerLimit;
  98039. this.upperLimit2 = this.limitMotor2.upperLimit;
  98040. this.motorSpeed2 = this.limitMotor2.motorSpeed;
  98041. this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
  98042. this.enableMotor2 = this.maxMotorForce2 > 0;
  98043. this.lowerLimit3 = this.limitMotor3.lowerLimit;
  98044. this.upperLimit3 = this.limitMotor3.upperLimit;
  98045. this.motorSpeed3 = this.limitMotor3.motorSpeed;
  98046. this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
  98047. this.enableMotor3 = this.maxMotorForce3 > 0;
  98048. this.m1 = this.b1.inverseMass;
  98049. this.m2 = this.b2.inverseMass;
  98050. var ti1 = this.i1.elements;
  98051. var ti2 = this.i2.elements;
  98052. this.i1e00 = ti1[0];
  98053. this.i1e01 = ti1[1];
  98054. this.i1e02 = ti1[2];
  98055. this.i1e10 = ti1[3];
  98056. this.i1e11 = ti1[4];
  98057. this.i1e12 = ti1[5];
  98058. this.i1e20 = ti1[6];
  98059. this.i1e21 = ti1[7];
  98060. this.i1e22 = ti1[8];
  98061. this.i2e00 = ti2[0];
  98062. this.i2e01 = ti2[1];
  98063. this.i2e02 = ti2[2];
  98064. this.i2e10 = ti2[3];
  98065. this.i2e11 = ti2[4];
  98066. this.i2e12 = ti2[5];
  98067. this.i2e20 = ti2[6];
  98068. this.i2e21 = ti2[7];
  98069. this.i2e22 = ti2[8];
  98070. var dx = this.p2.x - this.p1.x;
  98071. var dy = this.p2.y - this.p1.y;
  98072. var dz = this.p2.z - this.p1.z;
  98073. var d1 = dx * this.ax1 + dy * this.ay1 + dz * this.az1;
  98074. var d2 = dx * this.ax2 + dy * this.ay2 + dz * this.az2;
  98075. var d3 = dx * this.ax3 + dy * this.ay3 + dz * this.az3;
  98076. var frequency1 = this.limitMotor1.frequency;
  98077. var frequency2 = this.limitMotor2.frequency;
  98078. var frequency3 = this.limitMotor3.frequency;
  98079. var enableSpring1 = frequency1 > 0;
  98080. var enableSpring2 = frequency2 > 0;
  98081. var enableSpring3 = frequency3 > 0;
  98082. var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
  98083. var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
  98084. var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
  98085. // for stability
  98086. if (enableSpring1 && d1 > 20 || d1 < -20) {
  98087. enableSpring1 = false;
  98088. }
  98089. if (enableSpring2 && d2 > 20 || d2 < -20) {
  98090. enableSpring2 = false;
  98091. }
  98092. if (enableSpring3 && d3 > 20 || d3 < -20) {
  98093. enableSpring3 = false;
  98094. }
  98095. if (enableLimit1) {
  98096. if (this.lowerLimit1 == this.upperLimit1) {
  98097. if (this.limitState1 != 0) {
  98098. this.limitState1 = 0;
  98099. this.limitImpulse1 = 0;
  98100. }
  98101. this.limitVelocity1 = this.lowerLimit1 - d1;
  98102. if (!enableSpring1) d1 = this.lowerLimit1;
  98103. } else if (d1 < this.lowerLimit1) {
  98104. if (this.limitState1 != -1) {
  98105. this.limitState1 = -1;
  98106. this.limitImpulse1 = 0;
  98107. }
  98108. this.limitVelocity1 = this.lowerLimit1 - d1;
  98109. if (!enableSpring1) d1 = this.lowerLimit1;
  98110. } else if (d1 > this.upperLimit1) {
  98111. if (this.limitState1 != 1) {
  98112. this.limitState1 = 1;
  98113. this.limitImpulse1 = 0;
  98114. }
  98115. this.limitVelocity1 = this.upperLimit1 - d1;
  98116. if (!enableSpring1) d1 = this.upperLimit1;
  98117. } else {
  98118. this.limitState1 = 2;
  98119. this.limitImpulse1 = 0;
  98120. this.limitVelocity1 = 0;
  98121. }
  98122. if (!enableSpring1) {
  98123. if (this.limitVelocity1 > 0.005) this.limitVelocity1 -= 0.005;
  98124. else if (this.limitVelocity1 < -0.005) this.limitVelocity1 += 0.005;
  98125. else this.limitVelocity1 = 0;
  98126. }
  98127. } else {
  98128. this.limitState1 = 2;
  98129. this.limitImpulse1 = 0;
  98130. }
  98131. if (enableLimit2) {
  98132. if (this.lowerLimit2 == this.upperLimit2) {
  98133. if (this.limitState2 != 0) {
  98134. this.limitState2 = 0;
  98135. this.limitImpulse2 = 0;
  98136. }
  98137. this.limitVelocity2 = this.lowerLimit2 - d2;
  98138. if (!enableSpring2) d2 = this.lowerLimit2;
  98139. } else if (d2 < this.lowerLimit2) {
  98140. if (this.limitState2 != -1) {
  98141. this.limitState2 = -1;
  98142. this.limitImpulse2 = 0;
  98143. }
  98144. this.limitVelocity2 = this.lowerLimit2 - d2;
  98145. if (!enableSpring2) d2 = this.lowerLimit2;
  98146. } else if (d2 > this.upperLimit2) {
  98147. if (this.limitState2 != 1) {
  98148. this.limitState2 = 1;
  98149. this.limitImpulse2 = 0;
  98150. }
  98151. this.limitVelocity2 = this.upperLimit2 - d2;
  98152. if (!enableSpring2) d2 = this.upperLimit2;
  98153. } else {
  98154. this.limitState2 = 2;
  98155. this.limitImpulse2 = 0;
  98156. this.limitVelocity2 = 0;
  98157. }
  98158. if (!enableSpring2) {
  98159. if (this.limitVelocity2 > 0.005) this.limitVelocity2 -= 0.005;
  98160. else if (this.limitVelocity2 < -0.005) this.limitVelocity2 += 0.005;
  98161. else this.limitVelocity2 = 0;
  98162. }
  98163. } else {
  98164. this.limitState2 = 2;
  98165. this.limitImpulse2 = 0;
  98166. }
  98167. if (enableLimit3) {
  98168. if (this.lowerLimit3 == this.upperLimit3) {
  98169. if (this.limitState3 != 0) {
  98170. this.limitState3 = 0;
  98171. this.limitImpulse3 = 0;
  98172. }
  98173. this.limitVelocity3 = this.lowerLimit3 - d3;
  98174. if (!enableSpring3) d3 = this.lowerLimit3;
  98175. } else if (d3 < this.lowerLimit3) {
  98176. if (this.limitState3 != -1) {
  98177. this.limitState3 = -1;
  98178. this.limitImpulse3 = 0;
  98179. }
  98180. this.limitVelocity3 = this.lowerLimit3 - d3;
  98181. if (!enableSpring3) d3 = this.lowerLimit3;
  98182. } else if (d3 > this.upperLimit3) {
  98183. if (this.limitState3 != 1) {
  98184. this.limitState3 = 1;
  98185. this.limitImpulse3 = 0;
  98186. }
  98187. this.limitVelocity3 = this.upperLimit3 - d3;
  98188. if (!enableSpring3) d3 = this.upperLimit3;
  98189. } else {
  98190. this.limitState3 = 2;
  98191. this.limitImpulse3 = 0;
  98192. this.limitVelocity3 = 0;
  98193. }
  98194. if (!enableSpring3) {
  98195. if (this.limitVelocity3 > 0.005) this.limitVelocity3 -= 0.005;
  98196. else if (this.limitVelocity3 < -0.005) this.limitVelocity3 += 0.005;
  98197. else this.limitVelocity3 = 0;
  98198. }
  98199. } else {
  98200. this.limitState3 = 2;
  98201. this.limitImpulse3 = 0;
  98202. }
  98203. if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
  98204. this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
  98205. } else {
  98206. this.motorImpulse1 = 0;
  98207. this.maxMotorImpulse1 = 0;
  98208. }
  98209. if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
  98210. this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
  98211. } else {
  98212. this.motorImpulse2 = 0;
  98213. this.maxMotorImpulse2 = 0;
  98214. }
  98215. if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
  98216. this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
  98217. } else {
  98218. this.motorImpulse3 = 0;
  98219. this.maxMotorImpulse3 = 0;
  98220. }
  98221. var rdx = d1 * this.ax1 + d2 * this.ax2 + d3 * this.ax2;
  98222. var rdy = d1 * this.ay1 + d2 * this.ay2 + d3 * this.ay2;
  98223. var rdz = d1 * this.az1 + d2 * this.az2 + d3 * this.az2;
  98224. var w1 = this.m2 / (this.m1 + this.m2);
  98225. if (this.weight >= 0) w1 = this.weight; // use given weight
  98226. var w2 = 1 - w1;
  98227. this.r1x = this.r1.x + rdx * w1;
  98228. this.r1y = this.r1.y + rdy * w1;
  98229. this.r1z = this.r1.z + rdz * w1;
  98230. this.r2x = this.r2.x - rdx * w2;
  98231. this.r2y = this.r2.y - rdy * w2;
  98232. this.r2z = this.r2.z - rdz * w2;
  98233. // build jacobians
  98234. this.t1x1 = this.r1y * this.az1 - this.r1z * this.ay1;
  98235. this.t1y1 = this.r1z * this.ax1 - this.r1x * this.az1;
  98236. this.t1z1 = this.r1x * this.ay1 - this.r1y * this.ax1;
  98237. this.t2x1 = this.r2y * this.az1 - this.r2z * this.ay1;
  98238. this.t2y1 = this.r2z * this.ax1 - this.r2x * this.az1;
  98239. this.t2z1 = this.r2x * this.ay1 - this.r2y * this.ax1;
  98240. this.l1x1 = this.ax1 * this.m1;
  98241. this.l1y1 = this.ay1 * this.m1;
  98242. this.l1z1 = this.az1 * this.m1;
  98243. this.l2x1 = this.ax1 * this.m2;
  98244. this.l2y1 = this.ay1 * this.m2;
  98245. this.l2z1 = this.az1 * this.m2;
  98246. this.a1x1 = this.t1x1 * this.i1e00 + this.t1y1 * this.i1e01 + this.t1z1 * this.i1e02;
  98247. this.a1y1 = this.t1x1 * this.i1e10 + this.t1y1 * this.i1e11 + this.t1z1 * this.i1e12;
  98248. this.a1z1 = this.t1x1 * this.i1e20 + this.t1y1 * this.i1e21 + this.t1z1 * this.i1e22;
  98249. this.a2x1 = this.t2x1 * this.i2e00 + this.t2y1 * this.i2e01 + this.t2z1 * this.i2e02;
  98250. this.a2y1 = this.t2x1 * this.i2e10 + this.t2y1 * this.i2e11 + this.t2z1 * this.i2e12;
  98251. this.a2z1 = this.t2x1 * this.i2e20 + this.t2y1 * this.i2e21 + this.t2z1 * this.i2e22;
  98252. this.t1x2 = this.r1y * this.az2 - this.r1z * this.ay2;
  98253. this.t1y2 = this.r1z * this.ax2 - this.r1x * this.az2;
  98254. this.t1z2 = this.r1x * this.ay2 - this.r1y * this.ax2;
  98255. this.t2x2 = this.r2y * this.az2 - this.r2z * this.ay2;
  98256. this.t2y2 = this.r2z * this.ax2 - this.r2x * this.az2;
  98257. this.t2z2 = this.r2x * this.ay2 - this.r2y * this.ax2;
  98258. this.l1x2 = this.ax2 * this.m1;
  98259. this.l1y2 = this.ay2 * this.m1;
  98260. this.l1z2 = this.az2 * this.m1;
  98261. this.l2x2 = this.ax2 * this.m2;
  98262. this.l2y2 = this.ay2 * this.m2;
  98263. this.l2z2 = this.az2 * this.m2;
  98264. this.a1x2 = this.t1x2 * this.i1e00 + this.t1y2 * this.i1e01 + this.t1z2 * this.i1e02;
  98265. this.a1y2 = this.t1x2 * this.i1e10 + this.t1y2 * this.i1e11 + this.t1z2 * this.i1e12;
  98266. this.a1z2 = this.t1x2 * this.i1e20 + this.t1y2 * this.i1e21 + this.t1z2 * this.i1e22;
  98267. this.a2x2 = this.t2x2 * this.i2e00 + this.t2y2 * this.i2e01 + this.t2z2 * this.i2e02;
  98268. this.a2y2 = this.t2x2 * this.i2e10 + this.t2y2 * this.i2e11 + this.t2z2 * this.i2e12;
  98269. this.a2z2 = this.t2x2 * this.i2e20 + this.t2y2 * this.i2e21 + this.t2z2 * this.i2e22;
  98270. this.t1x3 = this.r1y * this.az3 - this.r1z * this.ay3;
  98271. this.t1y3 = this.r1z * this.ax3 - this.r1x * this.az3;
  98272. this.t1z3 = this.r1x * this.ay3 - this.r1y * this.ax3;
  98273. this.t2x3 = this.r2y * this.az3 - this.r2z * this.ay3;
  98274. this.t2y3 = this.r2z * this.ax3 - this.r2x * this.az3;
  98275. this.t2z3 = this.r2x * this.ay3 - this.r2y * this.ax3;
  98276. this.l1x3 = this.ax3 * this.m1;
  98277. this.l1y3 = this.ay3 * this.m1;
  98278. this.l1z3 = this.az3 * this.m1;
  98279. this.l2x3 = this.ax3 * this.m2;
  98280. this.l2y3 = this.ay3 * this.m2;
  98281. this.l2z3 = this.az3 * this.m2;
  98282. this.a1x3 = this.t1x3 * this.i1e00 + this.t1y3 * this.i1e01 + this.t1z3 * this.i1e02;
  98283. this.a1y3 = this.t1x3 * this.i1e10 + this.t1y3 * this.i1e11 + this.t1z3 * this.i1e12;
  98284. this.a1z3 = this.t1x3 * this.i1e20 + this.t1y3 * this.i1e21 + this.t1z3 * this.i1e22;
  98285. this.a2x3 = this.t2x3 * this.i2e00 + this.t2y3 * this.i2e01 + this.t2z3 * this.i2e02;
  98286. this.a2y3 = this.t2x3 * this.i2e10 + this.t2y3 * this.i2e11 + this.t2z3 * this.i2e12;
  98287. this.a2z3 = this.t2x3 * this.i2e20 + this.t2y3 * this.i2e21 + this.t2z3 * this.i2e22;
  98288. // build an impulse matrix
  98289. var m12 = this.m1 + this.m2;
  98290. this.k00 = (this.ax1 * this.ax1 + this.ay1 * this.ay1 + this.az1 * this.az1) * m12;
  98291. this.k01 = (this.ax1 * this.ax2 + this.ay1 * this.ay2 + this.az1 * this.az2) * m12;
  98292. this.k02 = (this.ax1 * this.ax3 + this.ay1 * this.ay3 + this.az1 * this.az3) * m12;
  98293. this.k10 = (this.ax2 * this.ax1 + this.ay2 * this.ay1 + this.az2 * this.az1) * m12;
  98294. this.k11 = (this.ax2 * this.ax2 + this.ay2 * this.ay2 + this.az2 * this.az2) * m12;
  98295. this.k12 = (this.ax2 * this.ax3 + this.ay2 * this.ay3 + this.az2 * this.az3) * m12;
  98296. this.k20 = (this.ax3 * this.ax1 + this.ay3 * this.ay1 + this.az3 * this.az1) * m12;
  98297. this.k21 = (this.ax3 * this.ax2 + this.ay3 * this.ay2 + this.az3 * this.az2) * m12;
  98298. this.k22 = (this.ax3 * this.ax3 + this.ay3 * this.ay3 + this.az3 * this.az3) * m12;
  98299. this.k00 += this.t1x1 * this.a1x1 + this.t1y1 * this.a1y1 + this.t1z1 * this.a1z1;
  98300. this.k01 += this.t1x1 * this.a1x2 + this.t1y1 * this.a1y2 + this.t1z1 * this.a1z2;
  98301. this.k02 += this.t1x1 * this.a1x3 + this.t1y1 * this.a1y3 + this.t1z1 * this.a1z3;
  98302. this.k10 += this.t1x2 * this.a1x1 + this.t1y2 * this.a1y1 + this.t1z2 * this.a1z1;
  98303. this.k11 += this.t1x2 * this.a1x2 + this.t1y2 * this.a1y2 + this.t1z2 * this.a1z2;
  98304. this.k12 += this.t1x2 * this.a1x3 + this.t1y2 * this.a1y3 + this.t1z2 * this.a1z3;
  98305. this.k20 += this.t1x3 * this.a1x1 + this.t1y3 * this.a1y1 + this.t1z3 * this.a1z1;
  98306. this.k21 += this.t1x3 * this.a1x2 + this.t1y3 * this.a1y2 + this.t1z3 * this.a1z2;
  98307. this.k22 += this.t1x3 * this.a1x3 + this.t1y3 * this.a1y3 + this.t1z3 * this.a1z3;
  98308. this.k00 += this.t2x1 * this.a2x1 + this.t2y1 * this.a2y1 + this.t2z1 * this.a2z1;
  98309. this.k01 += this.t2x1 * this.a2x2 + this.t2y1 * this.a2y2 + this.t2z1 * this.a2z2;
  98310. this.k02 += this.t2x1 * this.a2x3 + this.t2y1 * this.a2y3 + this.t2z1 * this.a2z3;
  98311. this.k10 += this.t2x2 * this.a2x1 + this.t2y2 * this.a2y1 + this.t2z2 * this.a2z1;
  98312. this.k11 += this.t2x2 * this.a2x2 + this.t2y2 * this.a2y2 + this.t2z2 * this.a2z2;
  98313. this.k12 += this.t2x2 * this.a2x3 + this.t2y2 * this.a2y3 + this.t2z2 * this.a2z3;
  98314. this.k20 += this.t2x3 * this.a2x1 + this.t2y3 * this.a2y1 + this.t2z3 * this.a2z1;
  98315. this.k21 += this.t2x3 * this.a2x2 + this.t2y3 * this.a2y2 + this.t2z3 * this.a2z2;
  98316. this.k22 += this.t2x3 * this.a2x3 + this.t2y3 * this.a2y3 + this.t2z3 * this.a2z3;
  98317. this.kv00 = this.k00;
  98318. this.kv11 = this.k11;
  98319. this.kv22 = this.k22;
  98320. this.dv00 = 1 / this.kv00;
  98321. this.dv11 = 1 / this.kv11;
  98322. this.dv22 = 1 / this.kv22;
  98323. if (enableSpring1 && this.limitState1 != 2) {
  98324. var omega = 6.2831853 * frequency1;
  98325. var k = omega * omega * timeStep;
  98326. var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
  98327. this.cfm1 = this.kv00 * dmp;
  98328. this.limitVelocity1 *= k * dmp;
  98329. } else {
  98330. this.cfm1 = 0;
  98331. this.limitVelocity1 *= invTimeStep * 0.05;
  98332. }
  98333. if (enableSpring2 && this.limitState2 != 2) {
  98334. omega = 6.2831853 * frequency2;
  98335. k = omega * omega * timeStep;
  98336. dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
  98337. this.cfm2 = this.kv11 * dmp;
  98338. this.limitVelocity2 *= k * dmp;
  98339. } else {
  98340. this.cfm2 = 0;
  98341. this.limitVelocity2 *= invTimeStep * 0.05;
  98342. }
  98343. if (enableSpring3 && this.limitState3 != 2) {
  98344. omega = 6.2831853 * frequency3;
  98345. k = omega * omega * timeStep;
  98346. dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
  98347. this.cfm3 = this.kv22 * dmp;
  98348. this.limitVelocity3 *= k * dmp;
  98349. } else {
  98350. this.cfm3 = 0;
  98351. this.limitVelocity3 *= invTimeStep * 0.05;
  98352. }
  98353. this.k00 += this.cfm1;
  98354. this.k11 += this.cfm2;
  98355. this.k22 += this.cfm3;
  98356. var inv = 1 / (
  98357. this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
  98358. this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
  98359. this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
  98360. );
  98361. this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
  98362. this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
  98363. this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
  98364. this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
  98365. this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
  98366. this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
  98367. this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
  98368. this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
  98369. this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
  98370. // warm starting
  98371. var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
  98372. var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
  98373. var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
  98374. this.l1.x += totalImpulse1 * this.l1x1 + totalImpulse2 * this.l1x2 + totalImpulse3 * this.l1x3;
  98375. this.l1.y += totalImpulse1 * this.l1y1 + totalImpulse2 * this.l1y2 + totalImpulse3 * this.l1y3;
  98376. this.l1.z += totalImpulse1 * this.l1z1 + totalImpulse2 * this.l1z2 + totalImpulse3 * this.l1z3;
  98377. this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
  98378. this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
  98379. this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
  98380. this.l2.x -= totalImpulse1 * this.l2x1 + totalImpulse2 * this.l2x2 + totalImpulse3 * this.l2x3;
  98381. this.l2.y -= totalImpulse1 * this.l2y1 + totalImpulse2 * this.l2y2 + totalImpulse3 * this.l2y3;
  98382. this.l2.z -= totalImpulse1 * this.l2z1 + totalImpulse2 * this.l2z2 + totalImpulse3 * this.l2z3;
  98383. this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
  98384. this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
  98385. this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
  98386. },
  98387. solve: function () {
  98388. 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;
  98389. 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;
  98390. 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;
  98391. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
  98392. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  98393. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
  98394. var oldMotorImpulse1 = this.motorImpulse1;
  98395. var oldMotorImpulse2 = this.motorImpulse2;
  98396. var oldMotorImpulse3 = this.motorImpulse3;
  98397. var dMotorImpulse1 = 0;
  98398. var dMotorImpulse2 = 0;
  98399. var dMotorImpulse3 = 0;
  98400. if (this.enableMotor1) {
  98401. dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
  98402. this.motorImpulse1 += dMotorImpulse1;
  98403. if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
  98404. this.motorImpulse1 = this.maxMotorImpulse1;
  98405. } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
  98406. this.motorImpulse1 = -this.maxMotorImpulse1;
  98407. }
  98408. dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
  98409. }
  98410. if (this.enableMotor2) {
  98411. dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
  98412. this.motorImpulse2 += dMotorImpulse2;
  98413. if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
  98414. this.motorImpulse2 = this.maxMotorImpulse2;
  98415. } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
  98416. this.motorImpulse2 = -this.maxMotorImpulse2;
  98417. }
  98418. dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
  98419. }
  98420. if (this.enableMotor3) {
  98421. dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
  98422. this.motorImpulse3 += dMotorImpulse3;
  98423. if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
  98424. this.motorImpulse3 = this.maxMotorImpulse3;
  98425. } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
  98426. this.motorImpulse3 = -this.maxMotorImpulse3;
  98427. }
  98428. dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
  98429. }
  98430. // apply motor impulse to relative velocity
  98431. rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
  98432. rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
  98433. rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
  98434. // subtract target velocity and applied impulse
  98435. rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
  98436. rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
  98437. rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
  98438. var oldLimitImpulse1 = this.limitImpulse1;
  98439. var oldLimitImpulse2 = this.limitImpulse2;
  98440. var oldLimitImpulse3 = this.limitImpulse3;
  98441. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  98442. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  98443. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  98444. this.limitImpulse1 += dLimitImpulse1;
  98445. this.limitImpulse2 += dLimitImpulse2;
  98446. this.limitImpulse3 += dLimitImpulse3;
  98447. // clamp
  98448. var clampState = 0;
  98449. if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
  98450. dLimitImpulse1 = -oldLimitImpulse1;
  98451. rvn2 += dLimitImpulse1 * this.k10;
  98452. rvn3 += dLimitImpulse1 * this.k20;
  98453. clampState |= 1;
  98454. }
  98455. if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
  98456. dLimitImpulse2 = -oldLimitImpulse2;
  98457. rvn1 += dLimitImpulse2 * this.k01;
  98458. rvn3 += dLimitImpulse2 * this.k21;
  98459. clampState |= 2;
  98460. }
  98461. if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
  98462. dLimitImpulse3 = -oldLimitImpulse3;
  98463. rvn1 += dLimitImpulse3 * this.k02;
  98464. rvn2 += dLimitImpulse3 * this.k12;
  98465. clampState |= 4;
  98466. }
  98467. // update un-clamped impulse
  98468. // TODO: isolate division
  98469. var det;
  98470. switch (clampState) {
  98471. case 1:// update 2 3
  98472. det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
  98473. dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
  98474. dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
  98475. break;
  98476. case 2:// update 1 3
  98477. det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
  98478. dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
  98479. dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
  98480. break;
  98481. case 3:// update 3
  98482. dLimitImpulse3 = rvn3 / this.k22;
  98483. break;
  98484. case 4:// update 1 2
  98485. det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
  98486. dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
  98487. dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
  98488. break;
  98489. case 5:// update 2
  98490. dLimitImpulse2 = rvn2 / this.k11;
  98491. break;
  98492. case 6:// update 1
  98493. dLimitImpulse1 = rvn1 / this.k00;
  98494. break;
  98495. }
  98496. this.limitImpulse1 = oldLimitImpulse1 + dLimitImpulse1;
  98497. this.limitImpulse2 = oldLimitImpulse2 + dLimitImpulse2;
  98498. this.limitImpulse3 = oldLimitImpulse3 + dLimitImpulse3;
  98499. var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
  98500. var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
  98501. var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
  98502. // apply impulse
  98503. this.l1.x += dImpulse1 * this.l1x1 + dImpulse2 * this.l1x2 + dImpulse3 * this.l1x3;
  98504. this.l1.y += dImpulse1 * this.l1y1 + dImpulse2 * this.l1y2 + dImpulse3 * this.l1y3;
  98505. this.l1.z += dImpulse1 * this.l1z1 + dImpulse2 * this.l1z2 + dImpulse3 * this.l1z3;
  98506. this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
  98507. this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
  98508. this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
  98509. this.l2.x -= dImpulse1 * this.l2x1 + dImpulse2 * this.l2x2 + dImpulse3 * this.l2x3;
  98510. this.l2.y -= dImpulse1 * this.l2y1 + dImpulse2 * this.l2y2 + dImpulse3 * this.l2y3;
  98511. this.l2.z -= dImpulse1 * this.l2z1 + dImpulse2 * this.l2z2 + dImpulse3 * this.l2z3;
  98512. this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
  98513. this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
  98514. this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
  98515. }
  98516. }
  98517. /**
  98518. * A translational constraint for various joints.
  98519. * @author saharan
  98520. */
  98521. OIMO.TranslationalConstraint = function (joint, limitMotor) {
  98522. this.cfm = NaN;
  98523. this.m1 = NaN;
  98524. this.m2 = NaN;
  98525. this.i1e00 = NaN;
  98526. this.i1e01 = NaN;
  98527. this.i1e02 = NaN;
  98528. this.i1e10 = NaN;
  98529. this.i1e11 = NaN;
  98530. this.i1e12 = NaN;
  98531. this.i1e20 = NaN;
  98532. this.i1e21 = NaN;
  98533. this.i1e22 = NaN;
  98534. this.i2e00 = NaN;
  98535. this.i2e01 = NaN;
  98536. this.i2e02 = NaN;
  98537. this.i2e10 = NaN;
  98538. this.i2e11 = NaN;
  98539. this.i2e12 = NaN;
  98540. this.i2e20 = NaN;
  98541. this.i2e21 = NaN;
  98542. this.i2e22 = NaN;
  98543. this.motorDenom = NaN;
  98544. this.invMotorDenom = NaN;
  98545. this.invDenom = NaN;
  98546. this.ax = NaN;
  98547. this.ay = NaN;
  98548. this.az = NaN;
  98549. this.r1x = NaN;
  98550. this.r1y = NaN;
  98551. this.r1z = NaN;
  98552. this.r2x = NaN;
  98553. this.r2y = NaN;
  98554. this.r2z = NaN;
  98555. this.t1x = NaN;
  98556. this.t1y = NaN;
  98557. this.t1z = NaN;
  98558. this.t2x = NaN;
  98559. this.t2y = NaN;
  98560. this.t2z = NaN;
  98561. this.l1x = NaN;
  98562. this.l1y = NaN;
  98563. this.l1z = NaN;
  98564. this.l2x = NaN;
  98565. this.l2y = NaN;
  98566. this.l2z = NaN;
  98567. this.a1x = NaN;
  98568. this.a1y = NaN;
  98569. this.a1z = NaN;
  98570. this.a2x = NaN;
  98571. this.a2y = NaN;
  98572. this.a2z = NaN;
  98573. this.lowerLimit = NaN;
  98574. this.upperLimit = NaN;
  98575. this.limitVelocity = NaN;
  98576. this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  98577. this.enableMotor = false;
  98578. this.motorSpeed = NaN;
  98579. this.maxMotorForce = NaN;
  98580. this.maxMotorImpulse = NaN;
  98581. this.limitMotor = limitMotor;
  98582. this.b1 = joint.body1;
  98583. this.b2 = joint.body2;
  98584. this.p1 = joint.anchorPoint1;
  98585. this.p2 = joint.anchorPoint2;
  98586. this.r1 = joint.relativeAnchorPoint1;
  98587. this.r2 = joint.relativeAnchorPoint2;
  98588. this.l1 = this.b1.linearVelocity;
  98589. this.l2 = this.b2.linearVelocity;
  98590. this.a1 = this.b1.angularVelocity;
  98591. this.a2 = this.b2.angularVelocity;
  98592. this.i1 = this.b1.inverseInertia;
  98593. this.i2 = this.b2.inverseInertia;
  98594. this.limitImpulse = 0;
  98595. this.motorImpulse = 0;
  98596. }
  98597. OIMO.TranslationalConstraint.prototype = {
  98598. constructor: OIMO.TranslationalConstraint,
  98599. preSolve: function (timeStep, invTimeStep) {
  98600. this.ax = this.limitMotor.axis.x;
  98601. this.ay = this.limitMotor.axis.y;
  98602. this.az = this.limitMotor.axis.z;
  98603. this.lowerLimit = this.limitMotor.lowerLimit;
  98604. this.upperLimit = this.limitMotor.upperLimit;
  98605. this.motorSpeed = this.limitMotor.motorSpeed;
  98606. this.maxMotorForce = this.limitMotor.maxMotorForce;
  98607. this.enableMotor = this.maxMotorForce > 0;
  98608. this.m1 = this.b1.inverseMass;
  98609. this.m2 = this.b2.inverseMass;
  98610. var ti1 = this.i1.elements;
  98611. var ti2 = this.i2.elements;
  98612. this.i1e00 = ti1[0];
  98613. this.i1e01 = ti1[1];
  98614. this.i1e02 = ti1[2];
  98615. this.i1e10 = ti1[3];
  98616. this.i1e11 = ti1[4];
  98617. this.i1e12 = ti1[5];
  98618. this.i1e20 = ti1[6];
  98619. this.i1e21 = ti1[7];
  98620. this.i1e22 = ti1[8];
  98621. this.i2e00 = ti2[0];
  98622. this.i2e01 = ti2[1];
  98623. this.i2e02 = ti2[2];
  98624. this.i2e10 = ti2[3];
  98625. this.i2e11 = ti2[4];
  98626. this.i2e12 = ti2[5];
  98627. this.i2e20 = ti2[6];
  98628. this.i2e21 = ti2[7];
  98629. this.i2e22 = ti2[8];
  98630. var dx = this.p2.x - this.p1.x;
  98631. var dy = this.p2.y - this.p1.y;
  98632. var dz = this.p2.z - this.p1.z;
  98633. var d = dx * this.ax + dy * this.ay + dz * this.az;
  98634. var frequency = this.limitMotor.frequency;
  98635. var enableSpring = frequency > 0;
  98636. var enableLimit = this.lowerLimit <= this.upperLimit;
  98637. if (enableSpring && d > 20 || d < -20) {
  98638. enableSpring = false;
  98639. }
  98640. if (enableLimit) {
  98641. if (this.lowerLimit == this.upperLimit) {
  98642. if (this.limitState != 0) {
  98643. this.limitState = 0;
  98644. this.limitImpulse = 0;
  98645. }
  98646. this.limitVelocity = this.lowerLimit - d;
  98647. if (!enableSpring) d = this.lowerLimit;
  98648. } else if (d < this.lowerLimit) {
  98649. if (this.limitState != -1) {
  98650. this.limitState = -1;
  98651. this.limitImpulse = 0;
  98652. }
  98653. this.limitVelocity = this.lowerLimit - d;
  98654. if (!enableSpring) d = this.lowerLimit;
  98655. } else if (d > this.upperLimit) {
  98656. if (this.limitState != 1) {
  98657. this.limitState = 1;
  98658. this.limitImpulse = 0;
  98659. }
  98660. this.limitVelocity = this.upperLimit - d;
  98661. if (!enableSpring) d = this.upperLimit;
  98662. } else {
  98663. this.limitState = 2;
  98664. this.limitImpulse = 0;
  98665. this.limitVelocity = 0;
  98666. }
  98667. if (!enableSpring) {
  98668. if (this.limitVelocity > 0.005) this.limitVelocity -= 0.005;
  98669. else if (this.limitVelocity < -0.005) this.limitVelocity += 0.005;
  98670. else this.limitVelocity = 0;
  98671. }
  98672. } else {
  98673. this.limitState = 2;
  98674. this.limitImpulse = 0;
  98675. }
  98676. if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
  98677. this.maxMotorImpulse = this.maxMotorForce * timeStep;
  98678. } else {
  98679. this.motorImpulse = 0;
  98680. this.maxMotorImpulse = 0;
  98681. }
  98682. var rdx = d * this.ax;
  98683. var rdy = d * this.ay;
  98684. var rdz = d * this.az;
  98685. var w1 = this.m1 / (this.m1 + this.m2);
  98686. var w2 = 1 - w1;
  98687. this.r1x = this.r1.x + rdx * w1;
  98688. this.r1y = this.r1.y + rdy * w1;
  98689. this.r1z = this.r1.z + rdz * w1;
  98690. this.r2x = this.r2.x - rdx * w2;
  98691. this.r2y = this.r2.y - rdy * w2;
  98692. this.r2z = this.r2.z - rdz * w2;
  98693. this.t1x = this.r1y * this.az - this.r1z * this.ay;
  98694. this.t1y = this.r1z * this.ax - this.r1x * this.az;
  98695. this.t1z = this.r1x * this.ay - this.r1y * this.ax;
  98696. this.t2x = this.r2y * this.az - this.r2z * this.ay;
  98697. this.t2y = this.r2z * this.ax - this.r2x * this.az;
  98698. this.t2z = this.r2x * this.ay - this.r2y * this.ax;
  98699. this.l1x = this.ax * this.m1;
  98700. this.l1y = this.ay * this.m1;
  98701. this.l1z = this.az * this.m1;
  98702. this.l2x = this.ax * this.m2;
  98703. this.l2y = this.ay * this.m2;
  98704. this.l2z = this.az * this.m2;
  98705. this.a1x = this.t1x * this.i1e00 + this.t1y * this.i1e01 + this.t1z * this.i1e02;
  98706. this.a1y = this.t1x * this.i1e10 + this.t1y * this.i1e11 + this.t1z * this.i1e12;
  98707. this.a1z = this.t1x * this.i1e20 + this.t1y * this.i1e21 + this.t1z * this.i1e22;
  98708. this.a2x = this.t2x * this.i2e00 + this.t2y * this.i2e01 + this.t2z * this.i2e02;
  98709. this.a2y = this.t2x * this.i2e10 + this.t2y * this.i2e11 + this.t2z * this.i2e12;
  98710. this.a2z = this.t2x * this.i2e20 + this.t2y * this.i2e21 + this.t2z * this.i2e22;
  98711. this.motorDenom =
  98712. this.m1 + this.m2 +
  98713. this.ax * (this.a1y * this.r1z - this.a1z * this.r1y + this.a2y * this.r2z - this.a2z * this.r2y) +
  98714. this.ay * (this.a1z * this.r1x - this.a1x * this.r1z + this.a2z * this.r2x - this.a2x * this.r2z) +
  98715. this.az * (this.a1x * this.r1y - this.a1y * this.r1x + this.a2x * this.r2y - this.a2y * this.r2x);
  98716. this.invMotorDenom = 1 / this.motorDenom;
  98717. if (enableSpring && this.limitState != 2) {
  98718. var omega = 6.2831853 * frequency;
  98719. var k = omega * omega * timeStep;
  98720. var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
  98721. this.cfm = this.motorDenom * dmp;
  98722. this.limitVelocity *= k * dmp;
  98723. } else {
  98724. this.cfm = 0;
  98725. this.limitVelocity *= invTimeStep * 0.05;
  98726. }
  98727. this.invDenom = 1 / (this.motorDenom + this.cfm);
  98728. var totalImpulse = this.limitImpulse + this.motorImpulse;
  98729. this.l1.x += totalImpulse * this.l1x;
  98730. this.l1.y += totalImpulse * this.l1y;
  98731. this.l1.z += totalImpulse * this.l1z;
  98732. this.a1.x += totalImpulse * this.a1x;
  98733. this.a1.y += totalImpulse * this.a1y;
  98734. this.a1.z += totalImpulse * this.a1z;
  98735. this.l2.x -= totalImpulse * this.l2x;
  98736. this.l2.y -= totalImpulse * this.l2y;
  98737. this.l2.z -= totalImpulse * this.l2z;
  98738. this.a2.x -= totalImpulse * this.a2x;
  98739. this.a2.y -= totalImpulse * this.a2y;
  98740. this.a2.z -= totalImpulse * this.a2z;
  98741. },
  98742. solve: function () {
  98743. var rvn =
  98744. this.ax * (this.l2.x - this.l1.x) + this.ay * (this.l2.y - this.l1.y) + this.az * (this.l2.z - this.l1.z) +
  98745. 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;
  98746. // motor part
  98747. var newMotorImpulse;
  98748. if (this.enableMotor) {
  98749. newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
  98750. var oldMotorImpulse = this.motorImpulse;
  98751. this.motorImpulse += newMotorImpulse;
  98752. if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
  98753. else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
  98754. newMotorImpulse = this.motorImpulse - oldMotorImpulse;
  98755. rvn -= newMotorImpulse * this.motorDenom;
  98756. } else newMotorImpulse = 0;
  98757. // limit part
  98758. var newLimitImpulse;
  98759. if (this.limitState != 2) {
  98760. newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
  98761. var oldLimitImpulse = this.limitImpulse;
  98762. this.limitImpulse += newLimitImpulse;
  98763. if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
  98764. newLimitImpulse = this.limitImpulse - oldLimitImpulse;
  98765. } else newLimitImpulse = 0;
  98766. var totalImpulse = newLimitImpulse + newMotorImpulse;
  98767. this.l1.x += totalImpulse * this.l1x;
  98768. this.l1.y += totalImpulse * this.l1y;
  98769. this.l1.z += totalImpulse * this.l1z;
  98770. this.a1.x += totalImpulse * this.a1x;
  98771. this.a1.y += totalImpulse * this.a1y;
  98772. this.a1.z += totalImpulse * this.a1z;
  98773. this.l2.x -= totalImpulse * this.l2x;
  98774. this.l2.y -= totalImpulse * this.l2y;
  98775. this.l2.z -= totalImpulse * this.l2z;
  98776. this.a2.x -= totalImpulse * this.a2x;
  98777. this.a2.y -= totalImpulse * this.a2y;
  98778. this.a2.z -= totalImpulse * this.a2z;
  98779. }
  98780. }
  98781. /**
  98782. * A contact is a pair of shapes whose axis-aligned bounding boxes are overlapping.
  98783. * @author saharan
  98784. */
  98785. OIMO.Contact = function () {
  98786. // The first shape.
  98787. this.shape1 = null;
  98788. // The second shape.
  98789. this.shape2 = null;
  98790. // The first rigid body.
  98791. this.body1 = null;
  98792. // The second rigid body.
  98793. this.body2 = null;
  98794. // The previous contact in the world.
  98795. this.prev = null;
  98796. // The next contact in the world.
  98797. this.next = null;
  98798. // Internal
  98799. this.persisting = false;
  98800. // Whether both the rigid bodies are sleeping or not.
  98801. this.sleeping = false;
  98802. // The collision detector between two shapes.
  98803. this.detector = null;
  98804. // The contact constraint of the contact.
  98805. this.constraint = null;
  98806. // Whether the shapes are touching or not.
  98807. this.touching = false;
  98808. this.b1Link = new OIMO.ContactLink(this);
  98809. this.b2Link = new OIMO.ContactLink(this);
  98810. this.s1Link = new OIMO.ContactLink(this);
  98811. this.s2Link = new OIMO.ContactLink(this);
  98812. // The contact manifold of the contact.
  98813. this.manifold = new OIMO.ContactManifold();
  98814. this.buffer = [];// vector 4
  98815. this.buffer.length = 4;
  98816. this.buffer[0] = new OIMO.ImpulseDataBuffer();
  98817. this.buffer[1] = new OIMO.ImpulseDataBuffer();
  98818. this.buffer[2] = new OIMO.ImpulseDataBuffer();
  98819. this.buffer[3] = new OIMO.ImpulseDataBuffer();
  98820. this.points = this.manifold.points;
  98821. this.constraint = new OIMO.ContactConstraint(this.manifold);
  98822. }
  98823. OIMO.Contact.prototype = {
  98824. constructor: OIMO.Contact,
  98825. mixRestitution: function (restitution1, restitution2) {
  98826. return OIMO.sqrt(restitution1 * restitution2);
  98827. },
  98828. mixFriction: function (friction1, friction2) {
  98829. return OIMO.sqrt(friction1 * friction2);
  98830. },
  98831. /**
  98832. * Update the contact manifold.
  98833. */
  98834. updateManifold: function () {
  98835. this.constraint.restitution = this.mixRestitution(this.shape1.restitution, this.shape2.restitution);
  98836. this.constraint.friction = this.mixFriction(this.shape1.friction, this.shape2.friction);
  98837. var numBuffers = this.manifold.numPoints;
  98838. var i = numBuffers;
  98839. while (i--) {
  98840. //for(var i=0;i<numBuffers;i++){
  98841. var b = this.buffer[i];
  98842. var p = this.points[i];
  98843. b.lp1X = p.localPoint1.x;
  98844. b.lp1Y = p.localPoint1.y;
  98845. b.lp1Z = p.localPoint1.z;
  98846. b.lp2X = p.localPoint2.x;
  98847. b.lp2Y = p.localPoint2.y;
  98848. b.lp2Z = p.localPoint2.z;
  98849. b.impulse = p.normalImpulse;
  98850. }
  98851. this.manifold.numPoints = 0;
  98852. this.detector.detectCollision(this.shape1, this.shape2, this.manifold);
  98853. var num = this.manifold.numPoints;
  98854. if (num == 0) {
  98855. this.touching = false;
  98856. return;
  98857. }
  98858. this.touching = true;
  98859. i = num;
  98860. while (i--) {
  98861. //for(i=0; i<num; i++){
  98862. p = this.points[i];
  98863. var lp1x = p.localPoint1.x;
  98864. var lp1y = p.localPoint1.y;
  98865. var lp1z = p.localPoint1.z;
  98866. var lp2x = p.localPoint2.x;
  98867. var lp2y = p.localPoint2.y;
  98868. var lp2z = p.localPoint2.z;
  98869. var index = -1;
  98870. var minDistance = 0.0004;
  98871. var j = numBuffers;
  98872. while (j--) {
  98873. //for(var j=0;j<numBuffers;j++){
  98874. b = this.buffer[j];
  98875. var dx = b.lp1X - lp1x;
  98876. var dy = b.lp1Y - lp1y;
  98877. var dz = b.lp1Z - lp1z;
  98878. var distance1 = dx * dx + dy * dy + dz * dz;
  98879. dx = b.lp2X - lp2x;
  98880. dy = b.lp2Y - lp2y;
  98881. dz = b.lp2Z - lp2z;
  98882. var distance2 = dx * dx + dy * dy + dz * dz;
  98883. if (distance1 < distance2) {
  98884. if (distance1 < minDistance) {
  98885. minDistance = distance1;
  98886. index = j;
  98887. }
  98888. } else {
  98889. if (distance2 < minDistance) {
  98890. minDistance = distance2;
  98891. index = j;
  98892. }
  98893. }
  98894. }
  98895. if (index != -1) {
  98896. var tmp = this.buffer[index];
  98897. this.buffer[index] = this.buffer[--numBuffers];
  98898. this.buffer[numBuffers] = tmp;
  98899. p.normalImpulse = tmp.impulse;
  98900. p.warmStarted = true;
  98901. } else {
  98902. p.normalImpulse = 0;
  98903. p.warmStarted = false;
  98904. }
  98905. }
  98906. },
  98907. /**
  98908. * Attach the contact to the shapes.
  98909. * @param shape1
  98910. * @param shape2
  98911. */
  98912. attach: function (shape1, shape2) {
  98913. this.shape1 = shape1;
  98914. this.shape2 = shape2;
  98915. this.body1 = shape1.parent;
  98916. this.body2 = shape2.parent;
  98917. this.manifold.body1 = this.body1;
  98918. this.manifold.body2 = this.body2;
  98919. this.constraint.body1 = this.body1;
  98920. this.constraint.body2 = this.body2;
  98921. this.constraint.attach();
  98922. this.s1Link.shape = shape2;
  98923. this.s1Link.body = this.body2;
  98924. this.s2Link.shape = shape1;
  98925. this.s2Link.body = this.body1;
  98926. if (shape1.contactLink != null) (this.s1Link.next = shape1.contactLink).prev = this.s1Link;
  98927. else this.s1Link.next = null;
  98928. shape1.contactLink = this.s1Link;
  98929. shape1.numContacts++;
  98930. if (shape2.contactLink != null) (this.s2Link.next = shape2.contactLink).prev = this.s2Link;
  98931. else this.s2Link.next = null;
  98932. shape2.contactLink = this.s2Link;
  98933. shape2.numContacts++;
  98934. this.b1Link.shape = shape2;
  98935. this.b1Link.body = this.body2;
  98936. this.b2Link.shape = shape1;
  98937. this.b2Link.body = this.body1;
  98938. if (this.body1.contactLink != null) (this.b1Link.next = this.body1.contactLink).prev = this.b1Link;
  98939. else this.b1Link.next = null;
  98940. this.body1.contactLink = this.b1Link;
  98941. this.body1.numContacts++;
  98942. if (this.body2.contactLink != null) (this.b2Link.next = this.body2.contactLink).prev = this.b2Link;
  98943. else this.b2Link.next = null;
  98944. this.body2.contactLink = this.b2Link;
  98945. this.body2.numContacts++;
  98946. this.prev = null;
  98947. this.next = null;
  98948. this.persisting = true;
  98949. this.sleeping = this.body1.sleeping && this.body2.sleeping;
  98950. this.manifold.numPoints = 0;
  98951. },
  98952. /**
  98953. * Detach the contact from the shapes.
  98954. */
  98955. detach: function () {
  98956. var prev = this.s1Link.prev;
  98957. var next = this.s1Link.next;
  98958. if (prev !== null) prev.next = next;
  98959. if (next !== null) next.prev = prev;
  98960. if (this.shape1.contactLink == this.s1Link) this.shape1.contactLink = next;
  98961. this.s1Link.prev = null;
  98962. this.s1Link.next = null;
  98963. this.s1Link.shape = null;
  98964. this.s1Link.body = null;
  98965. this.shape1.numContacts--;
  98966. prev = this.s2Link.prev;
  98967. next = this.s2Link.next;
  98968. if (prev !== null) prev.next = next;
  98969. if (next !== null) next.prev = prev;
  98970. if (this.shape2.contactLink == this.s2Link) this.shape2.contactLink = next;
  98971. this.s2Link.prev = null;
  98972. this.s2Link.next = null;
  98973. this.s2Link.shape = null;
  98974. this.s2Link.body = null;
  98975. this.shape2.numContacts--;
  98976. prev = this.b1Link.prev;
  98977. next = this.b1Link.next;
  98978. if (prev !== null) prev.next = next;
  98979. if (next !== null) next.prev = prev;
  98980. if (this.body1.contactLink == this.b1Link) this.body1.contactLink = next;
  98981. this.b1Link.prev = null;
  98982. this.b1Link.next = null;
  98983. this.b1Link.shape = null;
  98984. this.b1Link.body = null;
  98985. this.body1.numContacts--;
  98986. prev = this.b2Link.prev;
  98987. next = this.b2Link.next;
  98988. if (prev !== null) prev.next = next;
  98989. if (next !== null) next.prev = prev;
  98990. if (this.body2.contactLink == this.b2Link) this.body2.contactLink = next;
  98991. this.b2Link.prev = null;
  98992. this.b2Link.next = null;
  98993. this.b2Link.shape = null;
  98994. this.b2Link.body = null;
  98995. this.body2.numContacts--;
  98996. this.manifold.body1 = null;
  98997. this.manifold.body2 = null;
  98998. this.constraint.body1 = null;
  98999. this.constraint.body2 = null;
  99000. this.constraint.detach();
  99001. this.shape1 = null;
  99002. this.shape2 = null;
  99003. this.body1 = null;
  99004. this.body2 = null;
  99005. }
  99006. }
  99007. /**
  99008. * ...
  99009. * @author saharan
  99010. */
  99011. OIMO.ContactConstraint = function (manifold) {
  99012. OIMO.Constraint.call(this);
  99013. // The contact manifold of the constraint.
  99014. this.manifold = manifold;
  99015. // The coefficient of restitution of the constraint.
  99016. this.restitution = NaN;
  99017. // The coefficient of friction of the constraint.
  99018. this.friction = NaN;
  99019. this.p1 = null;
  99020. this.p2 = null;
  99021. this.lv1 = null;
  99022. this.lv2 = null;
  99023. this.av1 = null;
  99024. this.av2 = null;
  99025. this.i1 = null;
  99026. this.i2 = null;
  99027. this.ii1 = null;
  99028. this.ii2 = null;
  99029. this.m1 = NaN;
  99030. this.m2 = NaN;
  99031. this.num = 0;
  99032. this.ps = manifold.points;
  99033. this.cs = new OIMO.ContactPointDataBuffer();
  99034. this.cs.next = new OIMO.ContactPointDataBuffer();
  99035. this.cs.next.next = new OIMO.ContactPointDataBuffer();
  99036. this.cs.next.next.next = new OIMO.ContactPointDataBuffer();
  99037. }
  99038. OIMO.ContactConstraint.prototype = Object.create(OIMO.Constraint.prototype);
  99039. /**
  99040. * Attach the constraint to the bodies.
  99041. */
  99042. OIMO.ContactConstraint.prototype.attach = function () {
  99043. this.p1 = this.body1.position;
  99044. this.p2 = this.body2.position;
  99045. this.lv1 = this.body1.linearVelocity;
  99046. this.av1 = this.body1.angularVelocity;
  99047. this.lv2 = this.body2.linearVelocity;
  99048. this.av2 = this.body2.angularVelocity;
  99049. this.i1 = this.body1.inverseInertia;
  99050. this.i2 = this.body2.inverseInertia;
  99051. }
  99052. /**
  99053. * Detach the constraint from the bodies.
  99054. */
  99055. OIMO.ContactConstraint.prototype.detach = function () {
  99056. this.p1 = null;
  99057. this.p2 = null;
  99058. this.lv1 = null;
  99059. this.lv2 = null;
  99060. this.av1 = null;
  99061. this.av2 = null;
  99062. this.i1 = null;
  99063. this.i2 = null;
  99064. }
  99065. OIMO.ContactConstraint.prototype.preSolve = function (timeStep, invTimeStep) {
  99066. this.m1 = this.body1.inverseMass;
  99067. this.m2 = this.body2.inverseMass;
  99068. this.ii1 = this.i1.clone();
  99069. this.ii2 = this.i2.clone();
  99070. var ii1 = this.ii1.elements;
  99071. var ii2 = this.ii2.elements;
  99072. var p1x = this.p1.x;
  99073. var p1y = this.p1.y;
  99074. var p1z = this.p1.z;
  99075. var p2x = this.p2.x;
  99076. var p2y = this.p2.y;
  99077. var p2z = this.p2.z;
  99078. var m1m2 = this.m1 + this.m2;
  99079. this.num = this.manifold.numPoints;
  99080. var c = this.cs;
  99081. for (var i = 0; i < this.num; i++) {
  99082. var p = this.ps[i];
  99083. var tmp1X;
  99084. var tmp1Y;
  99085. var tmp1Z;
  99086. var tmp2X;
  99087. var tmp2Y;
  99088. var tmp2Z;
  99089. tmp1X = p.position.x;
  99090. tmp1Y = p.position.y;
  99091. tmp1Z = p.position.z;
  99092. var rp1X = tmp1X - p1x;
  99093. var rp1Y = tmp1Y - p1y;
  99094. var rp1Z = tmp1Z - p1z;
  99095. var rp2X = tmp1X - p2x;
  99096. var rp2Y = tmp1Y - p2y;
  99097. var rp2Z = tmp1Z - p2z;
  99098. c.rp1X = rp1X;
  99099. c.rp1Y = rp1Y;
  99100. c.rp1Z = rp1Z;
  99101. c.rp2X = rp2X;
  99102. c.rp2Y = rp2Y;
  99103. c.rp2Z = rp2Z;
  99104. c.norImp = p.normalImpulse;
  99105. c.tanImp = p.tangentImpulse;
  99106. c.binImp = p.binormalImpulse;
  99107. var norX = p.normal.x;
  99108. var norY = p.normal.y;
  99109. var norZ = p.normal.z;
  99110. var rvX = (this.lv2.x + this.av2.y * rp2Z - this.av2.z * rp2Y) - (this.lv1.x + this.av1.y * rp1Z - this.av1.z * rp1Y);
  99111. var rvY = (this.lv2.y + this.av2.z * rp2X - this.av2.x * rp2Z) - (this.lv1.y + this.av1.z * rp1X - this.av1.x * rp1Z);
  99112. var rvZ = (this.lv2.z + this.av2.x * rp2Y - this.av2.y * rp2X) - (this.lv1.z + this.av1.x * rp1Y - this.av1.y * rp1X);
  99113. var rvn = norX * rvX + norY * rvY + norZ * rvZ;
  99114. var tanX = rvX - rvn * norX;
  99115. var tanY = rvY - rvn * norY;
  99116. var tanZ = rvZ - rvn * norZ;
  99117. var len = tanX * tanX + tanY * tanY + tanZ * tanZ;
  99118. if (len > 0.04) {
  99119. len = 1 / OIMO.sqrt(len);
  99120. } else {
  99121. tanX = norY * norX - norZ * norZ;
  99122. tanY = -norZ * norY - norX * norX;
  99123. tanZ = norX * norZ + norY * norY;
  99124. len = 1 / OIMO.sqrt(tanX * tanX + tanY * tanY + tanZ * tanZ);
  99125. }
  99126. tanX *= len;
  99127. tanY *= len;
  99128. tanZ *= len;
  99129. var binX = norY * tanZ - norZ * tanY;
  99130. var binY = norZ * tanX - norX * tanZ;
  99131. var binZ = norX * tanY - norY * tanX;
  99132. c.norX = norX;
  99133. c.norY = norY;
  99134. c.norZ = norZ;
  99135. c.tanX = tanX;
  99136. c.tanY = tanY;
  99137. c.tanZ = tanZ;
  99138. c.binX = binX;
  99139. c.binY = binY;
  99140. c.binZ = binZ;
  99141. c.norU1X = norX * this.m1;
  99142. c.norU1Y = norY * this.m1;
  99143. c.norU1Z = norZ * this.m1;
  99144. c.norU2X = norX * this.m2;
  99145. c.norU2Y = norY * this.m2;
  99146. c.norU2Z = norZ * this.m2;
  99147. c.tanU1X = tanX * this.m1;
  99148. c.tanU1Y = tanY * this.m1;
  99149. c.tanU1Z = tanZ * this.m1;
  99150. c.tanU2X = tanX * this.m2;
  99151. c.tanU2Y = tanY * this.m2;
  99152. c.tanU2Z = tanZ * this.m2;
  99153. c.binU1X = binX * this.m1;
  99154. c.binU1Y = binY * this.m1;
  99155. c.binU1Z = binZ * this.m1;
  99156. c.binU2X = binX * this.m2;
  99157. c.binU2Y = binY * this.m2;
  99158. c.binU2Z = binZ * this.m2;
  99159. var norT1X = rp1Y * norZ - rp1Z * norY;
  99160. var norT1Y = rp1Z * norX - rp1X * norZ;
  99161. var norT1Z = rp1X * norY - rp1Y * norX;
  99162. var norT2X = rp2Y * norZ - rp2Z * norY;
  99163. var norT2Y = rp2Z * norX - rp2X * norZ;
  99164. var norT2Z = rp2X * norY - rp2Y * norX;
  99165. var tanT1X = rp1Y * tanZ - rp1Z * tanY;
  99166. var tanT1Y = rp1Z * tanX - rp1X * tanZ;
  99167. var tanT1Z = rp1X * tanY - rp1Y * tanX;
  99168. var tanT2X = rp2Y * tanZ - rp2Z * tanY;
  99169. var tanT2Y = rp2Z * tanX - rp2X * tanZ;
  99170. var tanT2Z = rp2X * tanY - rp2Y * tanX;
  99171. var binT1X = rp1Y * binZ - rp1Z * binY;
  99172. var binT1Y = rp1Z * binX - rp1X * binZ;
  99173. var binT1Z = rp1X * binY - rp1Y * binX;
  99174. var binT2X = rp2Y * binZ - rp2Z * binY;
  99175. var binT2Y = rp2Z * binX - rp2X * binZ;
  99176. var binT2Z = rp2X * binY - rp2Y * binX;
  99177. var norTU1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
  99178. var norTU1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
  99179. var norTU1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
  99180. var norTU2X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
  99181. var norTU2Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
  99182. var norTU2Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
  99183. var tanTU1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
  99184. var tanTU1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
  99185. var tanTU1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
  99186. var tanTU2X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
  99187. var tanTU2Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
  99188. var tanTU2Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
  99189. var binTU1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
  99190. var binTU1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
  99191. var binTU1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
  99192. var binTU2X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
  99193. var binTU2Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
  99194. var binTU2Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
  99195. c.norT1X = norT1X;
  99196. c.norT1Y = norT1Y;
  99197. c.norT1Z = norT1Z;
  99198. c.tanT1X = tanT1X;
  99199. c.tanT1Y = tanT1Y;
  99200. c.tanT1Z = tanT1Z;
  99201. c.binT1X = binT1X;
  99202. c.binT1Y = binT1Y;
  99203. c.binT1Z = binT1Z;
  99204. c.norT2X = norT2X;
  99205. c.norT2Y = norT2Y;
  99206. c.norT2Z = norT2Z;
  99207. c.tanT2X = tanT2X;
  99208. c.tanT2Y = tanT2Y;
  99209. c.tanT2Z = tanT2Z;
  99210. c.binT2X = binT2X;
  99211. c.binT2Y = binT2Y;
  99212. c.binT2Z = binT2Z;
  99213. c.norTU1X = norTU1X;
  99214. c.norTU1Y = norTU1Y;
  99215. c.norTU1Z = norTU1Z;
  99216. c.tanTU1X = tanTU1X;
  99217. c.tanTU1Y = tanTU1Y;
  99218. c.tanTU1Z = tanTU1Z;
  99219. c.binTU1X = binTU1X;
  99220. c.binTU1Y = binTU1Y;
  99221. c.binTU1Z = binTU1Z;
  99222. c.norTU2X = norTU2X;
  99223. c.norTU2Y = norTU2Y;
  99224. c.norTU2Z = norTU2Z;
  99225. c.tanTU2X = tanTU2X;
  99226. c.tanTU2Y = tanTU2Y;
  99227. c.tanTU2Z = tanTU2Z;
  99228. c.binTU2X = binTU2X;
  99229. c.binTU2Y = binTU2Y;
  99230. c.binTU2Z = binTU2Z;
  99231. tmp1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
  99232. tmp1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
  99233. tmp1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
  99234. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  99235. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  99236. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  99237. tmp1X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
  99238. tmp1Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
  99239. tmp1Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
  99240. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  99241. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  99242. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  99243. var norDen = 1 / (m1m2 + norX * tmp2X + norY * tmp2Y + norZ * tmp2Z);
  99244. tmp1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
  99245. tmp1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
  99246. tmp1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
  99247. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  99248. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  99249. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  99250. tmp1X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
  99251. tmp1Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
  99252. tmp1Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
  99253. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  99254. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  99255. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  99256. var tanDen = 1 / (m1m2 + tanX * tmp2X + tanY * tmp2Y + tanZ * tmp2Z);
  99257. tmp1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
  99258. tmp1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
  99259. tmp1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
  99260. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  99261. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  99262. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  99263. tmp1X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
  99264. tmp1Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
  99265. tmp1Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
  99266. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  99267. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  99268. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  99269. var binDen = 1 / (m1m2 + binX * tmp2X + binY * tmp2Y + binZ * tmp2Z);
  99270. c.norDen = norDen;
  99271. c.tanDen = tanDen;
  99272. c.binDen = binDen;
  99273. if (p.warmStarted) {
  99274. var norImp = p.normalImpulse;
  99275. this.lv1.x += c.norU1X * norImp;
  99276. this.lv1.y += c.norU1Y * norImp;
  99277. this.lv1.z += c.norU1Z * norImp;
  99278. this.av1.x += norTU1X * norImp;
  99279. this.av1.y += norTU1Y * norImp;
  99280. this.av1.z += norTU1Z * norImp;
  99281. this.lv2.x -= c.norU2X * norImp;
  99282. this.lv2.y -= c.norU2Y * norImp;
  99283. this.lv2.z -= c.norU2Z * norImp;
  99284. this.av2.x -= norTU2X * norImp;
  99285. this.av2.y -= norTU2Y * norImp;
  99286. this.av2.z -= norTU2Z * norImp;
  99287. c.norImp = norImp;
  99288. c.tanImp = 0;
  99289. c.binImp = 0;
  99290. rvn = 0; // disable bouncing
  99291. } else {
  99292. c.norImp = 0;
  99293. c.tanImp = 0;
  99294. c.binImp = 0;
  99295. }
  99296. if (rvn > -1) {
  99297. rvn = 0; // disable bouncing
  99298. }
  99299. var norTar = this.restitution * -rvn;
  99300. var sepV = -(p.penetration + 0.005) * invTimeStep * 0.05; // allow 0.5cm error
  99301. if (norTar < sepV) norTar = sepV;
  99302. c.norTar = norTar;
  99303. c.last = i == this.num - 1;
  99304. c = c.next;
  99305. }
  99306. }
  99307. OIMO.ContactConstraint.prototype.solve = function () {
  99308. var lv1x = this.lv1.x;
  99309. var lv1y = this.lv1.y;
  99310. var lv1z = this.lv1.z;
  99311. var lv2x = this.lv2.x;
  99312. var lv2y = this.lv2.y;
  99313. var lv2z = this.lv2.z;
  99314. var av1x = this.av1.x;
  99315. var av1y = this.av1.y;
  99316. var av1z = this.av1.z;
  99317. var av2x = this.av2.x;
  99318. var av2y = this.av2.y;
  99319. var av2z = this.av2.z;
  99320. var c = this.cs;
  99321. while (true) {
  99322. var oldImp1;
  99323. var newImp1;
  99324. var oldImp2;
  99325. var newImp2;
  99326. var rvn;
  99327. var norImp = c.norImp;
  99328. var tanImp = c.tanImp;
  99329. var binImp = c.binImp;
  99330. var max = -norImp * this.friction;
  99331. var rvX = lv2x - lv1x;
  99332. var rvY = lv2y - lv1y;
  99333. var rvZ = lv2z - lv1z;
  99334. rvn =
  99335. rvX * c.tanX + rvY * c.tanY + rvZ * c.tanZ +
  99336. av2x * c.tanT2X + av2y * c.tanT2Y + av2z * c.tanT2Z -
  99337. av1x * c.tanT1X - av1y * c.tanT1Y - av1z * c.tanT1Z
  99338. ;
  99339. oldImp1 = tanImp;
  99340. newImp1 = rvn * c.tanDen;
  99341. tanImp += newImp1;
  99342. rvn =
  99343. rvX * c.binX + rvY * c.binY + rvZ * c.binZ +
  99344. av2x * c.binT2X + av2y * c.binT2Y + av2z * c.binT2Z -
  99345. av1x * c.binT1X - av1y * c.binT1Y - av1z * c.binT1Z
  99346. ;
  99347. oldImp2 = binImp;
  99348. newImp2 = rvn * c.binDen;
  99349. binImp += newImp2;
  99350. // cone friction clamp
  99351. var len = tanImp * tanImp + binImp * binImp;
  99352. if (len > max * max) {
  99353. len = max / OIMO.sqrt(len);
  99354. tanImp *= len;
  99355. binImp *= len;
  99356. }
  99357. newImp1 = tanImp - oldImp1;
  99358. newImp2 = binImp - oldImp2;
  99359. lv1x += c.tanU1X * newImp1 + c.binU1X * newImp2;
  99360. lv1y += c.tanU1Y * newImp1 + c.binU1Y * newImp2;
  99361. lv1z += c.tanU1Z * newImp1 + c.binU1Z * newImp2;
  99362. av1x += c.tanTU1X * newImp1 + c.binTU1X * newImp2;
  99363. av1y += c.tanTU1Y * newImp1 + c.binTU1Y * newImp2;
  99364. av1z += c.tanTU1Z * newImp1 + c.binTU1Z * newImp2;
  99365. lv2x -= c.tanU2X * newImp1 + c.binU2X * newImp2;
  99366. lv2y -= c.tanU2Y * newImp1 + c.binU2Y * newImp2;
  99367. lv2z -= c.tanU2Z * newImp1 + c.binU2Z * newImp2;
  99368. av2x -= c.tanTU2X * newImp1 + c.binTU2X * newImp2;
  99369. av2y -= c.tanTU2Y * newImp1 + c.binTU2Y * newImp2;
  99370. av2z -= c.tanTU2Z * newImp1 + c.binTU2Z * newImp2;
  99371. // restitution part
  99372. rvn =
  99373. (lv2x - lv1x) * c.norX + (lv2y - lv1y) * c.norY + (lv2z - lv1z) * c.norZ +
  99374. av2x * c.norT2X + av2y * c.norT2Y + av2z * c.norT2Z -
  99375. av1x * c.norT1X - av1y * c.norT1Y - av1z * c.norT1Z;
  99376. oldImp1 = norImp;
  99377. newImp1 = (rvn - c.norTar) * c.norDen;
  99378. norImp += newImp1;
  99379. if (norImp > 0) norImp = 0;
  99380. newImp1 = norImp - oldImp1;
  99381. lv1x += c.norU1X * newImp1;
  99382. lv1y += c.norU1Y * newImp1;
  99383. lv1z += c.norU1Z * newImp1;
  99384. av1x += c.norTU1X * newImp1;
  99385. av1y += c.norTU1Y * newImp1;
  99386. av1z += c.norTU1Z * newImp1;
  99387. lv2x -= c.norU2X * newImp1;
  99388. lv2y -= c.norU2Y * newImp1;
  99389. lv2z -= c.norU2Z * newImp1;
  99390. av2x -= c.norTU2X * newImp1;
  99391. av2y -= c.norTU2Y * newImp1;
  99392. av2z -= c.norTU2Z * newImp1;
  99393. c.norImp = norImp;
  99394. c.tanImp = tanImp;
  99395. c.binImp = binImp;
  99396. if (c.last) break;
  99397. c = c.next;
  99398. }
  99399. this.lv1.x = lv1x;
  99400. this.lv1.y = lv1y;
  99401. this.lv1.z = lv1z;
  99402. this.lv2.x = lv2x;
  99403. this.lv2.y = lv2y;
  99404. this.lv2.z = lv2z;
  99405. this.av1.x = av1x;
  99406. this.av1.y = av1y;
  99407. this.av1.z = av1z;
  99408. this.av2.x = av2x;
  99409. this.av2.y = av2y;
  99410. this.av2.z = av2z;
  99411. }
  99412. OIMO.ContactConstraint.prototype.postSolve = function () {
  99413. var c = this.cs;
  99414. var i = this.num;
  99415. while (i--) {
  99416. //for(var i=0;i<this.num;i++){
  99417. var p = this.ps[i];
  99418. p.normal.x = c.norX;
  99419. p.normal.y = c.norY;
  99420. p.normal.z = c.norZ;
  99421. p.tangent.x = c.tanX;
  99422. p.tangent.y = c.tanY;
  99423. p.tangent.z = c.tanZ;
  99424. p.binormal.x = c.binX;
  99425. p.binormal.y = c.binY;
  99426. p.binormal.z = c.binZ;
  99427. p.normalImpulse = c.norImp;
  99428. p.tangentImpulse = c.tanImp;
  99429. p.binormalImpulse = c.binImp;
  99430. p.normalDenominator = c.norDen;
  99431. p.tangentDenominator = c.tanDen;
  99432. p.binormalDenominator = c.binDen;
  99433. c = c.next;
  99434. }
  99435. }
  99436. /**
  99437. * A link list of contacts.
  99438. * @author saharan
  99439. */
  99440. OIMO.ContactLink = function (contact) {
  99441. // The previous contact link.
  99442. this.prev = null;
  99443. // The next contact link.
  99444. this.next = null;
  99445. // The shape of the contact.
  99446. this.shape = null;
  99447. // The other rigid body.
  99448. this.body = null;
  99449. // The contact of the link.
  99450. this.contact = contact;
  99451. }
  99452. /**
  99453. * A contact manifold between two shapes.
  99454. * @author saharan
  99455. */
  99456. OIMO.ContactManifold = function () {
  99457. // The first rigid body.
  99458. this.body1 = null;
  99459. // The second rigid body.
  99460. this.body2 = null;
  99461. // The number of manifold points.
  99462. this.numPoints = 0;
  99463. // The manifold points.
  99464. this.points = [];
  99465. this.points.length = 4;
  99466. this.points[0] = new OIMO.ManifoldPoint();
  99467. this.points[1] = new OIMO.ManifoldPoint();
  99468. this.points[2] = new OIMO.ManifoldPoint();
  99469. this.points[3] = new OIMO.ManifoldPoint();
  99470. }
  99471. OIMO.ContactManifold.prototype = {
  99472. constructor: OIMO.ContactManifold,
  99473. /**
  99474. * Reset the manifold.
  99475. * @param shape1
  99476. * @param shape2
  99477. */
  99478. reset: function (shape1, shape2) {
  99479. this.body1 = shape1.parent;
  99480. this.body2 = shape2.parent;
  99481. this.numPoints = 0;
  99482. },
  99483. /**
  99484. * Add a point into this manifold.
  99485. * @param x
  99486. * @param y
  99487. * @param z
  99488. * @param normalX
  99489. * @param normalY
  99490. * @param normalZ
  99491. * @param penetration
  99492. * @param flip
  99493. */
  99494. addPoint: function (x, y, z, normalX, normalY, normalZ, penetration, flip) {
  99495. var p = this.points[this.numPoints++];
  99496. p.position.x = x;
  99497. p.position.y = y;
  99498. p.position.z = z;
  99499. var r = this.body1.rotation;
  99500. var rx = x - this.body1.position.x;
  99501. var ry = y - this.body1.position.y;
  99502. var rz = z - this.body1.position.z;
  99503. var tr = r.elements;
  99504. p.localPoint1.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
  99505. p.localPoint1.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
  99506. p.localPoint1.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
  99507. r = this.body2.rotation;
  99508. rx = x - this.body2.position.x;
  99509. ry = y - this.body2.position.y;
  99510. rz = z - this.body2.position.z;
  99511. p.localPoint2.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
  99512. p.localPoint2.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
  99513. p.localPoint2.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
  99514. p.normalImpulse = 0;
  99515. if (flip) {
  99516. p.normal.x = -normalX;
  99517. p.normal.y = -normalY;
  99518. p.normal.z = -normalZ;
  99519. } else {
  99520. p.normal.x = normalX;
  99521. p.normal.y = normalY;
  99522. p.normal.z = normalZ;
  99523. }
  99524. p.penetration = penetration;
  99525. p.warmStarted = false;
  99526. }
  99527. }
  99528. OIMO.ContactPointDataBuffer = function () {
  99529. this.norX = NaN;
  99530. this.norY = NaN;
  99531. this.norZ = NaN;
  99532. this.tanX = NaN;
  99533. this.tanY = NaN;
  99534. this.tanZ = NaN;
  99535. this.binX = NaN;
  99536. this.binY = NaN;
  99537. this.binZ = NaN;
  99538. this.rp1X = NaN;
  99539. this.rp1Y = NaN;
  99540. this.rp1Z = NaN;
  99541. this.rp2X = NaN;
  99542. this.rp2Y = NaN;
  99543. this.rp2Z = NaN;
  99544. this.norU1X = NaN;
  99545. this.norU1Y = NaN;
  99546. this.norU1Z = NaN;
  99547. this.norU2X = NaN;
  99548. this.norU2Y = NaN;
  99549. this.norU2Z = NaN;
  99550. this.tanU1X = NaN;
  99551. this.tanU1Y = NaN;
  99552. this.tanU1Z = NaN;
  99553. this.tanU2X = NaN;
  99554. this.tanU2Y = NaN;
  99555. this.tanU2Z = NaN;
  99556. this.binU1X = NaN;
  99557. this.binU1Y = NaN;
  99558. this.binU1Z = NaN;
  99559. this.binU2X = NaN;
  99560. this.binU2Y = NaN;
  99561. this.binU2Z = NaN;
  99562. this.norT1X = NaN;
  99563. this.norT1Y = NaN;
  99564. this.norT1Z = NaN;
  99565. this.norT2X = NaN;
  99566. this.norT2Y = NaN;
  99567. this.norT2Z = NaN;
  99568. this.tanT1X = NaN;
  99569. this.tanT1Y = NaN;
  99570. this.tanT1Z = NaN;
  99571. this.tanT2X = NaN;
  99572. this.tanT2Y = NaN;
  99573. this.tanT2Z = NaN;
  99574. this.binT1X = NaN;
  99575. this.binT1Y = NaN;
  99576. this.binT1Z = NaN;
  99577. this.binT2X = NaN;
  99578. this.binT2Y = NaN;
  99579. this.binT2Z = NaN;
  99580. this.norTU1X = NaN;
  99581. this.norTU1Y = NaN;
  99582. this.norTU1Z = NaN;
  99583. this.norTU2X = NaN;
  99584. this.norTU2Y = NaN;
  99585. this.norTU2Z = NaN;
  99586. this.tanTU1X = NaN;
  99587. this.tanTU1Y = NaN;
  99588. this.tanTU1Z = NaN;
  99589. this.tanTU2X = NaN;
  99590. this.tanTU2Y = NaN;
  99591. this.tanTU2Z = NaN;
  99592. this.binTU1X = NaN;
  99593. this.binTU1Y = NaN;
  99594. this.binTU1Z = NaN;
  99595. this.binTU2X = NaN;
  99596. this.binTU2Y = NaN;
  99597. this.binTU2Z = NaN;
  99598. this.norImp = NaN;
  99599. this.tanImp = NaN;
  99600. this.binImp = NaN;
  99601. this.norDen = NaN;
  99602. this.tanDen = NaN;
  99603. this.binDen = NaN;
  99604. this.norTar = NaN;
  99605. this.next = null;
  99606. this.last = false;
  99607. }
  99608. OIMO.ImpulseDataBuffer = function () {
  99609. this.lp1X = NaN;
  99610. this.lp1Y = NaN;
  99611. this.lp1Z = NaN;
  99612. this.lp2X = NaN;
  99613. this.lp2Y = NaN;
  99614. this.lp2Z = NaN;
  99615. this.impulse = NaN;
  99616. }
  99617. /**
  99618. * The class holds details of the contact point.
  99619. * @author saharan
  99620. */
  99621. OIMO.ManifoldPoint = function () {
  99622. // Whether this manifold point is persisting or not.
  99623. this.warmStarted = false;
  99624. // The position of this manifold point.
  99625. this.position = new OIMO.Vec3();
  99626. // The position in the first shape's coordinate.
  99627. this.localPoint1 = new OIMO.Vec3();
  99628. // The position in the second shape's coordinate.
  99629. this.localPoint2 = new OIMO.Vec3();
  99630. // The normal vector of this manifold point.
  99631. this.normal = new OIMO.Vec3();
  99632. // The tangent vector of this manifold point.
  99633. this.tangent = new OIMO.Vec3();
  99634. // The binormal vector of this manifold point.
  99635. this.binormal = new OIMO.Vec3();
  99636. // The impulse in normal direction.
  99637. this.normalImpulse = 0;
  99638. // The impulse in tangent direction.
  99639. this.tangentImpulse = 0;
  99640. // The impulse in binormal direction.
  99641. this.binormalImpulse = 0;
  99642. // The denominator in normal direction.
  99643. this.normalDenominator = 0;
  99644. // The denominator in tangent direction.
  99645. this.tangentDenominator = 0;
  99646. // The denominator in binormal direction.
  99647. this.binormalDenominator = 0;
  99648. // The depth of penetration.
  99649. this.penetration = 0;
  99650. }
  99651. /**
  99652. * This class holds mass information of a shape.
  99653. * @author saharan
  99654. */
  99655. OIMO.MassInfo = function () {
  99656. // Mass of the shape.
  99657. this.mass = 0;
  99658. // The moment inertia of the shape.
  99659. this.inertia = new OIMO.Mat33();
  99660. };
  99661. /**
  99662. * A shape is used to detect collisions of rigid bodies.
  99663. * @author saharan
  99664. * @author lo-th
  99665. */
  99666. OIMO.Shape = function (config) {
  99667. this.type = OIMO.SHAPE_NULL;
  99668. // The global identification of the shape should be unique to the shape.
  99669. this.id = OIMO.nextID++;
  99670. // The previous shape in parent rigid body.
  99671. this.prev = null;
  99672. // The next shape in parent rigid body.
  99673. this.next = null;
  99674. // The proxy of the shape used for broad-phase collision detection.
  99675. this.proxy = null;
  99676. // The parent rigid body of the shape.
  99677. this.parent = null;
  99678. // The linked list of the contacts with the shape.
  99679. this.contactLink = null;
  99680. // The number of the contacts with the shape.
  99681. this.numContacts = 0;
  99682. // The center of gravity of the shape in world coordinate system.
  99683. this.position = new OIMO.Vec3();
  99684. // The rotation matrix of the shape in world coordinate system
  99685. this.rotation = new OIMO.Mat33();
  99686. // The position of the shape in parent's coordinate system.
  99687. this.relativePosition = new OIMO.Vec3().copy(config.relativePosition);
  99688. // The rotation matrix of the shape in parent's coordinate system.
  99689. this.relativeRotation = new OIMO.Mat33().copy(config.relativeRotation);
  99690. // The axis-aligned bounding box of the shape.
  99691. this.aabb = new OIMO.AABB();
  99692. // The density of the shape.
  99693. this.density = config.density;
  99694. // The coefficient of friction of the shape.
  99695. this.friction = config.friction;
  99696. // The coefficient of restitution of the shape.
  99697. this.restitution = config.restitution;
  99698. // The bits of the collision groups to which the shape belongs.
  99699. this.belongsTo = config.belongsTo;
  99700. // The bits of the collision groups with which the shape collides.
  99701. this.collidesWith = config.collidesWith;
  99702. };
  99703. OIMO.Shape.prototype = {
  99704. constructor: OIMO.Shape,
  99705. // Calculate the mass information of the shape.
  99706. calculateMassInfo: function (out) {
  99707. OIMO.Error("Shape", "Inheritance error.");
  99708. },
  99709. // Update the proxy of the shape.
  99710. updateProxy: function () {
  99711. OIMO.Error("Shape", "Inheritance error.");
  99712. }
  99713. };
  99714. /**
  99715. * A shape configuration holds common configuration data for constructing a shape.
  99716. * Shape configurations can be reused safely.
  99717. * @author saharan
  99718. */
  99719. OIMO.ShapeConfig = function () {
  99720. // The position of the shape in parent's coordinate system.
  99721. this.relativePosition = new OIMO.Vec3();
  99722. // The rotation matrix of the shape in parent's coordinate system.
  99723. this.relativeRotation = new OIMO.Mat33();
  99724. // The coefficient of friction of the shape.
  99725. this.friction = 0.4;
  99726. // The coefficient of restitution of the shape.
  99727. this.restitution = 0.2;
  99728. // The density of the shape.
  99729. this.density = 1;
  99730. // The bits of the collision groups to which the shape belongs.
  99731. this.belongsTo = 1;
  99732. // The bits of the collision groups with which the shape collides.
  99733. this.collidesWith = 0xffffffff;
  99734. };
  99735. /**
  99736. * A box shape.
  99737. * @author saharan
  99738. * @author lo-th
  99739. */
  99740. OIMO.BoxShape = function (config, Width, Height, Depth) {
  99741. OIMO.Shape.call(this, config);
  99742. this.type = OIMO.SHAPE_BOX;
  99743. // The width of the box.
  99744. this.width = Width;
  99745. // The height of the box.
  99746. this.height = Height;
  99747. // The depth of the box.
  99748. this.depth = Depth;
  99749. // The half-width of the box.
  99750. this.halfWidth = Width * 0.5;
  99751. // The half-height of the box.
  99752. this.halfHeight = Height * 0.5;
  99753. // The half-depth of the box.
  99754. this.halfDepth = Depth * 0.5;
  99755. this.dimentions = new OIMO_ARRAY_TYPE(18);
  99756. this.elements = new OIMO_ARRAY_TYPE(24);
  99757. };
  99758. OIMO.BoxShape.prototype = Object.create(OIMO.Shape.prototype);
  99759. OIMO.BoxShape.prototype.constructor = OIMO.BoxShape;
  99760. OIMO.BoxShape.prototype.calculateMassInfo = function (out) {
  99761. var mass = this.width * this.height * this.depth * this.density;
  99762. var divid = 1 / 12;
  99763. out.mass = mass;
  99764. out.inertia.set(
  99765. mass * (this.height * this.height + this.depth * this.depth) * divid, 0, 0,
  99766. 0, mass * (this.width * this.width + this.depth * this.depth) * divid, 0,
  99767. 0, 0, mass * (this.width * this.width + this.height * this.height) * divid
  99768. );
  99769. };
  99770. OIMO.BoxShape.prototype.updateProxy = function () {
  99771. var te = this.rotation.elements;
  99772. var di = this.dimentions;
  99773. // Width
  99774. di[0] = te[0];
  99775. di[1] = te[3];
  99776. di[2] = te[6];
  99777. // Height
  99778. di[3] = te[1];
  99779. di[4] = te[4];
  99780. di[5] = te[7];
  99781. // Depth
  99782. di[6] = te[2];
  99783. di[7] = te[5];
  99784. di[8] = te[8];
  99785. // halp Width
  99786. di[9] = te[0] * this.halfWidth;
  99787. di[10] = te[3] * this.halfWidth;
  99788. di[11] = te[6] * this.halfWidth;
  99789. // halp Height
  99790. di[12] = te[1] * this.halfHeight;
  99791. di[13] = te[4] * this.halfHeight;
  99792. di[14] = te[7] * this.halfHeight;
  99793. // halp Depth
  99794. di[15] = te[2] * this.halfDepth;
  99795. di[16] = te[5] * this.halfDepth;
  99796. di[17] = te[8] * this.halfDepth;
  99797. var wx = di[9];
  99798. var wy = di[10];
  99799. var wz = di[11];
  99800. var hx = di[12];
  99801. var hy = di[13];
  99802. var hz = di[14];
  99803. var dx = di[15];
  99804. var dy = di[16];
  99805. var dz = di[17];
  99806. var x = this.position.x;
  99807. var y = this.position.y;
  99808. var z = this.position.z;
  99809. var v = this.elements;
  99810. //v1
  99811. v[0] = x + wx + hx + dx;
  99812. v[1] = y + wy + hy + dy;
  99813. v[2] = z + wz + hz + dz;
  99814. //v2
  99815. v[3] = x + wx + hx - dx;
  99816. v[4] = y + wy + hy - dy;
  99817. v[5] = z + wz + hz - dz;
  99818. //v3
  99819. v[6] = x + wx - hx + dx;
  99820. v[7] = y + wy - hy + dy;
  99821. v[8] = z + wz - hz + dz;
  99822. //v4
  99823. v[9] = x + wx - hx - dx;
  99824. v[10] = y + wy - hy - dy;
  99825. v[11] = z + wz - hz - dz;
  99826. //v5
  99827. v[12] = x - wx + hx + dx;
  99828. v[13] = y - wy + hy + dy;
  99829. v[14] = z - wz + hz + dz;
  99830. //v6
  99831. v[15] = x - wx + hx - dx;
  99832. v[16] = y - wy + hy - dy;
  99833. v[17] = z - wz + hz - dz;
  99834. //v7
  99835. v[18] = x - wx - hx + dx;
  99836. v[19] = y - wy - hy + dy;
  99837. v[20] = z - wz - hz + dz;
  99838. //v8
  99839. v[21] = x - wx - hx - dx;
  99840. v[22] = y - wy - hy - dy;
  99841. v[23] = z - wz - hz - dz;
  99842. var w = di[9] < 0 ? -di[9] : di[9];
  99843. var h = di[10] < 0 ? -di[10] : di[10];
  99844. var d = di[11] < 0 ? -di[11] : di[11];
  99845. w = di[12] < 0 ? w - di[12] : w + di[12];
  99846. h = di[13] < 0 ? h - di[13] : h + di[13];
  99847. d = di[14] < 0 ? d - di[14] : d + di[14];
  99848. w = di[15] < 0 ? w - di[15] : w + di[15];
  99849. h = di[16] < 0 ? h - di[16] : h + di[16];
  99850. d = di[17] < 0 ? d - di[17] : d + di[17];
  99851. var p = OIMO.AABB_PROX;
  99852. this.aabb.set(
  99853. this.position.x - w - p, this.position.x + w + p,
  99854. this.position.y - h - p, this.position.y + h + p,
  99855. this.position.z - d - p, this.position.z + d + p
  99856. );
  99857. if (this.proxy != null) this.proxy.update();
  99858. };
  99859. /**
  99860. * A sphere shape.
  99861. * @author saharan
  99862. * @author lo-th
  99863. */
  99864. OIMO.SphereShape = function (config, radius) {
  99865. OIMO.Shape.call(this, config);
  99866. this.type = OIMO.SHAPE_SPHERE;
  99867. // The radius of the shape.
  99868. this.radius = radius;
  99869. };
  99870. OIMO.SphereShape.prototype = Object.create(OIMO.Shape.prototype);
  99871. OIMO.SphereShape.prototype.constructor = OIMO.SphereShape;
  99872. OIMO.SphereShape.prototype.calculateMassInfo = function (out) {
  99873. var mass = 1.333 * OIMO.PI * this.radius * this.radius * this.radius * this.density;
  99874. out.mass = mass;
  99875. var inertia = mass * this.radius * this.radius * 0.4;
  99876. out.inertia.set(inertia, 0, 0, 0, inertia, 0, 0, 0, inertia);
  99877. };
  99878. OIMO.SphereShape.prototype.updateProxy = function () {
  99879. var p = OIMO.AABB_PROX;
  99880. this.aabb.set(
  99881. this.position.x - this.radius - p, this.position.x + this.radius + p,
  99882. this.position.y - this.radius - p, this.position.y + this.radius + p,
  99883. this.position.z - this.radius - p, this.position.z + this.radius + p
  99884. );
  99885. if (this.proxy != null) this.proxy.update();
  99886. };
  99887. /**
  99888. * A cylinder shap.
  99889. * @author saharan
  99890. * @author lo-th
  99891. */
  99892. OIMO.CylinderShape = function (config, radius, height) {
  99893. OIMO.Shape.call(this, config);
  99894. this.type = OIMO.SHAPE_CYLINDER;
  99895. this.radius = radius;
  99896. this.height = height;
  99897. this.halfHeight = height * 0.5;
  99898. this.normalDirection = new OIMO.Vec3();
  99899. this.halfDirection = new OIMO.Vec3();
  99900. };
  99901. OIMO.CylinderShape.prototype = Object.create(OIMO.Shape.prototype);
  99902. OIMO.CylinderShape.prototype.constructor = OIMO.CylinderShape;
  99903. OIMO.CylinderShape.prototype.calculateMassInfo = function (out) {
  99904. var rsq = this.radius * this.radius;
  99905. var mass = OIMO.PI * rsq * this.height * this.density;
  99906. var inertiaXZ = ((0.25 * rsq) + (0.0833 * this.height * this.height)) * mass;
  99907. var inertiaY = 0.5 * rsq;
  99908. out.mass = mass;
  99909. out.inertia.set(inertiaXZ, 0, 0, 0, inertiaY, 0, 0, 0, inertiaXZ);
  99910. };
  99911. OIMO.CylinderShape.prototype.updateProxy = function () {
  99912. var te = this.rotation.elements;
  99913. var len, wx, hy, dz, xx, yy, zz, w, h, d, p;
  99914. xx = te[1] * te[1];
  99915. yy = te[4] * te[4];
  99916. zz = te[7] * te[7];
  99917. this.normalDirection.set(te[1], te[4], te[7]);
  99918. this.halfDirection.scale(this.normalDirection, this.halfHeight);
  99919. wx = 1 - xx;
  99920. len = OIMO.sqrt(wx * wx + xx * yy + xx * zz);
  99921. if (len > 0) len = this.radius / len;
  99922. wx *= len;
  99923. hy = 1 - yy;
  99924. len = OIMO.sqrt(yy * xx + hy * hy + yy * zz);
  99925. if (len > 0) len = this.radius / len;
  99926. hy *= len;
  99927. dz = 1 - zz;
  99928. len = OIMO.sqrt(zz * xx + zz * yy + dz * dz);
  99929. if (len > 0) len = this.radius / len;
  99930. dz *= len;
  99931. w = this.halfDirection.x < 0 ? -this.halfDirection.x : this.halfDirection.x;
  99932. h = this.halfDirection.y < 0 ? -this.halfDirection.y : this.halfDirection.y;
  99933. d = this.halfDirection.z < 0 ? -this.halfDirection.z : this.halfDirection.z;
  99934. w = wx < 0 ? w - wx : w + wx;
  99935. h = hy < 0 ? h - hy : h + hy;
  99936. d = dz < 0 ? d - dz : d + dz;
  99937. p = OIMO.AABB_PROX;
  99938. this.aabb.set(
  99939. this.position.x - w - p, this.position.x + w + p,
  99940. this.position.y - h - p, this.position.y + h + p,
  99941. this.position.z - d - p, this.position.z + d + p
  99942. );
  99943. if (this.proxy != null) this.proxy.update();
  99944. };
  99945. /**
  99946. * A tetra shape.
  99947. * @author xprogram
  99948. */
  99949. OIMO.TetraShape = function (config, p1, p2, p3, p4) {
  99950. OIMO.Shape.call(this, config);
  99951. this.type = OIMO.SHAPE_TETRA;
  99952. // Vertices and faces of tetra
  99953. this.verts = [p1, p2, p3, p4];
  99954. this.faces = [
  99955. mtri(0, 1, 2),
  99956. mtri(1, 2, 3),
  99957. mtri(2, 3, 4),
  99958. mtri(4, 0, 1),
  99959. ];
  99960. };
  99961. OIMO.TetraShape.prototype = Object.create(OIMO.Shape.prototype);
  99962. OIMO.TetraShape.prototype.constructor = OIMO.TetraShape;
  99963. OIMO.TetraShape.prototype.calculateMassInfo = function () {
  99964. // I guess you could calculate box mass and split it
  99965. // in half for the tetra...
  99966. };
  99967. OIMO.TetraShape.prototype.updateProxy = function () {
  99968. this.aabb.setFromPoints(this.verts);
  99969. if (this.proxy !== null)
  99970. this.proxy.update();
  99971. };
  99972. function mtri(a, b, c) {
  99973. return { a: a, b: b, c: c };
  99974. }
  99975. OIMO.CollisionDetector = function () {
  99976. this.flip = false;
  99977. };
  99978. OIMO.CollisionDetector.prototype = {
  99979. constructor: OIMO.CollisionDetector,
  99980. detectCollision: function (shape1, shape2, manifold) {
  99981. OIMO.Error("CollisionDetector", "Inheritance error.");
  99982. }
  99983. };
  99984. /**
  99985. * A collision detector which detects collisions between two boxes.
  99986. * @author saharan
  99987. */
  99988. OIMO.BoxBoxCollisionDetector = function () {
  99989. OIMO.CollisionDetector.call(this);
  99990. this.clipVertices1 = new OIMO_ARRAY_TYPE(24); // 8 vertices x,y,z
  99991. this.clipVertices2 = new OIMO_ARRAY_TYPE(24);
  99992. this.used = new OIMO_ARRAY_TYPE(8);
  99993. this.INF = 1 / 0;
  99994. };
  99995. OIMO.BoxBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  99996. OIMO.BoxBoxCollisionDetector.prototype.constructor = OIMO.BoxBoxCollisionDetector;
  99997. OIMO.BoxBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  99998. // What you are doing
  99999. // · I to prepare a separate axis of the fifteen
  100000. //-Six in each of three normal vectors of the xyz direction of the box both
  100001. // · Remaining nine 3x3 a vector perpendicular to the side of the box 2 and the side of the box 1
  100002. // · Calculate the depth to the separation axis
  100003. // Calculates the distance using the inner product and put the amount of embedment
  100004. // · However a vertical separation axis and side to weight a little to avoid vibration
  100005. // And end when there is a separate axis that is remote even one
  100006. // · I look for separation axis with little to dent most
  100007. // Men and if separation axis of the first six - end collision
  100008. // Heng If it separate axis of nine other - side collision
  100009. // Heng - case of a side collision
  100010. // · Find points of two sides on which you made ​​the separation axis
  100011. // Calculates the point of closest approach of a straight line consisting of separate axis points obtained, and the collision point
  100012. //-Surface - the case of the plane crash
  100013. //-Box A, box B and the other a box of better made ​​a separate axis
  100014. // • 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
  100015. // When viewed from the front surface A, and the cut part exceeding the area of the surface A is a surface B
  100016. //-Plane B becomes the 3-8 triangle, I a candidate for the collision point the vertex of surface B
  100017. // • If more than one candidate 5 exists, scraping up to four
  100018. // For potential collision points of all, to examine the distance between the surface A
  100019. // • If you were on the inside surface of A, and the collision point
  100020. var b1;
  100021. var b2;
  100022. if (shape1.id < shape2.id) {
  100023. b1 = (shape1);
  100024. b2 = (shape2);
  100025. } else {
  100026. b1 = (shape2);
  100027. b2 = (shape1);
  100028. }
  100029. var V1 = b1.elements;
  100030. var V2 = b2.elements;
  100031. var D1 = b1.dimentions;
  100032. var D2 = b2.dimentions;
  100033. var p1 = b1.position;
  100034. var p2 = b2.position;
  100035. var p1x = p1.x;
  100036. var p1y = p1.y;
  100037. var p1z = p1.z;
  100038. var p2x = p2.x;
  100039. var p2y = p2.y;
  100040. var p2z = p2.z;
  100041. // diff
  100042. var dx = p2x - p1x;
  100043. var dy = p2y - p1y;
  100044. var dz = p2z - p1z;
  100045. // distance
  100046. var w1 = b1.halfWidth;
  100047. var h1 = b1.halfHeight;
  100048. var d1 = b1.halfDepth;
  100049. var w2 = b2.halfWidth;
  100050. var h2 = b2.halfHeight;
  100051. var d2 = b2.halfDepth;
  100052. // direction
  100053. // ----------------------------
  100054. // 15 separating axes
  100055. // 1~6: face
  100056. // 7~f: edge
  100057. // http://marupeke296.com/COL_3D_No13_OBBvsOBB.html
  100058. // ----------------------------
  100059. var a1x = D1[0];
  100060. var a1y = D1[1];
  100061. var a1z = D1[2];
  100062. var a2x = D1[3];
  100063. var a2y = D1[4];
  100064. var a2z = D1[5];
  100065. var a3x = D1[6];
  100066. var a3y = D1[7];
  100067. var a3z = D1[8];
  100068. var d1x = D1[9];
  100069. var d1y = D1[10];
  100070. var d1z = D1[11];
  100071. var d2x = D1[12];
  100072. var d2y = D1[13];
  100073. var d2z = D1[14];
  100074. var d3x = D1[15];
  100075. var d3y = D1[16];
  100076. var d3z = D1[17];
  100077. var a4x = D2[0];
  100078. var a4y = D2[1];
  100079. var a4z = D2[2];
  100080. var a5x = D2[3];
  100081. var a5y = D2[4];
  100082. var a5z = D2[5];
  100083. var a6x = D2[6];
  100084. var a6y = D2[7];
  100085. var a6z = D2[8];
  100086. var d4x = D2[9];
  100087. var d4y = D2[10];
  100088. var d4z = D2[11];
  100089. var d5x = D2[12];
  100090. var d5y = D2[13];
  100091. var d5z = D2[14];
  100092. var d6x = D2[15];
  100093. var d6y = D2[16];
  100094. var d6z = D2[17];
  100095. var a7x = a1y * a4z - a1z * a4y;
  100096. var a7y = a1z * a4x - a1x * a4z;
  100097. var a7z = a1x * a4y - a1y * a4x;
  100098. var a8x = a1y * a5z - a1z * a5y;
  100099. var a8y = a1z * a5x - a1x * a5z;
  100100. var a8z = a1x * a5y - a1y * a5x;
  100101. var a9x = a1y * a6z - a1z * a6y;
  100102. var a9y = a1z * a6x - a1x * a6z;
  100103. var a9z = a1x * a6y - a1y * a6x;
  100104. var aax = a2y * a4z - a2z * a4y;
  100105. var aay = a2z * a4x - a2x * a4z;
  100106. var aaz = a2x * a4y - a2y * a4x;
  100107. var abx = a2y * a5z - a2z * a5y;
  100108. var aby = a2z * a5x - a2x * a5z;
  100109. var abz = a2x * a5y - a2y * a5x;
  100110. var acx = a2y * a6z - a2z * a6y;
  100111. var acy = a2z * a6x - a2x * a6z;
  100112. var acz = a2x * a6y - a2y * a6x;
  100113. var adx = a3y * a4z - a3z * a4y;
  100114. var ady = a3z * a4x - a3x * a4z;
  100115. var adz = a3x * a4y - a3y * a4x;
  100116. var aex = a3y * a5z - a3z * a5y;
  100117. var aey = a3z * a5x - a3x * a5z;
  100118. var aez = a3x * a5y - a3y * a5x;
  100119. var afx = a3y * a6z - a3z * a6y;
  100120. var afy = a3z * a6x - a3x * a6z;
  100121. var afz = a3x * a6y - a3y * a6x;
  100122. // right or left flags
  100123. var right1;
  100124. var right2;
  100125. var right3;
  100126. var right4;
  100127. var right5;
  100128. var right6;
  100129. var right7;
  100130. var right8;
  100131. var right9;
  100132. var righta;
  100133. var rightb;
  100134. var rightc;
  100135. var rightd;
  100136. var righte;
  100137. var rightf;
  100138. // overlapping distances
  100139. var overlap1;
  100140. var overlap2;
  100141. var overlap3;
  100142. var overlap4;
  100143. var overlap5;
  100144. var overlap6;
  100145. var overlap7;
  100146. var overlap8;
  100147. var overlap9;
  100148. var overlapa;
  100149. var overlapb;
  100150. var overlapc;
  100151. var overlapd;
  100152. var overlape;
  100153. var overlapf;
  100154. // invalid flags
  100155. var invalid7 = false;
  100156. var invalid8 = false;
  100157. var invalid9 = false;
  100158. var invalida = false;
  100159. var invalidb = false;
  100160. var invalidc = false;
  100161. var invalidd = false;
  100162. var invalide = false;
  100163. var invalidf = false;
  100164. // temporary variables
  100165. var len;
  100166. var len1;
  100167. var len2;
  100168. var dot1;
  100169. var dot2;
  100170. var dot3;
  100171. // try axis 1
  100172. len = a1x * dx + a1y * dy + a1z * dz;
  100173. right1 = len > 0;
  100174. if (!right1) len = -len;
  100175. len1 = w1;
  100176. dot1 = a1x * a4x + a1y * a4y + a1z * a4z;
  100177. dot2 = a1x * a5x + a1y * a5y + a1z * a5z;
  100178. dot3 = a1x * a6x + a1y * a6y + a1z * a6z;
  100179. if (dot1 < 0) dot1 = -dot1;
  100180. if (dot2 < 0) dot2 = -dot2;
  100181. if (dot3 < 0) dot3 = -dot3;
  100182. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  100183. overlap1 = len - len1 - len2;
  100184. if (overlap1 > 0) return;
  100185. // try axis 2
  100186. len = a2x * dx + a2y * dy + a2z * dz;
  100187. right2 = len > 0;
  100188. if (!right2) len = -len;
  100189. len1 = h1;
  100190. dot1 = a2x * a4x + a2y * a4y + a2z * a4z;
  100191. dot2 = a2x * a5x + a2y * a5y + a2z * a5z;
  100192. dot3 = a2x * a6x + a2y * a6y + a2z * a6z;
  100193. if (dot1 < 0) dot1 = -dot1;
  100194. if (dot2 < 0) dot2 = -dot2;
  100195. if (dot3 < 0) dot3 = -dot3;
  100196. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  100197. overlap2 = len - len1 - len2;
  100198. if (overlap2 > 0) return;
  100199. // try axis 3
  100200. len = a3x * dx + a3y * dy + a3z * dz;
  100201. right3 = len > 0;
  100202. if (!right3) len = -len;
  100203. len1 = d1;
  100204. dot1 = a3x * a4x + a3y * a4y + a3z * a4z;
  100205. dot2 = a3x * a5x + a3y * a5y + a3z * a5z;
  100206. dot3 = a3x * a6x + a3y * a6y + a3z * a6z;
  100207. if (dot1 < 0) dot1 = -dot1;
  100208. if (dot2 < 0) dot2 = -dot2;
  100209. if (dot3 < 0) dot3 = -dot3;
  100210. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  100211. overlap3 = len - len1 - len2;
  100212. if (overlap3 > 0) return;
  100213. // try axis 4
  100214. len = a4x * dx + a4y * dy + a4z * dz;
  100215. right4 = len > 0;
  100216. if (!right4) len = -len;
  100217. dot1 = a4x * a1x + a4y * a1y + a4z * a1z;
  100218. dot2 = a4x * a2x + a4y * a2y + a4z * a2z;
  100219. dot3 = a4x * a3x + a4y * a3y + a4z * a3z;
  100220. if (dot1 < 0) dot1 = -dot1;
  100221. if (dot2 < 0) dot2 = -dot2;
  100222. if (dot3 < 0) dot3 = -dot3;
  100223. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  100224. len2 = w2;
  100225. overlap4 = (len - len1 - len2) * 1.0;
  100226. if (overlap4 > 0) return;
  100227. // try axis 5
  100228. len = a5x * dx + a5y * dy + a5z * dz;
  100229. right5 = len > 0;
  100230. if (!right5) len = -len;
  100231. dot1 = a5x * a1x + a5y * a1y + a5z * a1z;
  100232. dot2 = a5x * a2x + a5y * a2y + a5z * a2z;
  100233. dot3 = a5x * a3x + a5y * a3y + a5z * a3z;
  100234. if (dot1 < 0) dot1 = -dot1;
  100235. if (dot2 < 0) dot2 = -dot2;
  100236. if (dot3 < 0) dot3 = -dot3;
  100237. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  100238. len2 = h2;
  100239. overlap5 = (len - len1 - len2) * 1.0;
  100240. if (overlap5 > 0) return;
  100241. // try axis 6
  100242. len = a6x * dx + a6y * dy + a6z * dz;
  100243. right6 = len > 0;
  100244. if (!right6) len = -len;
  100245. dot1 = a6x * a1x + a6y * a1y + a6z * a1z;
  100246. dot2 = a6x * a2x + a6y * a2y + a6z * a2z;
  100247. dot3 = a6x * a3x + a6y * a3y + a6z * a3z;
  100248. if (dot1 < 0) dot1 = -dot1;
  100249. if (dot2 < 0) dot2 = -dot2;
  100250. if (dot3 < 0) dot3 = -dot3;
  100251. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  100252. len2 = d2;
  100253. overlap6 = (len - len1 - len2) * 1.0;
  100254. if (overlap6 > 0) return;
  100255. // try axis 7
  100256. len = a7x * a7x + a7y * a7y + a7z * a7z;
  100257. if (len > 1e-5) {
  100258. len = 1 / OIMO.sqrt(len);
  100259. a7x *= len;
  100260. a7y *= len;
  100261. a7z *= len;
  100262. len = a7x * dx + a7y * dy + a7z * dz;
  100263. right7 = len > 0;
  100264. if (!right7) len = -len;
  100265. dot1 = a7x * a2x + a7y * a2y + a7z * a2z;
  100266. dot2 = a7x * a3x + a7y * a3y + a7z * a3z;
  100267. if (dot1 < 0) dot1 = -dot1;
  100268. if (dot2 < 0) dot2 = -dot2;
  100269. len1 = dot1 * h1 + dot2 * d1;
  100270. dot1 = a7x * a5x + a7y * a5y + a7z * a5z;
  100271. dot2 = a7x * a6x + a7y * a6y + a7z * a6z;
  100272. if (dot1 < 0) dot1 = -dot1;
  100273. if (dot2 < 0) dot2 = -dot2;
  100274. len2 = dot1 * h2 + dot2 * d2;
  100275. overlap7 = len - len1 - len2;
  100276. if (overlap7 > 0) return;
  100277. } else {
  100278. right7 = false;
  100279. overlap7 = 0;
  100280. invalid7 = true;
  100281. }
  100282. // try axis 8
  100283. len = a8x * a8x + a8y * a8y + a8z * a8z;
  100284. if (len > 1e-5) {
  100285. len = 1 / OIMO.sqrt(len);
  100286. a8x *= len;
  100287. a8y *= len;
  100288. a8z *= len;
  100289. len = a8x * dx + a8y * dy + a8z * dz;
  100290. right8 = len > 0;
  100291. if (!right8) len = -len;
  100292. dot1 = a8x * a2x + a8y * a2y + a8z * a2z;
  100293. dot2 = a8x * a3x + a8y * a3y + a8z * a3z;
  100294. if (dot1 < 0) dot1 = -dot1;
  100295. if (dot2 < 0) dot2 = -dot2;
  100296. len1 = dot1 * h1 + dot2 * d1;
  100297. dot1 = a8x * a4x + a8y * a4y + a8z * a4z;
  100298. dot2 = a8x * a6x + a8y * a6y + a8z * a6z;
  100299. if (dot1 < 0) dot1 = -dot1;
  100300. if (dot2 < 0) dot2 = -dot2;
  100301. len2 = dot1 * w2 + dot2 * d2;
  100302. overlap8 = len - len1 - len2;
  100303. if (overlap8 > 0) return;
  100304. } else {
  100305. right8 = false;
  100306. overlap8 = 0;
  100307. invalid8 = true;
  100308. }
  100309. // try axis 9
  100310. len = a9x * a9x + a9y * a9y + a9z * a9z;
  100311. if (len > 1e-5) {
  100312. len = 1 / OIMO.sqrt(len);
  100313. a9x *= len;
  100314. a9y *= len;
  100315. a9z *= len;
  100316. len = a9x * dx + a9y * dy + a9z * dz;
  100317. right9 = len > 0;
  100318. if (!right9) len = -len;
  100319. dot1 = a9x * a2x + a9y * a2y + a9z * a2z;
  100320. dot2 = a9x * a3x + a9y * a3y + a9z * a3z;
  100321. if (dot1 < 0) dot1 = -dot1;
  100322. if (dot2 < 0) dot2 = -dot2;
  100323. len1 = dot1 * h1 + dot2 * d1;
  100324. dot1 = a9x * a4x + a9y * a4y + a9z * a4z;
  100325. dot2 = a9x * a5x + a9y * a5y + a9z * a5z;
  100326. if (dot1 < 0) dot1 = -dot1;
  100327. if (dot2 < 0) dot2 = -dot2;
  100328. len2 = dot1 * w2 + dot2 * h2;
  100329. overlap9 = len - len1 - len2;
  100330. if (overlap9 > 0) return;
  100331. } else {
  100332. right9 = false;
  100333. overlap9 = 0;
  100334. invalid9 = true;
  100335. }
  100336. // try axis 10
  100337. len = aax * aax + aay * aay + aaz * aaz;
  100338. if (len > 1e-5) {
  100339. len = 1 / OIMO.sqrt(len);
  100340. aax *= len;
  100341. aay *= len;
  100342. aaz *= len;
  100343. len = aax * dx + aay * dy + aaz * dz;
  100344. righta = len > 0;
  100345. if (!righta) len = -len;
  100346. dot1 = aax * a1x + aay * a1y + aaz * a1z;
  100347. dot2 = aax * a3x + aay * a3y + aaz * a3z;
  100348. if (dot1 < 0) dot1 = -dot1;
  100349. if (dot2 < 0) dot2 = -dot2;
  100350. len1 = dot1 * w1 + dot2 * d1;
  100351. dot1 = aax * a5x + aay * a5y + aaz * a5z;
  100352. dot2 = aax * a6x + aay * a6y + aaz * a6z;
  100353. if (dot1 < 0) dot1 = -dot1;
  100354. if (dot2 < 0) dot2 = -dot2;
  100355. len2 = dot1 * h2 + dot2 * d2;
  100356. overlapa = len - len1 - len2;
  100357. if (overlapa > 0) return;
  100358. } else {
  100359. righta = false;
  100360. overlapa = 0;
  100361. invalida = true;
  100362. }
  100363. // try axis 11
  100364. len = abx * abx + aby * aby + abz * abz;
  100365. if (len > 1e-5) {
  100366. len = 1 / OIMO.sqrt(len);
  100367. abx *= len;
  100368. aby *= len;
  100369. abz *= len;
  100370. len = abx * dx + aby * dy + abz * dz;
  100371. rightb = len > 0;
  100372. if (!rightb) len = -len;
  100373. dot1 = abx * a1x + aby * a1y + abz * a1z;
  100374. dot2 = abx * a3x + aby * a3y + abz * a3z;
  100375. if (dot1 < 0) dot1 = -dot1;
  100376. if (dot2 < 0) dot2 = -dot2;
  100377. len1 = dot1 * w1 + dot2 * d1;
  100378. dot1 = abx * a4x + aby * a4y + abz * a4z;
  100379. dot2 = abx * a6x + aby * a6y + abz * a6z;
  100380. if (dot1 < 0) dot1 = -dot1;
  100381. if (dot2 < 0) dot2 = -dot2;
  100382. len2 = dot1 * w2 + dot2 * d2;
  100383. overlapb = len - len1 - len2;
  100384. if (overlapb > 0) return;
  100385. } else {
  100386. rightb = false;
  100387. overlapb = 0;
  100388. invalidb = true;
  100389. }
  100390. // try axis 12
  100391. len = acx * acx + acy * acy + acz * acz;
  100392. if (len > 1e-5) {
  100393. len = 1 / OIMO.sqrt(len);
  100394. acx *= len;
  100395. acy *= len;
  100396. acz *= len;
  100397. len = acx * dx + acy * dy + acz * dz;
  100398. rightc = len > 0;
  100399. if (!rightc) len = -len;
  100400. dot1 = acx * a1x + acy * a1y + acz * a1z;
  100401. dot2 = acx * a3x + acy * a3y + acz * a3z;
  100402. if (dot1 < 0) dot1 = -dot1;
  100403. if (dot2 < 0) dot2 = -dot2;
  100404. len1 = dot1 * w1 + dot2 * d1;
  100405. dot1 = acx * a4x + acy * a4y + acz * a4z;
  100406. dot2 = acx * a5x + acy * a5y + acz * a5z;
  100407. if (dot1 < 0) dot1 = -dot1;
  100408. if (dot2 < 0) dot2 = -dot2;
  100409. len2 = dot1 * w2 + dot2 * h2;
  100410. overlapc = len - len1 - len2;
  100411. if (overlapc > 0) return;
  100412. } else {
  100413. rightc = false;
  100414. overlapc = 0;
  100415. invalidc = true;
  100416. }
  100417. // try axis 13
  100418. len = adx * adx + ady * ady + adz * adz;
  100419. if (len > 1e-5) {
  100420. len = 1 / OIMO.sqrt(len);
  100421. adx *= len;
  100422. ady *= len;
  100423. adz *= len;
  100424. len = adx * dx + ady * dy + adz * dz;
  100425. rightd = len > 0;
  100426. if (!rightd) len = -len;
  100427. dot1 = adx * a1x + ady * a1y + adz * a1z;
  100428. dot2 = adx * a2x + ady * a2y + adz * a2z;
  100429. if (dot1 < 0) dot1 = -dot1;
  100430. if (dot2 < 0) dot2 = -dot2;
  100431. len1 = dot1 * w1 + dot2 * h1;
  100432. dot1 = adx * a5x + ady * a5y + adz * a5z;
  100433. dot2 = adx * a6x + ady * a6y + adz * a6z;
  100434. if (dot1 < 0) dot1 = -dot1;
  100435. if (dot2 < 0) dot2 = -dot2;
  100436. len2 = dot1 * h2 + dot2 * d2;
  100437. overlapd = len - len1 - len2;
  100438. if (overlapd > 0) return;
  100439. } else {
  100440. rightd = false;
  100441. overlapd = 0;
  100442. invalidd = true;
  100443. }
  100444. // try axis 14
  100445. len = aex * aex + aey * aey + aez * aez;
  100446. if (len > 1e-5) {
  100447. len = 1 / OIMO.sqrt(len);
  100448. aex *= len;
  100449. aey *= len;
  100450. aez *= len;
  100451. len = aex * dx + aey * dy + aez * dz;
  100452. righte = len > 0;
  100453. if (!righte) len = -len;
  100454. dot1 = aex * a1x + aey * a1y + aez * a1z;
  100455. dot2 = aex * a2x + aey * a2y + aez * a2z;
  100456. if (dot1 < 0) dot1 = -dot1;
  100457. if (dot2 < 0) dot2 = -dot2;
  100458. len1 = dot1 * w1 + dot2 * h1;
  100459. dot1 = aex * a4x + aey * a4y + aez * a4z;
  100460. dot2 = aex * a6x + aey * a6y + aez * a6z;
  100461. if (dot1 < 0) dot1 = -dot1;
  100462. if (dot2 < 0) dot2 = -dot2;
  100463. len2 = dot1 * w2 + dot2 * d2;
  100464. overlape = len - len1 - len2;
  100465. if (overlape > 0) return;
  100466. } else {
  100467. righte = false;
  100468. overlape = 0;
  100469. invalide = true;
  100470. }
  100471. // try axis 15
  100472. len = afx * afx + afy * afy + afz * afz;
  100473. if (len > 1e-5) {
  100474. len = 1 / OIMO.sqrt(len);
  100475. afx *= len;
  100476. afy *= len;
  100477. afz *= len;
  100478. len = afx * dx + afy * dy + afz * dz;
  100479. rightf = len > 0;
  100480. if (!rightf) len = -len;
  100481. dot1 = afx * a1x + afy * a1y + afz * a1z;
  100482. dot2 = afx * a2x + afy * a2y + afz * a2z;
  100483. if (dot1 < 0) dot1 = -dot1;
  100484. if (dot2 < 0) dot2 = -dot2;
  100485. len1 = dot1 * w1 + dot2 * h1;
  100486. dot1 = afx * a4x + afy * a4y + afz * a4z;
  100487. dot2 = afx * a5x + afy * a5y + afz * a5z;
  100488. if (dot1 < 0) dot1 = -dot1;
  100489. if (dot2 < 0) dot2 = -dot2;
  100490. len2 = dot1 * w2 + dot2 * h2;
  100491. overlapf = len - len1 - len2;
  100492. if (overlapf > 0) return;
  100493. } else {
  100494. rightf = false;
  100495. overlapf = 0;
  100496. invalidf = true;
  100497. }
  100498. // boxes are overlapping
  100499. var depth = overlap1;
  100500. var depth2 = overlap1;
  100501. var minIndex = 0;
  100502. var right = right1;
  100503. if (overlap2 > depth2) {
  100504. depth = overlap2;
  100505. depth2 = overlap2;
  100506. minIndex = 1;
  100507. right = right2;
  100508. }
  100509. if (overlap3 > depth2) {
  100510. depth = overlap3;
  100511. depth2 = overlap3;
  100512. minIndex = 2;
  100513. right = right3;
  100514. }
  100515. if (overlap4 > depth2) {
  100516. depth = overlap4;
  100517. depth2 = overlap4;
  100518. minIndex = 3;
  100519. right = right4;
  100520. }
  100521. if (overlap5 > depth2) {
  100522. depth = overlap5;
  100523. depth2 = overlap5;
  100524. minIndex = 4;
  100525. right = right5;
  100526. }
  100527. if (overlap6 > depth2) {
  100528. depth = overlap6;
  100529. depth2 = overlap6;
  100530. minIndex = 5;
  100531. right = right6;
  100532. }
  100533. if (overlap7 - 0.01 > depth2 && !invalid7) {
  100534. depth = overlap7;
  100535. depth2 = overlap7 - 0.01;
  100536. minIndex = 6;
  100537. right = right7;
  100538. }
  100539. if (overlap8 - 0.01 > depth2 && !invalid8) {
  100540. depth = overlap8;
  100541. depth2 = overlap8 - 0.01;
  100542. minIndex = 7;
  100543. right = right8;
  100544. }
  100545. if (overlap9 - 0.01 > depth2 && !invalid9) {
  100546. depth = overlap9;
  100547. depth2 = overlap9 - 0.01;
  100548. minIndex = 8;
  100549. right = right9;
  100550. }
  100551. if (overlapa - 0.01 > depth2 && !invalida) {
  100552. depth = overlapa;
  100553. depth2 = overlapa - 0.01;
  100554. minIndex = 9;
  100555. right = righta;
  100556. }
  100557. if (overlapb - 0.01 > depth2 && !invalidb) {
  100558. depth = overlapb;
  100559. depth2 = overlapb - 0.01;
  100560. minIndex = 10;
  100561. right = rightb;
  100562. }
  100563. if (overlapc - 0.01 > depth2 && !invalidc) {
  100564. depth = overlapc;
  100565. depth2 = overlapc - 0.01;
  100566. minIndex = 11;
  100567. right = rightc;
  100568. }
  100569. if (overlapd - 0.01 > depth2 && !invalidd) {
  100570. depth = overlapd;
  100571. depth2 = overlapd - 0.01;
  100572. minIndex = 12;
  100573. right = rightd;
  100574. }
  100575. if (overlape - 0.01 > depth2 && !invalide) {
  100576. depth = overlape;
  100577. depth2 = overlape - 0.01;
  100578. minIndex = 13;
  100579. right = righte;
  100580. }
  100581. if (overlapf - 0.01 > depth2 && !invalidf) {
  100582. depth = overlapf;
  100583. minIndex = 14;
  100584. right = rightf;
  100585. }
  100586. // normal
  100587. var nx = 0;
  100588. var ny = 0;
  100589. var nz = 0;
  100590. // edge line or face side normal
  100591. var n1x = 0;
  100592. var n1y = 0;
  100593. var n1z = 0;
  100594. var n2x = 0;
  100595. var n2y = 0;
  100596. var n2z = 0;
  100597. // center of current face
  100598. var cx = 0;
  100599. var cy = 0;
  100600. var cz = 0;
  100601. // face side
  100602. var s1x = 0;
  100603. var s1y = 0;
  100604. var s1z = 0;
  100605. var s2x = 0;
  100606. var s2y = 0;
  100607. var s2z = 0;
  100608. // swap b1 b2
  100609. var swap = false;
  100610. //_______________________________________
  100611. if (minIndex == 0) {// b1.x * b2
  100612. if (right) {
  100613. cx = p1x + d1x; cy = p1y + d1y; cz = p1z + d1z;
  100614. nx = a1x; ny = a1y; nz = a1z;
  100615. } else {
  100616. cx = p1x - d1x; cy = p1y - d1y; cz = p1z - d1z;
  100617. nx = -a1x; ny = -a1y; nz = -a1z;
  100618. }
  100619. s1x = d2x; s1y = d2y; s1z = d2z;
  100620. n1x = -a2x; n1y = -a2y; n1z = -a2z;
  100621. s2x = d3x; s2y = d3y; s2z = d3z;
  100622. n2x = -a3x; n2y = -a3y; n2z = -a3z;
  100623. }
  100624. else if (minIndex == 1) {// b1.y * b2
  100625. if (right) {
  100626. cx = p1x + d2x; cy = p1y + d2y; cz = p1z + d2z;
  100627. nx = a2x; ny = a2y; nz = a2z;
  100628. } else {
  100629. cx = p1x - d2x; cy = p1y - d2y; cz = p1z - d2z;
  100630. nx = -a2x; ny = -a2y; nz = -a2z;
  100631. }
  100632. s1x = d1x; s1y = d1y; s1z = d1z;
  100633. n1x = -a1x; n1y = -a1y; n1z = -a1z;
  100634. s2x = d3x; s2y = d3y; s2z = d3z;
  100635. n2x = -a3x; n2y = -a3y; n2z = -a3z;
  100636. }
  100637. else if (minIndex == 2) {// b1.z * b2
  100638. if (right) {
  100639. cx = p1x + d3x; cy = p1y + d3y; cz = p1z + d3z;
  100640. nx = a3x; ny = a3y; nz = a3z;
  100641. } else {
  100642. cx = p1x - d3x; cy = p1y - d3y; cz = p1z - d3z;
  100643. nx = -a3x; ny = -a3y; nz = -a3z;
  100644. }
  100645. s1x = d1x; s1y = d1y; s1z = d1z;
  100646. n1x = -a1x; n1y = -a1y; n1z = -a1z;
  100647. s2x = d2x; s2y = d2y; s2z = d2z;
  100648. n2x = -a2x; n2y = -a2y; n2z = -a2z;
  100649. }
  100650. else if (minIndex == 3) {// b2.x * b1
  100651. swap = true;
  100652. if (!right) {
  100653. cx = p2x + d4x; cy = p2y + d4y; cz = p2z + d4z;
  100654. nx = a4x; ny = a4y; nz = a4z;
  100655. } else {
  100656. cx = p2x - d4x; cy = p2y - d4y; cz = p2z - d4z;
  100657. nx = -a4x; ny = -a4y; nz = -a4z;
  100658. }
  100659. s1x = d5x; s1y = d5y; s1z = d5z;
  100660. n1x = -a5x; n1y = -a5y; n1z = -a5z;
  100661. s2x = d6x; s2y = d6y; s2z = d6z;
  100662. n2x = -a6x; n2y = -a6y; n2z = -a6z;
  100663. }
  100664. else if (minIndex == 4) {// b2.y * b1
  100665. swap = true;
  100666. if (!right) {
  100667. cx = p2x + d5x; cy = p2y + d5y; cz = p2z + d5z;
  100668. nx = a5x; ny = a5y; nz = a5z;
  100669. } else {
  100670. cx = p2x - d5x; cy = p2y - d5y; cz = p2z - d5z;
  100671. nx = -a5x; ny = -a5y; nz = -a5z;
  100672. }
  100673. s1x = d4x; s1y = d4y; s1z = d4z;
  100674. n1x = -a4x; n1y = -a4y; n1z = -a4z;
  100675. s2x = d6x; s2y = d6y; s2z = d6z;
  100676. n2x = -a6x; n2y = -a6y; n2z = -a6z;
  100677. }
  100678. else if (minIndex == 5) {// b2.z * b1
  100679. swap = true;
  100680. if (!right) {
  100681. cx = p2x + d6x; cy = p2y + d6y; cz = p2z + d6z;
  100682. nx = a6x; ny = a6y; nz = a6z;
  100683. } else {
  100684. cx = p2x - d6x; cy = p2y - d6y; cz = p2z - d6z;
  100685. nx = -a6x; ny = -a6y; nz = -a6z;
  100686. }
  100687. s1x = d4x; s1y = d4y; s1z = d4z;
  100688. n1x = -a4x; n1y = -a4y; n1z = -a4z;
  100689. s2x = d5x; s2y = d5y; s2z = d5z;
  100690. n2x = -a5x; n2y = -a5y; n2z = -a5z;
  100691. }
  100692. else if (minIndex == 6) {// b1.x * b2.x
  100693. nx = a7x; ny = a7y; nz = a7z;
  100694. n1x = a1x; n1y = a1y; n1z = a1z;
  100695. n2x = a4x; n2y = a4y; n2z = a4z;
  100696. }
  100697. else if (minIndex == 7) {// b1.x * b2.y
  100698. nx = a8x; ny = a8y; nz = a8z;
  100699. n1x = a1x; n1y = a1y; n1z = a1z;
  100700. n2x = a5x; n2y = a5y; n2z = a5z;
  100701. }
  100702. else if (minIndex == 8) {// b1.x * b2.z
  100703. nx = a9x; ny = a9y; nz = a9z;
  100704. n1x = a1x; n1y = a1y; n1z = a1z;
  100705. n2x = a6x; n2y = a6y; n2z = a6z;
  100706. }
  100707. else if (minIndex == 9) {// b1.y * b2.x
  100708. nx = aax; ny = aay; nz = aaz;
  100709. n1x = a2x; n1y = a2y; n1z = a2z;
  100710. n2x = a4x; n2y = a4y; n2z = a4z
  100711. }
  100712. else if (minIndex == 10) {// b1.y * b2.y
  100713. nx = abx; ny = aby; nz = abz;
  100714. n1x = a2x; n1y = a2y; n1z = a2z;
  100715. n2x = a5x; n2y = a5y; n2z = a5z;
  100716. }
  100717. else if (minIndex == 11) {// b1.y * b2.z
  100718. nx = acx; ny = acy; nz = acz;
  100719. n1x = a2x; n1y = a2y; n1z = a2z;
  100720. n2x = a6x; n2y = a6y; n2z = a6z;
  100721. }
  100722. else if (minIndex == 12) {// b1.z * b2.x
  100723. nx = adx; ny = ady; nz = adz;
  100724. n1x = a3x; n1y = a3y; n1z = a3z;
  100725. n2x = a4x; n2y = a4y; n2z = a4z;
  100726. }
  100727. else if (minIndex == 13) {// b1.z * b2.y
  100728. nx = aex; ny = aey; nz = aez;
  100729. n1x = a3x; n1y = a3y; n1z = a3z;
  100730. n2x = a5x; n2y = a5y; n2z = a5z;
  100731. }
  100732. else if (minIndex == 14) {// b1.z * b2.z
  100733. nx = afx; ny = afy; nz = afz;
  100734. n1x = a3x; n1y = a3y; n1z = a3z;
  100735. n2x = a6x; n2y = a6y; n2z = a6z;
  100736. }
  100737. //__________________________________________
  100738. var v;
  100739. if (minIndex > 5) {
  100740. if (!right) {
  100741. nx = -nx; ny = -ny; nz = -nz;
  100742. }
  100743. var distance;
  100744. var maxDistance;
  100745. var vx;
  100746. var vy;
  100747. var vz;
  100748. var v1x;
  100749. var v1y;
  100750. var v1z;
  100751. var v2x;
  100752. var v2y;
  100753. var v2z;
  100754. //vertex1;
  100755. v1x = V1[0]; v1y = V1[1]; v1z = V1[2];
  100756. maxDistance = nx * v1x + ny * v1y + nz * v1z;
  100757. //vertex2;
  100758. vx = V1[3]; vy = V1[4]; vz = V1[5];
  100759. distance = nx * vx + ny * vy + nz * vz;
  100760. if (distance > maxDistance) {
  100761. maxDistance = distance;
  100762. v1x = vx; v1y = vy; v1z = vz;
  100763. }
  100764. //vertex3;
  100765. vx = V1[6]; vy = V1[7]; vz = V1[8];
  100766. distance = nx * vx + ny * vy + nz * vz;
  100767. if (distance > maxDistance) {
  100768. maxDistance = distance;
  100769. v1x = vx; v1y = vy; v1z = vz;
  100770. }
  100771. //vertex4;
  100772. vx = V1[9]; vy = V1[10]; vz = V1[11];
  100773. distance = nx * vx + ny * vy + nz * vz;
  100774. if (distance > maxDistance) {
  100775. maxDistance = distance;
  100776. v1x = vx; v1y = vy; v1z = vz;
  100777. }
  100778. //vertex5;
  100779. vx = V1[12]; vy = V1[13]; vz = V1[14];
  100780. distance = nx * vx + ny * vy + nz * vz;
  100781. if (distance > maxDistance) {
  100782. maxDistance = distance;
  100783. v1x = vx; v1y = vy; v1z = vz;
  100784. }
  100785. //vertex6;
  100786. vx = V1[15]; vy = V1[16]; vz = V1[17];
  100787. distance = nx * vx + ny * vy + nz * vz;
  100788. if (distance > maxDistance) {
  100789. maxDistance = distance;
  100790. v1x = vx; v1y = vy; v1z = vz;
  100791. }
  100792. //vertex7;
  100793. vx = V1[18]; vy = V1[19]; vz = V1[20];
  100794. distance = nx * vx + ny * vy + nz * vz;
  100795. if (distance > maxDistance) {
  100796. maxDistance = distance;
  100797. v1x = vx; v1y = vy; v1z = vz;
  100798. }
  100799. //vertex8;
  100800. vx = V1[21]; vy = V1[22]; vz = V1[23];
  100801. distance = nx * vx + ny * vy + nz * vz;
  100802. if (distance > maxDistance) {
  100803. maxDistance = distance;
  100804. v1x = vx; v1y = vy; v1z = vz;
  100805. }
  100806. //vertex1;
  100807. v2x = V2[0]; v2y = V2[1]; v2z = V2[2];
  100808. maxDistance = nx * v2x + ny * v2y + nz * v2z;
  100809. //vertex2;
  100810. vx = V2[3]; vy = V2[4]; vz = V2[5];
  100811. distance = nx * vx + ny * vy + nz * vz;
  100812. if (distance < maxDistance) {
  100813. maxDistance = distance;
  100814. v2x = vx; v2y = vy; v2z = vz;
  100815. }
  100816. //vertex3;
  100817. vx = V2[6]; vy = V2[7]; vz = V2[8];
  100818. distance = nx * vx + ny * vy + nz * vz;
  100819. if (distance < maxDistance) {
  100820. maxDistance = distance;
  100821. v2x = vx; v2y = vy; v2z = vz;
  100822. }
  100823. //vertex4;
  100824. vx = V2[9]; vy = V2[10]; vz = V2[11];
  100825. distance = nx * vx + ny * vy + nz * vz;
  100826. if (distance < maxDistance) {
  100827. maxDistance = distance;
  100828. v2x = vx; v2y = vy; v2z = vz;
  100829. }
  100830. //vertex5;
  100831. vx = V2[12]; vy = V2[13]; vz = V2[14];
  100832. distance = nx * vx + ny * vy + nz * vz;
  100833. if (distance < maxDistance) {
  100834. maxDistance = distance;
  100835. v2x = vx; v2y = vy; v2z = vz;
  100836. }
  100837. //vertex6;
  100838. vx = V2[15]; vy = V2[16]; vz = V2[17];
  100839. distance = nx * vx + ny * vy + nz * vz;
  100840. if (distance < maxDistance) {
  100841. maxDistance = distance;
  100842. v2x = vx; v2y = vy; v2z = vz;
  100843. }
  100844. //vertex7;
  100845. vx = V2[18]; vy = V2[19]; vz = V2[20];
  100846. distance = nx * vx + ny * vy + nz * vz;
  100847. if (distance < maxDistance) {
  100848. maxDistance = distance;
  100849. v2x = vx; v2y = vy; v2z = vz;
  100850. }
  100851. //vertex8;
  100852. vx = V2[21]; vy = V2[22]; vz = V2[23];
  100853. distance = nx * vx + ny * vy + nz * vz;
  100854. if (distance < maxDistance) {
  100855. maxDistance = distance;
  100856. v2x = vx; v2y = vy; v2z = vz;
  100857. }
  100858. vx = v2x - v1x; vy = v2y - v1y; vz = v2z - v1z;
  100859. dot1 = n1x * n2x + n1y * n2y + n1z * n2z;
  100860. var t = (vx * (n1x - n2x * dot1) + vy * (n1y - n2y * dot1) + vz * (n1z - n2z * dot1)) / (1 - dot1 * dot1);
  100861. 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);
  100862. return;
  100863. }
  100864. // now detect face-face collision...
  100865. // target quad
  100866. var q1x;
  100867. var q1y;
  100868. var q1z;
  100869. var q2x;
  100870. var q2y;
  100871. var q2z;
  100872. var q3x;
  100873. var q3y;
  100874. var q3z;
  100875. var q4x;
  100876. var q4y;
  100877. var q4z;
  100878. // search support face and vertex
  100879. var minDot = 1;
  100880. var dot = 0;
  100881. var minDotIndex = 0;
  100882. if (swap) {
  100883. dot = a1x * nx + a1y * ny + a1z * nz;
  100884. if (dot < minDot) {
  100885. minDot = dot;
  100886. minDotIndex = 0;
  100887. }
  100888. if (-dot < minDot) {
  100889. minDot = -dot;
  100890. minDotIndex = 1;
  100891. }
  100892. dot = a2x * nx + a2y * ny + a2z * nz;
  100893. if (dot < minDot) {
  100894. minDot = dot;
  100895. minDotIndex = 2;
  100896. }
  100897. if (-dot < minDot) {
  100898. minDot = -dot;
  100899. minDotIndex = 3;
  100900. }
  100901. dot = a3x * nx + a3y * ny + a3z * nz;
  100902. if (dot < minDot) {
  100903. minDot = dot;
  100904. minDotIndex = 4;
  100905. }
  100906. if (-dot < minDot) {
  100907. minDot = -dot;
  100908. minDotIndex = 5;
  100909. }
  100910. if (minDotIndex == 0) {// x+ face
  100911. q1x = V1[0]; q1y = V1[1]; q1z = V1[2];//vertex1
  100912. q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex3
  100913. q3x = V1[9]; q3y = V1[10]; q3z = V1[11];//vertex4
  100914. q4x = V1[3]; q4y = V1[4]; q4z = V1[5];//vertex2
  100915. }
  100916. else if (minDotIndex == 1) {// x- face
  100917. q1x = V1[15]; q1y = V1[16]; q1z = V1[17];//vertex6
  100918. q2x = V1[21]; q2y = V1[22]; q2z = V1[23];//vertex8
  100919. q3x = V1[18]; q3y = V1[19]; q3z = V1[20];//vertex7
  100920. q4x = V1[12]; q4y = V1[13]; q4z = V1[14];//vertex5
  100921. }
  100922. else if (minDotIndex == 2) {// y+ face
  100923. q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
  100924. q2x = V1[0]; q2y = V1[1]; q2z = V1[2];//vertex1
  100925. q3x = V1[3]; q3y = V1[4]; q3z = V1[5];//vertex2
  100926. q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
  100927. }
  100928. else if (minDotIndex == 3) {// y- face
  100929. q1x = V1[21]; q1y = V1[22]; q1z = V1[23];//vertex8
  100930. q2x = V1[9]; q2y = V1[10]; q2z = V1[11];//vertex4
  100931. q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
  100932. q4x = V1[18]; q4y = V1[19]; q4z = V1[20];//vertex7
  100933. }
  100934. else if (minDotIndex == 4) {// z+ face
  100935. q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
  100936. q2x = V1[18]; q2y = V1[19]; q2z = V1[20];//vertex7
  100937. q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
  100938. q4x = V1[0]; q4y = V1[1]; q4z = V1[2];//vertex1
  100939. }
  100940. else if (minDotIndex == 5) {// z- face
  100941. q1x = V1[3]; q1y = V1[4]; q1z = V1[5];//vertex2
  100942. q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex4
  100943. q3x = V1[21]; q3y = V1[22]; q3z = V1[23];//vertex8
  100944. q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
  100945. }
  100946. } else {
  100947. dot = a4x * nx + a4y * ny + a4z * nz;
  100948. if (dot < minDot) {
  100949. minDot = dot;
  100950. minDotIndex = 0;
  100951. }
  100952. if (-dot < minDot) {
  100953. minDot = -dot;
  100954. minDotIndex = 1;
  100955. }
  100956. dot = a5x * nx + a5y * ny + a5z * nz;
  100957. if (dot < minDot) {
  100958. minDot = dot;
  100959. minDotIndex = 2;
  100960. }
  100961. if (-dot < minDot) {
  100962. minDot = -dot;
  100963. minDotIndex = 3;
  100964. }
  100965. dot = a6x * nx + a6y * ny + a6z * nz;
  100966. if (dot < minDot) {
  100967. minDot = dot;
  100968. minDotIndex = 4;
  100969. }
  100970. if (-dot < minDot) {
  100971. minDot = -dot;
  100972. minDotIndex = 5;
  100973. }
  100974. //______________________________________________________
  100975. if (minDotIndex == 0) {// x+ face
  100976. q1x = V2[0]; q1y = V2[1]; q1z = V2[2];//vertex1
  100977. q2x = V2[6]; q2y = V2[7]; q2z = V2[8];//vertex3
  100978. q3x = V2[9]; q3y = V2[10]; q3z = V2[11];//vertex4
  100979. q4x = V2[3]; q4y = V2[4]; q4z = V2[5];//vertex2
  100980. }
  100981. else if (minDotIndex == 1) {// x- face
  100982. q1x = V2[15]; q1y = V2[16]; q1z = V2[17];//vertex6
  100983. q2x = V2[21]; q2y = V2[22]; q2z = V2[23]; //vertex8
  100984. q3x = V2[18]; q3y = V2[19]; q3z = V2[20];//vertex7
  100985. q4x = V2[12]; q4y = V2[13]; q4z = V2[14];//vertex5
  100986. }
  100987. else if (minDotIndex == 2) {// y+ face
  100988. q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
  100989. q2x = V2[0]; q2y = V2[1]; q2z = V2[2];//vertex1
  100990. q3x = V2[3]; q3y = V2[4]; q3z = V2[5];//vertex2
  100991. q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
  100992. }
  100993. else if (minDotIndex == 3) {// y- face
  100994. q1x = V2[21]; q1y = V2[22]; q1z = V2[23];//vertex8
  100995. q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
  100996. q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
  100997. q4x = V2[18]; q4y = V2[19]; q4z = V2[20];//vertex7
  100998. }
  100999. else if (minDotIndex == 4) {// z+ face
  101000. q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
  101001. q2x = V2[18]; q2y = V2[19]; q2z = V2[20];//vertex7
  101002. q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
  101003. q4x = V2[0]; q4y = V2[1]; q4z = V2[2];//vertex1
  101004. }
  101005. else if (minDotIndex == 5) {// z- face
  101006. q1x = V2[3]; q1y = V2[4]; q1z = V2[5];//vertex2
  101007. q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
  101008. q3x = V2[21]; q3y = V2[22]; q3z = V2[23];//vertex8
  101009. q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
  101010. }
  101011. }
  101012. // clip vertices
  101013. var numClipVertices;
  101014. var numAddedClipVertices;
  101015. var index;
  101016. var x1;
  101017. var y1;
  101018. var z1;
  101019. var x2;
  101020. var y2;
  101021. var z2;
  101022. this.clipVertices1[0] = q1x;
  101023. this.clipVertices1[1] = q1y;
  101024. this.clipVertices1[2] = q1z;
  101025. this.clipVertices1[3] = q2x;
  101026. this.clipVertices1[4] = q2y;
  101027. this.clipVertices1[5] = q2z;
  101028. this.clipVertices1[6] = q3x;
  101029. this.clipVertices1[7] = q3y;
  101030. this.clipVertices1[8] = q3z;
  101031. this.clipVertices1[9] = q4x;
  101032. this.clipVertices1[10] = q4y;
  101033. this.clipVertices1[11] = q4z;
  101034. numAddedClipVertices = 0;
  101035. x1 = this.clipVertices1[9];
  101036. y1 = this.clipVertices1[10];
  101037. z1 = this.clipVertices1[11];
  101038. dot1 = (x1 - cx - s1x) * n1x + (y1 - cy - s1y) * n1y + (z1 - cz - s1z) * n1z;
  101039. //var i = 4;
  101040. //while(i--){
  101041. for (var i = 0; i < 4; i++) {
  101042. index = i * 3;
  101043. x2 = this.clipVertices1[index];
  101044. y2 = this.clipVertices1[index + 1];
  101045. z2 = this.clipVertices1[index + 2];
  101046. dot2 = (x2 - cx - s1x) * n1x + (y2 - cy - s1y) * n1y + (z2 - cz - s1z) * n1z;
  101047. if (dot1 > 0) {
  101048. if (dot2 > 0) {
  101049. index = numAddedClipVertices * 3;
  101050. numAddedClipVertices++;
  101051. this.clipVertices2[index] = x2;
  101052. this.clipVertices2[index + 1] = y2;
  101053. this.clipVertices2[index + 2] = z2;
  101054. } else {
  101055. index = numAddedClipVertices * 3;
  101056. numAddedClipVertices++;
  101057. t = dot1 / (dot1 - dot2);
  101058. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  101059. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  101060. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  101061. }
  101062. } else {
  101063. if (dot2 > 0) {
  101064. index = numAddedClipVertices * 3;
  101065. numAddedClipVertices++;
  101066. t = dot1 / (dot1 - dot2);
  101067. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  101068. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  101069. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  101070. index = numAddedClipVertices * 3;
  101071. numAddedClipVertices++;
  101072. this.clipVertices2[index] = x2;
  101073. this.clipVertices2[index + 1] = y2;
  101074. this.clipVertices2[index + 2] = z2;
  101075. }
  101076. }
  101077. x1 = x2;
  101078. y1 = y2;
  101079. z1 = z2;
  101080. dot1 = dot2;
  101081. }
  101082. numClipVertices = numAddedClipVertices;
  101083. if (numClipVertices == 0) return;
  101084. numAddedClipVertices = 0;
  101085. index = (numClipVertices - 1) * 3;
  101086. x1 = this.clipVertices2[index];
  101087. y1 = this.clipVertices2[index + 1];
  101088. z1 = this.clipVertices2[index + 2];
  101089. dot1 = (x1 - cx - s2x) * n2x + (y1 - cy - s2y) * n2y + (z1 - cz - s2z) * n2z;
  101090. //i = numClipVertices;
  101091. //while(i--){
  101092. for (i = 0; i < numClipVertices; i++) {
  101093. index = i * 3;
  101094. x2 = this.clipVertices2[index];
  101095. y2 = this.clipVertices2[index + 1];
  101096. z2 = this.clipVertices2[index + 2];
  101097. dot2 = (x2 - cx - s2x) * n2x + (y2 - cy - s2y) * n2y + (z2 - cz - s2z) * n2z;
  101098. if (dot1 > 0) {
  101099. if (dot2 > 0) {
  101100. index = numAddedClipVertices * 3;
  101101. numAddedClipVertices++;
  101102. this.clipVertices1[index] = x2;
  101103. this.clipVertices1[index + 1] = y2;
  101104. this.clipVertices1[index + 2] = z2;
  101105. } else {
  101106. index = numAddedClipVertices * 3;
  101107. numAddedClipVertices++;
  101108. t = dot1 / (dot1 - dot2);
  101109. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  101110. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  101111. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  101112. }
  101113. } else {
  101114. if (dot2 > 0) {
  101115. index = numAddedClipVertices * 3;
  101116. numAddedClipVertices++;
  101117. t = dot1 / (dot1 - dot2);
  101118. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  101119. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  101120. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  101121. index = numAddedClipVertices * 3;
  101122. numAddedClipVertices++;
  101123. this.clipVertices1[index] = x2;
  101124. this.clipVertices1[index + 1] = y2;
  101125. this.clipVertices1[index + 2] = z2;
  101126. }
  101127. }
  101128. x1 = x2;
  101129. y1 = y2;
  101130. z1 = z2;
  101131. dot1 = dot2;
  101132. }
  101133. numClipVertices = numAddedClipVertices;
  101134. if (numClipVertices == 0) return;
  101135. numAddedClipVertices = 0;
  101136. index = (numClipVertices - 1) * 3;
  101137. x1 = this.clipVertices1[index];
  101138. y1 = this.clipVertices1[index + 1];
  101139. z1 = this.clipVertices1[index + 2];
  101140. dot1 = (x1 - cx + s1x) * -n1x + (y1 - cy + s1y) * -n1y + (z1 - cz + s1z) * -n1z;
  101141. //i = numClipVertices;
  101142. //while(i--){
  101143. for (i = 0; i < numClipVertices; i++) {
  101144. index = i * 3;
  101145. x2 = this.clipVertices1[index];
  101146. y2 = this.clipVertices1[index + 1];
  101147. z2 = this.clipVertices1[index + 2];
  101148. dot2 = (x2 - cx + s1x) * -n1x + (y2 - cy + s1y) * -n1y + (z2 - cz + s1z) * -n1z;
  101149. if (dot1 > 0) {
  101150. if (dot2 > 0) {
  101151. index = numAddedClipVertices * 3;
  101152. numAddedClipVertices++;
  101153. this.clipVertices2[index] = x2;
  101154. this.clipVertices2[index + 1] = y2;
  101155. this.clipVertices2[index + 2] = z2;
  101156. } else {
  101157. index = numAddedClipVertices * 3;
  101158. numAddedClipVertices++;
  101159. t = dot1 / (dot1 - dot2);
  101160. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  101161. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  101162. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  101163. }
  101164. } else {
  101165. if (dot2 > 0) {
  101166. index = numAddedClipVertices * 3;
  101167. numAddedClipVertices++;
  101168. t = dot1 / (dot1 - dot2);
  101169. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  101170. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  101171. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  101172. index = numAddedClipVertices * 3;
  101173. numAddedClipVertices++;
  101174. this.clipVertices2[index] = x2;
  101175. this.clipVertices2[index + 1] = y2;
  101176. this.clipVertices2[index + 2] = z2;
  101177. }
  101178. }
  101179. x1 = x2;
  101180. y1 = y2;
  101181. z1 = z2;
  101182. dot1 = dot2;
  101183. }
  101184. numClipVertices = numAddedClipVertices;
  101185. if (numClipVertices == 0) return;
  101186. numAddedClipVertices = 0;
  101187. index = (numClipVertices - 1) * 3;
  101188. x1 = this.clipVertices2[index];
  101189. y1 = this.clipVertices2[index + 1];
  101190. z1 = this.clipVertices2[index + 2];
  101191. dot1 = (x1 - cx + s2x) * -n2x + (y1 - cy + s2y) * -n2y + (z1 - cz + s2z) * -n2z;
  101192. //i = numClipVertices;
  101193. //while(i--){
  101194. for (i = 0; i < numClipVertices; i++) {
  101195. index = i * 3;
  101196. x2 = this.clipVertices2[index];
  101197. y2 = this.clipVertices2[index + 1];
  101198. z2 = this.clipVertices2[index + 2];
  101199. dot2 = (x2 - cx + s2x) * -n2x + (y2 - cy + s2y) * -n2y + (z2 - cz + s2z) * -n2z;
  101200. if (dot1 > 0) {
  101201. if (dot2 > 0) {
  101202. index = numAddedClipVertices * 3;
  101203. numAddedClipVertices++;
  101204. this.clipVertices1[index] = x2;
  101205. this.clipVertices1[index + 1] = y2;
  101206. this.clipVertices1[index + 2] = z2;
  101207. } else {
  101208. index = numAddedClipVertices * 3;
  101209. numAddedClipVertices++;
  101210. t = dot1 / (dot1 - dot2);
  101211. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  101212. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  101213. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  101214. }
  101215. } else {
  101216. if (dot2 > 0) {
  101217. index = numAddedClipVertices * 3;
  101218. numAddedClipVertices++;
  101219. t = dot1 / (dot1 - dot2);
  101220. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  101221. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  101222. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  101223. index = numAddedClipVertices * 3;
  101224. numAddedClipVertices++;
  101225. this.clipVertices1[index] = x2;
  101226. this.clipVertices1[index + 1] = y2;
  101227. this.clipVertices1[index + 2] = z2;
  101228. }
  101229. }
  101230. x1 = x2;
  101231. y1 = y2;
  101232. z1 = z2;
  101233. dot1 = dot2;
  101234. }
  101235. numClipVertices = numAddedClipVertices;
  101236. if (swap) {
  101237. var tb = b1;
  101238. b1 = b2;
  101239. b2 = tb;
  101240. }
  101241. if (numClipVertices == 0) return;
  101242. var flipped = b1 != shape1;
  101243. if (numClipVertices > 4) {
  101244. x1 = (q1x + q2x + q3x + q4x) * 0.25;
  101245. y1 = (q1y + q2y + q3y + q4y) * 0.25;
  101246. z1 = (q1z + q2z + q3z + q4z) * 0.25;
  101247. n1x = q1x - x1;
  101248. n1y = q1y - y1;
  101249. n1z = q1z - z1;
  101250. n2x = q2x - x1;
  101251. n2y = q2y - y1;
  101252. n2z = q2z - z1;
  101253. var index1 = 0;
  101254. var index2 = 0;
  101255. var index3 = 0;
  101256. var index4 = 0;
  101257. var maxDot = -this.INF;
  101258. minDot = this.INF;
  101259. //i = numClipVertices;
  101260. //while(i--){
  101261. for (i = 0; i < numClipVertices; i++) {
  101262. this.used[i] = false;
  101263. index = i * 3;
  101264. x1 = this.clipVertices1[index];
  101265. y1 = this.clipVertices1[index + 1];
  101266. z1 = this.clipVertices1[index + 2];
  101267. dot = x1 * n1x + y1 * n1y + z1 * n1z;
  101268. if (dot < minDot) {
  101269. minDot = dot;
  101270. index1 = i;
  101271. }
  101272. if (dot > maxDot) {
  101273. maxDot = dot;
  101274. index3 = i;
  101275. }
  101276. }
  101277. this.used[index1] = true;
  101278. this.used[index3] = true;
  101279. maxDot = -this.INF;
  101280. minDot = this.INF;
  101281. //i = numClipVertices;
  101282. //while(i--){
  101283. for (i = 0; i < numClipVertices; i++) {
  101284. if (this.used[i]) continue;
  101285. index = i * 3;
  101286. x1 = this.clipVertices1[index];
  101287. y1 = this.clipVertices1[index + 1];
  101288. z1 = this.clipVertices1[index + 2];
  101289. dot = x1 * n2x + y1 * n2y + z1 * n2z;
  101290. if (dot < minDot) {
  101291. minDot = dot;
  101292. index2 = i;
  101293. }
  101294. if (dot > maxDot) {
  101295. maxDot = dot;
  101296. index4 = i;
  101297. }
  101298. }
  101299. index = index1 * 3;
  101300. x1 = this.clipVertices1[index];
  101301. y1 = this.clipVertices1[index + 1];
  101302. z1 = this.clipVertices1[index + 2];
  101303. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  101304. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  101305. index = index2 * 3;
  101306. x1 = this.clipVertices1[index];
  101307. y1 = this.clipVertices1[index + 1];
  101308. z1 = this.clipVertices1[index + 2];
  101309. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  101310. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  101311. index = index3 * 3;
  101312. x1 = this.clipVertices1[index];
  101313. y1 = this.clipVertices1[index + 1];
  101314. z1 = this.clipVertices1[index + 2];
  101315. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  101316. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  101317. index = index4 * 3;
  101318. x1 = this.clipVertices1[index];
  101319. y1 = this.clipVertices1[index + 1];
  101320. z1 = this.clipVertices1[index + 2];
  101321. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  101322. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  101323. } else {
  101324. //i = numClipVertices;
  101325. //while(i--){
  101326. for (i = 0; i < numClipVertices; i++) {
  101327. index = i * 3;
  101328. x1 = this.clipVertices1[index];
  101329. y1 = this.clipVertices1[index + 1];
  101330. z1 = this.clipVertices1[index + 2];
  101331. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  101332. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  101333. }
  101334. }
  101335. };
  101336. /**
  101337. * A collision detector which detects collisions between sphere and box.
  101338. * @author saharan
  101339. */
  101340. OIMO.SphereBoxCollisionDetector = function (flip) {
  101341. OIMO.CollisionDetector.call(this);
  101342. this.flip = flip;
  101343. };
  101344. OIMO.SphereBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  101345. OIMO.SphereBoxCollisionDetector.prototype.constructor = OIMO.SphereBoxCollisionDetector;
  101346. OIMO.SphereBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  101347. var s;
  101348. var b;
  101349. if (this.flip) {
  101350. s = (shape2);
  101351. b = (shape1);
  101352. } else {
  101353. s = (shape1);
  101354. b = (shape2);
  101355. }
  101356. var D = b.dimentions;
  101357. var ps = s.position;
  101358. var psx = ps.x;
  101359. var psy = ps.y;
  101360. var psz = ps.z;
  101361. var pb = b.position;
  101362. var pbx = pb.x;
  101363. var pby = pb.y;
  101364. var pbz = pb.z;
  101365. var rad = s.radius;
  101366. var hw = b.halfWidth;
  101367. var hh = b.halfHeight;
  101368. var hd = b.halfDepth;
  101369. var dx = psx - pbx;
  101370. var dy = psy - pby;
  101371. var dz = psz - pbz;
  101372. var sx = D[0] * dx + D[1] * dy + D[2] * dz;
  101373. var sy = D[3] * dx + D[4] * dy + D[5] * dz;
  101374. var sz = D[6] * dx + D[7] * dy + D[8] * dz;
  101375. var cx;
  101376. var cy;
  101377. var cz;
  101378. var len;
  101379. var invLen;
  101380. var overlap = 0;
  101381. if (sx > hw) {
  101382. sx = hw;
  101383. } else if (sx < -hw) {
  101384. sx = -hw;
  101385. } else {
  101386. overlap = 1;
  101387. }
  101388. if (sy > hh) {
  101389. sy = hh;
  101390. } else if (sy < -hh) {
  101391. sy = -hh;
  101392. } else {
  101393. overlap |= 2;
  101394. }
  101395. if (sz > hd) {
  101396. sz = hd;
  101397. } else if (sz < -hd) {
  101398. sz = -hd;
  101399. } else {
  101400. overlap |= 4;
  101401. }
  101402. if (overlap == 7) {
  101403. // center of sphere is in the box
  101404. if (sx < 0) {
  101405. dx = hw + sx;
  101406. } else {
  101407. dx = hw - sx;
  101408. }
  101409. if (sy < 0) {
  101410. dy = hh + sy;
  101411. } else {
  101412. dy = hh - sy;
  101413. }
  101414. if (sz < 0) {
  101415. dz = hd + sz;
  101416. } else {
  101417. dz = hd - sz;
  101418. }
  101419. if (dx < dy) {
  101420. if (dx < dz) {
  101421. len = dx - hw;
  101422. if (sx < 0) {
  101423. sx = -hw;
  101424. dx = D[0];
  101425. dy = D[1];
  101426. dz = D[2];
  101427. } else {
  101428. sx = hw;
  101429. dx = -D[0];
  101430. dy = -D[1];
  101431. dz = -D[2];
  101432. }
  101433. } else {
  101434. len = dz - hd;
  101435. if (sz < 0) {
  101436. sz = -hd;
  101437. dx = D[6];
  101438. dy = D[7];
  101439. dz = D[8];
  101440. } else {
  101441. sz = hd;
  101442. dx = -D[6];
  101443. dy = -D[7];
  101444. dz = -D[8];
  101445. }
  101446. }
  101447. } else {
  101448. if (dy < dz) {
  101449. len = dy - hh;
  101450. if (sy < 0) {
  101451. sy = -hh;
  101452. dx = D[3];
  101453. dy = D[4];
  101454. dz = D[5];
  101455. } else {
  101456. sy = hh;
  101457. dx = -D[3];
  101458. dy = -D[4];
  101459. dz = -D[5];
  101460. }
  101461. } else {
  101462. len = dz - hd;
  101463. if (sz < 0) {
  101464. sz = -hd;
  101465. dx = D[6];
  101466. dy = D[7];
  101467. dz = D[8];
  101468. } else {
  101469. sz = hd;
  101470. dx = -D[6];
  101471. dy = -D[7];
  101472. dz = -D[8];
  101473. }
  101474. }
  101475. }
  101476. cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
  101477. cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
  101478. cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
  101479. manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
  101480. } else {
  101481. cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
  101482. cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
  101483. cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
  101484. dx = cx - ps.x;
  101485. dy = cy - ps.y;
  101486. dz = cz - ps.z;
  101487. len = dx * dx + dy * dy + dz * dz;
  101488. if (len > 0 && len < rad * rad) {
  101489. len = OIMO.sqrt(len);
  101490. invLen = 1 / len;
  101491. dx *= invLen;
  101492. dy *= invLen;
  101493. dz *= invLen;
  101494. manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
  101495. }
  101496. }
  101497. };
  101498. /**
  101499. * A collision detector which detects collisions between two spheres.
  101500. * @author saharan
  101501. */
  101502. OIMO.SphereSphereCollisionDetector = function () {
  101503. OIMO.CollisionDetector.call(this);
  101504. };
  101505. OIMO.SphereSphereCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  101506. OIMO.SphereSphereCollisionDetector.prototype.constructor = OIMO.SphereSphereCollisionDetector;
  101507. OIMO.SphereSphereCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  101508. var s1 = shape1;
  101509. var s2 = shape2;
  101510. var p1 = s1.position;
  101511. var p2 = s2.position;
  101512. var dx = p2.x - p1.x;
  101513. var dy = p2.y - p1.y;
  101514. var dz = p2.z - p1.z;
  101515. var len = dx * dx + dy * dy + dz * dz;
  101516. var r1 = s1.radius;
  101517. var r2 = s2.radius;
  101518. var rad = r1 + r2;
  101519. if (len > 0 && len < rad * rad) {
  101520. len = OIMO.sqrt(len);
  101521. var invLen = 1 / len;
  101522. dx *= invLen;
  101523. dy *= invLen;
  101524. dz *= invLen;
  101525. manifold.addPoint(p1.x + dx * r1, p1.y + dy * r1, p1.z + dz * r1, dx, dy, dz, len - rad, false);
  101526. }
  101527. };
  101528. OIMO.BoxCylinderCollisionDetector = function (flip) {
  101529. OIMO.CollisionDetector.call(this);
  101530. this.flip = flip;
  101531. };
  101532. OIMO.BoxCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  101533. OIMO.BoxCylinderCollisionDetector.prototype.constructor = OIMO.BoxCylinderCollisionDetector;
  101534. OIMO.BoxCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
  101535. var t1x;
  101536. var t1y;
  101537. var t1z;
  101538. var t2x;
  101539. var t2y;
  101540. var t2z;
  101541. var sup = new OIMO.Vec3();
  101542. var len;
  101543. var p1x;
  101544. var p1y;
  101545. var p1z;
  101546. var p2x;
  101547. var p2y;
  101548. var p2z;
  101549. var v01x = c1.position.x;
  101550. var v01y = c1.position.y;
  101551. var v01z = c1.position.z;
  101552. var v02x = c2.position.x;
  101553. var v02y = c2.position.y;
  101554. var v02z = c2.position.z;
  101555. var v0x = v02x - v01x;
  101556. var v0y = v02y - v01y;
  101557. var v0z = v02z - v01z;
  101558. if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
  101559. var nx = -v0x;
  101560. var ny = -v0y;
  101561. var nz = -v0z;
  101562. this.supportPointB(c1, -nx, -ny, -nz, sup);
  101563. var v11x = sup.x;
  101564. var v11y = sup.y;
  101565. var v11z = sup.z;
  101566. this.supportPointC(c2, nx, ny, nz, sup);
  101567. var v12x = sup.x;
  101568. var v12y = sup.y;
  101569. var v12z = sup.z;
  101570. var v1x = v12x - v11x;
  101571. var v1y = v12y - v11y;
  101572. var v1z = v12z - v11z;
  101573. if (v1x * nx + v1y * ny + v1z * nz <= 0) {
  101574. return false;
  101575. }
  101576. nx = v1y * v0z - v1z * v0y;
  101577. ny = v1z * v0x - v1x * v0z;
  101578. nz = v1x * v0y - v1y * v0x;
  101579. if (nx * nx + ny * ny + nz * nz == 0) {
  101580. sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
  101581. sep.normalize(sep);
  101582. pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
  101583. return true;
  101584. }
  101585. this.supportPointB(c1, -nx, -ny, -nz, sup);
  101586. var v21x = sup.x;
  101587. var v21y = sup.y;
  101588. var v21z = sup.z;
  101589. this.supportPointC(c2, nx, ny, nz, sup);
  101590. var v22x = sup.x;
  101591. var v22y = sup.y;
  101592. var v22z = sup.z;
  101593. var v2x = v22x - v21x;
  101594. var v2y = v22y - v21y;
  101595. var v2z = v22z - v21z;
  101596. if (v2x * nx + v2y * ny + v2z * nz <= 0) {
  101597. return false;
  101598. }
  101599. t1x = v1x - v0x;
  101600. t1y = v1y - v0y;
  101601. t1z = v1z - v0z;
  101602. t2x = v2x - v0x;
  101603. t2y = v2y - v0y;
  101604. t2z = v2z - v0z;
  101605. nx = t1y * t2z - t1z * t2y;
  101606. ny = t1z * t2x - t1x * t2z;
  101607. nz = t1x * t2y - t1y * t2x;
  101608. if (nx * v0x + ny * v0y + nz * v0z > 0) {
  101609. t1x = v1x;
  101610. t1y = v1y;
  101611. t1z = v1z;
  101612. v1x = v2x;
  101613. v1y = v2y;
  101614. v1z = v2z;
  101615. v2x = t1x;
  101616. v2y = t1y;
  101617. v2z = t1z;
  101618. t1x = v11x;
  101619. t1y = v11y;
  101620. t1z = v11z;
  101621. v11x = v21x;
  101622. v11y = v21y;
  101623. v11z = v21z;
  101624. v21x = t1x;
  101625. v21y = t1y;
  101626. v21z = t1z;
  101627. t1x = v12x;
  101628. t1y = v12y;
  101629. t1z = v12z;
  101630. v12x = v22x;
  101631. v12y = v22y;
  101632. v12z = v22z;
  101633. v22x = t1x;
  101634. v22y = t1y;
  101635. v22z = t1z;
  101636. nx = -nx;
  101637. ny = -ny;
  101638. nz = -nz;
  101639. }
  101640. var iterations = 0;
  101641. while (true) {
  101642. if (++iterations > 100) {
  101643. return false;
  101644. }
  101645. this.supportPointB(c1, -nx, -ny, -nz, sup);
  101646. var v31x = sup.x;
  101647. var v31y = sup.y;
  101648. var v31z = sup.z;
  101649. this.supportPointC(c2, nx, ny, nz, sup);
  101650. var v32x = sup.x;
  101651. var v32y = sup.y;
  101652. var v32z = sup.z;
  101653. var v3x = v32x - v31x;
  101654. var v3y = v32y - v31y;
  101655. var v3z = v32z - v31z;
  101656. if (v3x * nx + v3y * ny + v3z * nz <= 0) {
  101657. return false;
  101658. }
  101659. if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
  101660. v2x = v3x;
  101661. v2y = v3y;
  101662. v2z = v3z;
  101663. v21x = v31x;
  101664. v21y = v31y;
  101665. v21z = v31z;
  101666. v22x = v32x;
  101667. v22y = v32y;
  101668. v22z = v32z;
  101669. t1x = v1x - v0x;
  101670. t1y = v1y - v0y;
  101671. t1z = v1z - v0z;
  101672. t2x = v3x - v0x;
  101673. t2y = v3y - v0y;
  101674. t2z = v3z - v0z;
  101675. nx = t1y * t2z - t1z * t2y;
  101676. ny = t1z * t2x - t1x * t2z;
  101677. nz = t1x * t2y - t1y * t2x;
  101678. continue;
  101679. }
  101680. if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
  101681. v1x = v3x;
  101682. v1y = v3y;
  101683. v1z = v3z;
  101684. v11x = v31x;
  101685. v11y = v31y;
  101686. v11z = v31z;
  101687. v12x = v32x;
  101688. v12y = v32y;
  101689. v12z = v32z;
  101690. t1x = v3x - v0x;
  101691. t1y = v3y - v0y;
  101692. t1z = v3z - v0z;
  101693. t2x = v2x - v0x;
  101694. t2y = v2y - v0y;
  101695. t2z = v2z - v0z;
  101696. nx = t1y * t2z - t1z * t2y;
  101697. ny = t1z * t2x - t1x * t2z;
  101698. nz = t1x * t2y - t1y * t2x;
  101699. continue;
  101700. }
  101701. var hit = false;
  101702. while (true) {
  101703. t1x = v2x - v1x;
  101704. t1y = v2y - v1y;
  101705. t1z = v2z - v1z;
  101706. t2x = v3x - v1x;
  101707. t2y = v3y - v1y;
  101708. t2z = v3z - v1z;
  101709. nx = t1y * t2z - t1z * t2y;
  101710. ny = t1z * t2x - t1x * t2z;
  101711. nz = t1x * t2y - t1y * t2x;
  101712. len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  101713. nx *= len;
  101714. ny *= len;
  101715. nz *= len;
  101716. if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
  101717. var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
  101718. var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
  101719. var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
  101720. var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
  101721. var sum = b0 + b1 + b2 + b3;
  101722. if (sum <= 0) {
  101723. b0 = 0;
  101724. b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
  101725. b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
  101726. b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
  101727. sum = b1 + b2 + b3;
  101728. }
  101729. var inv = 1 / sum;
  101730. p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
  101731. p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
  101732. p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
  101733. p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
  101734. p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
  101735. p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
  101736. hit = true;
  101737. }
  101738. this.supportPointB(c1, -nx, -ny, -nz, sup);
  101739. var v41x = sup.x;
  101740. var v41y = sup.y;
  101741. var v41z = sup.z;
  101742. this.supportPointC(c2, nx, ny, nz, sup);
  101743. var v42x = sup.x;
  101744. var v42y = sup.y;
  101745. var v42z = sup.z;
  101746. var v4x = v42x - v41x;
  101747. var v4y = v42y - v41y;
  101748. var v4z = v42z - v41z;
  101749. var separation = -(v4x * nx + v4y * ny + v4z * nz);
  101750. if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
  101751. if (hit) {
  101752. sep.init(-nx, -ny, -nz);
  101753. pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
  101754. dep.x = separation;
  101755. return true;
  101756. }
  101757. return false;
  101758. }
  101759. if (
  101760. (v4y * v1z - v4z * v1y) * v0x +
  101761. (v4z * v1x - v4x * v1z) * v0y +
  101762. (v4x * v1y - v4y * v1x) * v0z < 0
  101763. ) {
  101764. if (
  101765. (v4y * v2z - v4z * v2y) * v0x +
  101766. (v4z * v2x - v4x * v2z) * v0y +
  101767. (v4x * v2y - v4y * v2x) * v0z < 0
  101768. ) {
  101769. v1x = v4x;
  101770. v1y = v4y;
  101771. v1z = v4z;
  101772. v11x = v41x;
  101773. v11y = v41y;
  101774. v11z = v41z;
  101775. v12x = v42x;
  101776. v12y = v42y;
  101777. v12z = v42z;
  101778. } else {
  101779. v3x = v4x;
  101780. v3y = v4y;
  101781. v3z = v4z;
  101782. v31x = v41x;
  101783. v31y = v41y;
  101784. v31z = v41z;
  101785. v32x = v42x;
  101786. v32y = v42y;
  101787. v32z = v42z;
  101788. }
  101789. } else {
  101790. if (
  101791. (v4y * v3z - v4z * v3y) * v0x +
  101792. (v4z * v3x - v4x * v3z) * v0y +
  101793. (v4x * v3y - v4y * v3x) * v0z < 0
  101794. ) {
  101795. v2x = v4x;
  101796. v2y = v4y;
  101797. v2z = v4z;
  101798. v21x = v41x;
  101799. v21y = v41y;
  101800. v21z = v41z;
  101801. v22x = v42x;
  101802. v22y = v42y;
  101803. v22z = v42z;
  101804. } else {
  101805. v1x = v4x;
  101806. v1y = v4y;
  101807. v1z = v4z;
  101808. v11x = v41x;
  101809. v11y = v41y;
  101810. v11z = v41z;
  101811. v12x = v42x;
  101812. v12y = v42y;
  101813. v12z = v42z;
  101814. }
  101815. }
  101816. }
  101817. }
  101818. //return false;
  101819. };
  101820. OIMO.BoxCylinderCollisionDetector.prototype.supportPointB = function (c, dx, dy, dz, out) {
  101821. var rot = c.rotation.elements;
  101822. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  101823. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  101824. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  101825. var w = c.halfWidth;
  101826. var h = c.halfHeight;
  101827. var d = c.halfDepth;
  101828. var ox;
  101829. var oy;
  101830. var oz;
  101831. if (ldx < 0) ox = -w;
  101832. else ox = w;
  101833. if (ldy < 0) oy = -h;
  101834. else oy = h;
  101835. if (ldz < 0) oz = -d;
  101836. else oz = d;
  101837. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  101838. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  101839. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  101840. out.init(ldx, ldy, ldz);
  101841. };
  101842. OIMO.BoxCylinderCollisionDetector.prototype.supportPointC = function (c, dx, dy, dz, out) {
  101843. var rot = c.rotation.elements;
  101844. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  101845. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  101846. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  101847. var radx = ldx;
  101848. var radz = ldz;
  101849. var len = radx * radx + radz * radz;
  101850. var rad = c.radius;
  101851. var hh = c.halfHeight;
  101852. var ox;
  101853. var oy;
  101854. var oz;
  101855. if (len == 0) {
  101856. if (ldy < 0) {
  101857. ox = rad;
  101858. oy = -hh;
  101859. oz = 0;
  101860. } else {
  101861. ox = rad;
  101862. oy = hh;
  101863. oz = 0;
  101864. }
  101865. } else {
  101866. len = c.radius / OIMO.sqrt(len);
  101867. if (ldy < 0) {
  101868. ox = radx * len;
  101869. oy = -hh;
  101870. oz = radz * len;
  101871. } else {
  101872. ox = radx * len;
  101873. oy = hh;
  101874. oz = radz * len;
  101875. }
  101876. }
  101877. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  101878. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  101879. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  101880. out.init(ldx, ldy, ldz);
  101881. };
  101882. OIMO.BoxCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  101883. var b;
  101884. var c;
  101885. if (this.flip) {
  101886. b = shape2;
  101887. c = shape1;
  101888. } else {
  101889. b = shape1;
  101890. c = shape2;
  101891. }
  101892. var sep = new OIMO.Vec3();
  101893. var pos = new OIMO.Vec3();
  101894. var dep = new OIMO.Vec3();
  101895. var co;
  101896. if (!this.getSep(b, c, sep, pos, dep)) return;
  101897. var pbx = b.position.x;
  101898. var pby = b.position.y;
  101899. var pbz = b.position.z;
  101900. var pcx = c.position.x;
  101901. var pcy = c.position.y;
  101902. var pcz = c.position.z;
  101903. var bw = b.halfWidth;
  101904. var bh = b.halfHeight;
  101905. var bd = b.halfDepth;
  101906. var ch = c.halfHeight;
  101907. var r = c.radius;
  101908. var D = b.dimentions;
  101909. var nwx = D[0];//b.normalDirectionWidth.x;
  101910. var nwy = D[1];//b.normalDirectionWidth.y;
  101911. var nwz = D[2];//b.normalDirectionWidth.z;
  101912. var nhx = D[3];//b.normalDirectionHeight.x;
  101913. var nhy = D[4];//b.normalDirectionHeight.y;
  101914. var nhz = D[5];//b.normalDirectionHeight.z;
  101915. var ndx = D[6];//b.normalDirectionDepth.x;
  101916. var ndy = D[7];//b.normalDirectionDepth.y;
  101917. var ndz = D[8];//b.normalDirectionDepth.z;
  101918. var dwx = D[9];//b.halfDirectionWidth.x;
  101919. var dwy = D[10];//b.halfDirectionWidth.y;
  101920. var dwz = D[11];//b.halfDirectionWidth.z;
  101921. var dhx = D[12];//b.halfDirectionHeight.x;
  101922. var dhy = D[13];//b.halfDirectionHeight.y;
  101923. var dhz = D[14];//b.halfDirectionHeight.z;
  101924. var ddx = D[15];//b.halfDirectionDepth.x;
  101925. var ddy = D[16];//b.halfDirectionDepth.y;
  101926. var ddz = D[17];//b.halfDirectionDepth.z;
  101927. var ncx = c.normalDirection.x;
  101928. var ncy = c.normalDirection.y;
  101929. var ncz = c.normalDirection.z;
  101930. var dcx = c.halfDirection.x;
  101931. var dcy = c.halfDirection.y;
  101932. var dcz = c.halfDirection.z;
  101933. var nx = sep.x;
  101934. var ny = sep.y;
  101935. var nz = sep.z;
  101936. var dotw = nx * nwx + ny * nwy + nz * nwz;
  101937. var doth = nx * nhx + ny * nhy + nz * nhz;
  101938. var dotd = nx * ndx + ny * ndy + nz * ndz;
  101939. var dotc = nx * ncx + ny * ncy + nz * ncz;
  101940. var right1 = dotw > 0;
  101941. var right2 = doth > 0;
  101942. var right3 = dotd > 0;
  101943. var right4 = dotc > 0;
  101944. if (!right1) dotw = -dotw;
  101945. if (!right2) doth = -doth;
  101946. if (!right3) dotd = -dotd;
  101947. if (!right4) dotc = -dotc;
  101948. var state = 0;
  101949. if (dotc > 0.999) {
  101950. if (dotw > 0.999) {
  101951. if (dotw > dotc) state = 1;
  101952. else state = 4;
  101953. } else if (doth > 0.999) {
  101954. if (doth > dotc) state = 2;
  101955. else state = 4;
  101956. } else if (dotd > 0.999) {
  101957. if (dotd > dotc) state = 3;
  101958. else state = 4;
  101959. } else state = 4;
  101960. } else {
  101961. if (dotw > 0.999) state = 1;
  101962. else if (doth > 0.999) state = 2;
  101963. else if (dotd > 0.999) state = 3;
  101964. }
  101965. var cbx;
  101966. var cby;
  101967. var cbz;
  101968. var ccx;
  101969. var ccy;
  101970. var ccz;
  101971. var r00;
  101972. var r01;
  101973. var r02;
  101974. var r10;
  101975. var r11;
  101976. var r12;
  101977. var r20;
  101978. var r21;
  101979. var r22;
  101980. var px;
  101981. var py;
  101982. var pz;
  101983. var pd;
  101984. var dot;
  101985. var len;
  101986. var tx;
  101987. var ty;
  101988. var tz;
  101989. var td;
  101990. var dx;
  101991. var dy;
  101992. var dz;
  101993. var d1x;
  101994. var d1y;
  101995. var d1z;
  101996. var d2x;
  101997. var d2y;
  101998. var d2z;
  101999. var sx;
  102000. var sy;
  102001. var sz;
  102002. var sd;
  102003. var ex;
  102004. var ey;
  102005. var ez;
  102006. var ed;
  102007. var dot1;
  102008. var dot2;
  102009. var t1;
  102010. var t2;
  102011. var dir1x;
  102012. var dir1y;
  102013. var dir1z;
  102014. var dir2x;
  102015. var dir2y;
  102016. var dir2z;
  102017. var dir1l;
  102018. var dir2l;
  102019. if (state == 0) {
  102020. //manifold.addPoint(pos.x,pos.y,pos.z,nx,ny,nz,dep.x,b,c,0,0,false);
  102021. manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, dep.x, this.flip);
  102022. } else if (state == 4) {
  102023. if (right4) {
  102024. ccx = pcx - dcx;
  102025. ccy = pcy - dcy;
  102026. ccz = pcz - dcz;
  102027. nx = -ncx;
  102028. ny = -ncy;
  102029. nz = -ncz;
  102030. } else {
  102031. ccx = pcx + dcx;
  102032. ccy = pcy + dcy;
  102033. ccz = pcz + dcz;
  102034. nx = ncx;
  102035. ny = ncy;
  102036. nz = ncz;
  102037. }
  102038. var v1x;
  102039. var v1y;
  102040. var v1z;
  102041. var v2x;
  102042. var v2y;
  102043. var v2z;
  102044. var v3x;
  102045. var v3y;
  102046. var v3z;
  102047. var v4x;
  102048. var v4y;
  102049. var v4z;
  102050. dot = 1;
  102051. state = 0;
  102052. dot1 = nwx * nx + nwy * ny + nwz * nz;
  102053. if (dot1 < dot) {
  102054. dot = dot1;
  102055. state = 0;
  102056. }
  102057. if (-dot1 < dot) {
  102058. dot = -dot1;
  102059. state = 1;
  102060. }
  102061. dot1 = nhx * nx + nhy * ny + nhz * nz;
  102062. if (dot1 < dot) {
  102063. dot = dot1;
  102064. state = 2;
  102065. }
  102066. if (-dot1 < dot) {
  102067. dot = -dot1;
  102068. state = 3;
  102069. }
  102070. dot1 = ndx * nx + ndy * ny + ndz * nz;
  102071. if (dot1 < dot) {
  102072. dot = dot1;
  102073. state = 4;
  102074. }
  102075. if (-dot1 < dot) {
  102076. dot = -dot1;
  102077. state = 5;
  102078. }
  102079. var v = b.elements;
  102080. switch (state) {
  102081. case 0:
  102082. //v=b.vertex1;
  102083. v1x = v[0];//v.x;
  102084. v1y = v[1];//v.y;
  102085. v1z = v[2];//v.z;
  102086. //v=b.vertex3;
  102087. v2x = v[6];//v.x;
  102088. v2y = v[7];//v.y;
  102089. v2z = v[8];//v.z;
  102090. //v=b.vertex4;
  102091. v3x = v[9];//v.x;
  102092. v3y = v[10];//v.y;
  102093. v3z = v[11];//v.z;
  102094. //v=b.vertex2;
  102095. v4x = v[3];//v.x;
  102096. v4y = v[4];//v.y;
  102097. v4z = v[5];//v.z;
  102098. break;
  102099. case 1:
  102100. //v=b.vertex6;
  102101. v1x = v[15];//v.x;
  102102. v1y = v[16];//v.y;
  102103. v1z = v[17];//v.z;
  102104. //v=b.vertex8;
  102105. v2x = v[21];//v.x;
  102106. v2y = v[22];//v.y;
  102107. v2z = v[23];//v.z;
  102108. //v=b.vertex7;
  102109. v3x = v[18];//v.x;
  102110. v3y = v[19];//v.y;
  102111. v3z = v[20];//v.z;
  102112. //v=b.vertex5;
  102113. v4x = v[12];//v.x;
  102114. v4y = v[13];//v.y;
  102115. v4z = v[14];//v.z;
  102116. break;
  102117. case 2:
  102118. //v=b.vertex5;
  102119. v1x = v[12];//v.x;
  102120. v1y = v[13];//v.y;
  102121. v1z = v[14];//v.z;
  102122. //v=b.vertex1;
  102123. v2x = v[0];//v.x;
  102124. v2y = v[1];//v.y;
  102125. v2z = v[2];//v.z;
  102126. //v=b.vertex2;
  102127. v3x = v[3];//v.x;
  102128. v3y = v[4];//v.y;
  102129. v3z = v[5];//v.z;
  102130. //v=b.vertex6;
  102131. v4x = v[15];//v.x;
  102132. v4y = v[16];//v.y;
  102133. v4z = v[17];//v.z;
  102134. break;
  102135. case 3:
  102136. //v=b.vertex8;
  102137. v1x = v[21];//v.x;
  102138. v1y = v[22];//v.y;
  102139. v1z = v[23];//v.z;
  102140. //v=b.vertex4;
  102141. v2x = v[9];//v.x;
  102142. v2y = v[10];//v.y;
  102143. v2z = v[11];//v.z;
  102144. //v=b.vertex3;
  102145. v3x = v[6];//v.x;
  102146. v3y = v[7];//v.y;
  102147. v3z = v[8];//v.z;
  102148. //v=b.vertex7;
  102149. v4x = v[18];//v.x;
  102150. v4y = v[19];//v.y;
  102151. v4z = v[20];//v.z;
  102152. break;
  102153. case 4:
  102154. //v=b.vertex5;
  102155. v1x = v[12];//v.x;
  102156. v1y = v[13];//v.y;
  102157. v1z = v[14];//v.z;
  102158. //v=b.vertex7;
  102159. v2x = v[18];//v.x;
  102160. v2y = v[19];//v.y;
  102161. v2z = v[20];//v.z;
  102162. //v=b.vertex3;
  102163. v3x = v[6];//v.x;
  102164. v3y = v[7];//v.y;
  102165. v3z = v[8];//v.z;
  102166. //v=b.vertex1;
  102167. v4x = v[0];//v.x;
  102168. v4y = v[1];//v.y;
  102169. v4z = v[2];//v.z;
  102170. break;
  102171. case 5:
  102172. //v=b.vertex2;
  102173. v1x = v[3];//v.x;
  102174. v1y = v[4];//v.y;
  102175. v1z = v[5];//v.z;
  102176. //v=b.vertex4;
  102177. v2x = v[9];//v.x;
  102178. v2y = v[10];//v.y;
  102179. v2z = v[11];//v.z;
  102180. //v=b.vertex8;
  102181. v3x = v[21];//v.x;
  102182. v3y = v[22];//v.y;
  102183. v3z = v[23];//v.z;
  102184. //v=b.vertex6;
  102185. v4x = v[15];//v.x;
  102186. v4y = v[16];//v.y;
  102187. v4z = v[17];//v.z;
  102188. break;
  102189. }
  102190. pd = nx * (v1x - ccx) + ny * (v1y - ccy) + nz * (v1z - ccz);
  102191. if (pd <= 0) manifold.addPoint(v1x, v1y, v1z, -nx, -ny, -nz, pd, this.flip);
  102192. pd = nx * (v2x - ccx) + ny * (v2y - ccy) + nz * (v2z - ccz);
  102193. if (pd <= 0) manifold.addPoint(v2x, v2y, v2z, -nx, -ny, -nz, pd, this.flip);
  102194. pd = nx * (v3x - ccx) + ny * (v3y - ccy) + nz * (v3z - ccz);
  102195. if (pd <= 0) manifold.addPoint(v3x, v3y, v3z, -nx, -ny, -nz, pd, this.flip);
  102196. pd = nx * (v4x - ccx) + ny * (v4y - ccy) + nz * (v4z - ccz);
  102197. if (pd <= 0) manifold.addPoint(v4x, v4y, v4z, -nx, -ny, -nz, pd, this.flip);
  102198. } else {
  102199. switch (state) {
  102200. case 1:
  102201. if (right1) {
  102202. cbx = pbx + dwx;
  102203. cby = pby + dwy;
  102204. cbz = pbz + dwz;
  102205. nx = nwx;
  102206. ny = nwy;
  102207. nz = nwz;
  102208. } else {
  102209. cbx = pbx - dwx;
  102210. cby = pby - dwy;
  102211. cbz = pbz - dwz;
  102212. nx = -nwx;
  102213. ny = -nwy;
  102214. nz = -nwz;
  102215. }
  102216. dir1x = nhx;
  102217. dir1y = nhy;
  102218. dir1z = nhz;
  102219. dir1l = bh;
  102220. dir2x = ndx;
  102221. dir2y = ndy;
  102222. dir2z = ndz;
  102223. dir2l = bd;
  102224. break;
  102225. case 2:
  102226. if (right2) {
  102227. cbx = pbx + dhx;
  102228. cby = pby + dhy;
  102229. cbz = pbz + dhz;
  102230. nx = nhx;
  102231. ny = nhy;
  102232. nz = nhz;
  102233. } else {
  102234. cbx = pbx - dhx;
  102235. cby = pby - dhy;
  102236. cbz = pbz - dhz;
  102237. nx = -nhx;
  102238. ny = -nhy;
  102239. nz = -nhz;
  102240. }
  102241. dir1x = nwx;
  102242. dir1y = nwy;
  102243. dir1z = nwz;
  102244. dir1l = bw;
  102245. dir2x = ndx;
  102246. dir2y = ndy;
  102247. dir2z = ndz;
  102248. dir2l = bd;
  102249. break;
  102250. case 3:
  102251. if (right3) {
  102252. cbx = pbx + ddx;
  102253. cby = pby + ddy;
  102254. cbz = pbz + ddz;
  102255. nx = ndx;
  102256. ny = ndy;
  102257. nz = ndz;
  102258. } else {
  102259. cbx = pbx - ddx;
  102260. cby = pby - ddy;
  102261. cbz = pbz - ddz;
  102262. nx = -ndx;
  102263. ny = -ndy;
  102264. nz = -ndz;
  102265. }
  102266. dir1x = nwx;
  102267. dir1y = nwy;
  102268. dir1z = nwz;
  102269. dir1l = bw;
  102270. dir2x = nhx;
  102271. dir2y = nhy;
  102272. dir2z = nhz;
  102273. dir2l = bh;
  102274. break;
  102275. }
  102276. dot = nx * ncx + ny * ncy + nz * ncz;
  102277. if (dot < 0) len = ch;
  102278. else len = -ch;
  102279. ccx = pcx + len * ncx;
  102280. ccy = pcy + len * ncy;
  102281. ccz = pcz + len * ncz;
  102282. if (dotc >= 0.999999) {
  102283. tx = -ny;
  102284. ty = nz;
  102285. tz = nx;
  102286. } else {
  102287. tx = nx;
  102288. ty = ny;
  102289. tz = nz;
  102290. }
  102291. len = tx * ncx + ty * ncy + tz * ncz;
  102292. dx = len * ncx - tx;
  102293. dy = len * ncy - ty;
  102294. dz = len * ncz - tz;
  102295. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  102296. if (len == 0) return;
  102297. len = r / len;
  102298. dx *= len;
  102299. dy *= len;
  102300. dz *= len;
  102301. tx = ccx + dx;
  102302. ty = ccy + dy;
  102303. tz = ccz + dz;
  102304. if (dot < -0.96 || dot > 0.96) {
  102305. r00 = ncx * ncx * 1.5 - 0.5;
  102306. r01 = ncx * ncy * 1.5 - ncz * 0.866025403;
  102307. r02 = ncx * ncz * 1.5 + ncy * 0.866025403;
  102308. r10 = ncy * ncx * 1.5 + ncz * 0.866025403;
  102309. r11 = ncy * ncy * 1.5 - 0.5;
  102310. r12 = ncy * ncz * 1.5 - ncx * 0.866025403;
  102311. r20 = ncz * ncx * 1.5 - ncy * 0.866025403;
  102312. r21 = ncz * ncy * 1.5 + ncx * 0.866025403;
  102313. r22 = ncz * ncz * 1.5 - 0.5;
  102314. px = tx;
  102315. py = ty;
  102316. pz = tz;
  102317. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  102318. tx = px - pd * nx - cbx;
  102319. ty = py - pd * ny - cby;
  102320. tz = pz - pd * nz - cbz;
  102321. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  102322. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  102323. if (sd < -dir1l) sd = -dir1l;
  102324. else if (sd > dir1l) sd = dir1l;
  102325. if (ed < -dir2l) ed = -dir2l;
  102326. else if (ed > dir2l) ed = dir2l;
  102327. tx = sd * dir1x + ed * dir2x;
  102328. ty = sd * dir1y + ed * dir2y;
  102329. tz = sd * dir1z + ed * dir2z;
  102330. px = cbx + tx;
  102331. py = cby + ty;
  102332. pz = cbz + tz;
  102333. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  102334. px = dx * r00 + dy * r01 + dz * r02;
  102335. py = dx * r10 + dy * r11 + dz * r12;
  102336. pz = dx * r20 + dy * r21 + dz * r22;
  102337. px = (dx = px) + ccx;
  102338. py = (dy = py) + ccy;
  102339. pz = (dz = pz) + ccz;
  102340. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  102341. if (pd <= 0) {
  102342. tx = px - pd * nx - cbx;
  102343. ty = py - pd * ny - cby;
  102344. tz = pz - pd * nz - cbz;
  102345. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  102346. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  102347. if (sd < -dir1l) sd = -dir1l;
  102348. else if (sd > dir1l) sd = dir1l;
  102349. if (ed < -dir2l) ed = -dir2l;
  102350. else if (ed > dir2l) ed = dir2l;
  102351. tx = sd * dir1x + ed * dir2x;
  102352. ty = sd * dir1y + ed * dir2y;
  102353. tz = sd * dir1z + ed * dir2z;
  102354. px = cbx + tx;
  102355. py = cby + ty;
  102356. pz = cbz + tz;
  102357. //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,2,0,false);
  102358. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  102359. }
  102360. px = dx * r00 + dy * r01 + dz * r02;
  102361. py = dx * r10 + dy * r11 + dz * r12;
  102362. pz = dx * r20 + dy * r21 + dz * r22;
  102363. px = (dx = px) + ccx;
  102364. py = (dy = py) + ccy;
  102365. pz = (dz = pz) + ccz;
  102366. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  102367. if (pd <= 0) {
  102368. tx = px - pd * nx - cbx;
  102369. ty = py - pd * ny - cby;
  102370. tz = pz - pd * nz - cbz;
  102371. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  102372. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  102373. if (sd < -dir1l) sd = -dir1l;
  102374. else if (sd > dir1l) sd = dir1l;
  102375. if (ed < -dir2l) ed = -dir2l;
  102376. else if (ed > dir2l) ed = dir2l;
  102377. tx = sd * dir1x + ed * dir2x;
  102378. ty = sd * dir1y + ed * dir2y;
  102379. tz = sd * dir1z + ed * dir2z;
  102380. px = cbx + tx;
  102381. py = cby + ty;
  102382. pz = cbz + tz;
  102383. //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,3,0,false);
  102384. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  102385. }
  102386. } else {
  102387. sx = tx;
  102388. sy = ty;
  102389. sz = tz;
  102390. sd = nx * (sx - cbx) + ny * (sy - cby) + nz * (sz - cbz);
  102391. sx -= sd * nx;
  102392. sy -= sd * ny;
  102393. sz -= sd * nz;
  102394. if (dot > 0) {
  102395. ex = tx + dcx * 2;
  102396. ey = ty + dcy * 2;
  102397. ez = tz + dcz * 2;
  102398. } else {
  102399. ex = tx - dcx * 2;
  102400. ey = ty - dcy * 2;
  102401. ez = tz - dcz * 2;
  102402. }
  102403. ed = nx * (ex - cbx) + ny * (ey - cby) + nz * (ez - cbz);
  102404. ex -= ed * nx;
  102405. ey -= ed * ny;
  102406. ez -= ed * nz;
  102407. d1x = sx - cbx;
  102408. d1y = sy - cby;
  102409. d1z = sz - cbz;
  102410. d2x = ex - cbx;
  102411. d2y = ey - cby;
  102412. d2z = ez - cbz;
  102413. tx = ex - sx;
  102414. ty = ey - sy;
  102415. tz = ez - sz;
  102416. td = ed - sd;
  102417. dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
  102418. doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
  102419. dot1 = dotw - dir1l;
  102420. dot2 = doth - dir1l;
  102421. if (dot1 > 0) {
  102422. if (dot2 > 0) return;
  102423. t1 = dot1 / (dot1 - dot2);
  102424. sx = sx + tx * t1;
  102425. sy = sy + ty * t1;
  102426. sz = sz + tz * t1;
  102427. sd = sd + td * t1;
  102428. d1x = sx - cbx;
  102429. d1y = sy - cby;
  102430. d1z = sz - cbz;
  102431. dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
  102432. tx = ex - sx;
  102433. ty = ey - sy;
  102434. tz = ez - sz;
  102435. td = ed - sd;
  102436. } else if (dot2 > 0) {
  102437. t1 = dot1 / (dot1 - dot2);
  102438. ex = sx + tx * t1;
  102439. ey = sy + ty * t1;
  102440. ez = sz + tz * t1;
  102441. ed = sd + td * t1;
  102442. d2x = ex - cbx;
  102443. d2y = ey - cby;
  102444. d2z = ez - cbz;
  102445. doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
  102446. tx = ex - sx;
  102447. ty = ey - sy;
  102448. tz = ez - sz;
  102449. td = ed - sd;
  102450. }
  102451. dot1 = dotw + dir1l;
  102452. dot2 = doth + dir1l;
  102453. if (dot1 < 0) {
  102454. if (dot2 < 0) return;
  102455. t1 = dot1 / (dot1 - dot2);
  102456. sx = sx + tx * t1;
  102457. sy = sy + ty * t1;
  102458. sz = sz + tz * t1;
  102459. sd = sd + td * t1;
  102460. d1x = sx - cbx;
  102461. d1y = sy - cby;
  102462. d1z = sz - cbz;
  102463. tx = ex - sx;
  102464. ty = ey - sy;
  102465. tz = ez - sz;
  102466. td = ed - sd;
  102467. } else if (dot2 < 0) {
  102468. t1 = dot1 / (dot1 - dot2);
  102469. ex = sx + tx * t1;
  102470. ey = sy + ty * t1;
  102471. ez = sz + tz * t1;
  102472. ed = sd + td * t1;
  102473. d2x = ex - cbx;
  102474. d2y = ey - cby;
  102475. d2z = ez - cbz;
  102476. tx = ex - sx;
  102477. ty = ey - sy;
  102478. tz = ez - sz;
  102479. td = ed - sd;
  102480. }
  102481. dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
  102482. doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
  102483. dot1 = dotw - dir2l;
  102484. dot2 = doth - dir2l;
  102485. if (dot1 > 0) {
  102486. if (dot2 > 0) return;
  102487. t1 = dot1 / (dot1 - dot2);
  102488. sx = sx + tx * t1;
  102489. sy = sy + ty * t1;
  102490. sz = sz + tz * t1;
  102491. sd = sd + td * t1;
  102492. d1x = sx - cbx;
  102493. d1y = sy - cby;
  102494. d1z = sz - cbz;
  102495. dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
  102496. tx = ex - sx;
  102497. ty = ey - sy;
  102498. tz = ez - sz;
  102499. td = ed - sd;
  102500. } else if (dot2 > 0) {
  102501. t1 = dot1 / (dot1 - dot2);
  102502. ex = sx + tx * t1;
  102503. ey = sy + ty * t1;
  102504. ez = sz + tz * t1;
  102505. ed = sd + td * t1;
  102506. d2x = ex - cbx;
  102507. d2y = ey - cby;
  102508. d2z = ez - cbz;
  102509. doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
  102510. tx = ex - sx;
  102511. ty = ey - sy;
  102512. tz = ez - sz;
  102513. td = ed - sd;
  102514. }
  102515. dot1 = dotw + dir2l;
  102516. dot2 = doth + dir2l;
  102517. if (dot1 < 0) {
  102518. if (dot2 < 0) return;
  102519. t1 = dot1 / (dot1 - dot2);
  102520. sx = sx + tx * t1;
  102521. sy = sy + ty * t1;
  102522. sz = sz + tz * t1;
  102523. sd = sd + td * t1;
  102524. } else if (dot2 < 0) {
  102525. t1 = dot1 / (dot1 - dot2);
  102526. ex = sx + tx * t1;
  102527. ey = sy + ty * t1;
  102528. ez = sz + tz * t1;
  102529. ed = sd + td * t1;
  102530. }
  102531. if (sd < 0) {
  102532. //manifold.addPoint(sx,sy,sz,nx,ny,nz,sd,b,c,1,0,false);
  102533. manifold.addPoint(sx, sy, sz, nx, ny, nz, sd, this.flip);
  102534. }
  102535. if (ed < 0) {
  102536. //manifold.addPoint(ex,ey,ez,nx,ny,nz,ed,b,c,4,0,false);
  102537. manifold.addPoint(ex, ey, ez, nx, ny, nz, ed, this.flip);
  102538. }
  102539. }
  102540. }
  102541. };
  102542. OIMO.CylinderCylinderCollisionDetector = function () {
  102543. OIMO.CollisionDetector.call(this);
  102544. };
  102545. OIMO.CylinderCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  102546. OIMO.CylinderCylinderCollisionDetector.prototype.constructor = OIMO.CylinderCylinderCollisionDetector;
  102547. OIMO.CylinderCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
  102548. var t1x;
  102549. var t1y;
  102550. var t1z;
  102551. var t2x;
  102552. var t2y;
  102553. var t2z;
  102554. var sup = new OIMO.Vec3();
  102555. var len;
  102556. var p1x;
  102557. var p1y;
  102558. var p1z;
  102559. var p2x;
  102560. var p2y;
  102561. var p2z;
  102562. var v01x = c1.position.x;
  102563. var v01y = c1.position.y;
  102564. var v01z = c1.position.z;
  102565. var v02x = c2.position.x;
  102566. var v02y = c2.position.y;
  102567. var v02z = c2.position.z;
  102568. var v0x = v02x - v01x;
  102569. var v0y = v02y - v01y;
  102570. var v0z = v02z - v01z;
  102571. if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
  102572. var nx = -v0x;
  102573. var ny = -v0y;
  102574. var nz = -v0z;
  102575. this.supportPoint(c1, -nx, -ny, -nz, sup);
  102576. var v11x = sup.x;
  102577. var v11y = sup.y;
  102578. var v11z = sup.z;
  102579. this.supportPoint(c2, nx, ny, nz, sup);
  102580. var v12x = sup.x;
  102581. var v12y = sup.y;
  102582. var v12z = sup.z;
  102583. var v1x = v12x - v11x;
  102584. var v1y = v12y - v11y;
  102585. var v1z = v12z - v11z;
  102586. if (v1x * nx + v1y * ny + v1z * nz <= 0) {
  102587. return false;
  102588. }
  102589. nx = v1y * v0z - v1z * v0y;
  102590. ny = v1z * v0x - v1x * v0z;
  102591. nz = v1x * v0y - v1y * v0x;
  102592. if (nx * nx + ny * ny + nz * nz == 0) {
  102593. sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
  102594. sep.normalize(sep);
  102595. pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
  102596. return true;
  102597. }
  102598. this.supportPoint(c1, -nx, -ny, -nz, sup);
  102599. var v21x = sup.x;
  102600. var v21y = sup.y;
  102601. var v21z = sup.z;
  102602. this.supportPoint(c2, nx, ny, nz, sup);
  102603. var v22x = sup.x;
  102604. var v22y = sup.y;
  102605. var v22z = sup.z;
  102606. var v2x = v22x - v21x;
  102607. var v2y = v22y - v21y;
  102608. var v2z = v22z - v21z;
  102609. if (v2x * nx + v2y * ny + v2z * nz <= 0) {
  102610. return false;
  102611. }
  102612. t1x = v1x - v0x;
  102613. t1y = v1y - v0y;
  102614. t1z = v1z - v0z;
  102615. t2x = v2x - v0x;
  102616. t2y = v2y - v0y;
  102617. t2z = v2z - v0z;
  102618. nx = t1y * t2z - t1z * t2y;
  102619. ny = t1z * t2x - t1x * t2z;
  102620. nz = t1x * t2y - t1y * t2x;
  102621. if (nx * v0x + ny * v0y + nz * v0z > 0) {
  102622. t1x = v1x;
  102623. t1y = v1y;
  102624. t1z = v1z;
  102625. v1x = v2x;
  102626. v1y = v2y;
  102627. v1z = v2z;
  102628. v2x = t1x;
  102629. v2y = t1y;
  102630. v2z = t1z;
  102631. t1x = v11x;
  102632. t1y = v11y;
  102633. t1z = v11z;
  102634. v11x = v21x;
  102635. v11y = v21y;
  102636. v11z = v21z;
  102637. v21x = t1x;
  102638. v21y = t1y;
  102639. v21z = t1z;
  102640. t1x = v12x;
  102641. t1y = v12y;
  102642. t1z = v12z;
  102643. v12x = v22x;
  102644. v12y = v22y;
  102645. v12z = v22z;
  102646. v22x = t1x;
  102647. v22y = t1y;
  102648. v22z = t1z;
  102649. nx = -nx;
  102650. ny = -ny;
  102651. nz = -nz;
  102652. }
  102653. var iterations = 0;
  102654. while (true) {
  102655. if (++iterations > 100) {
  102656. return false;
  102657. }
  102658. this.supportPoint(c1, -nx, -ny, -nz, sup);
  102659. var v31x = sup.x;
  102660. var v31y = sup.y;
  102661. var v31z = sup.z;
  102662. this.supportPoint(c2, nx, ny, nz, sup);
  102663. var v32x = sup.x;
  102664. var v32y = sup.y;
  102665. var v32z = sup.z;
  102666. var v3x = v32x - v31x;
  102667. var v3y = v32y - v31y;
  102668. var v3z = v32z - v31z;
  102669. if (v3x * nx + v3y * ny + v3z * nz <= 0) {
  102670. return false;
  102671. }
  102672. if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
  102673. v2x = v3x;
  102674. v2y = v3y;
  102675. v2z = v3z;
  102676. v21x = v31x;
  102677. v21y = v31y;
  102678. v21z = v31z;
  102679. v22x = v32x;
  102680. v22y = v32y;
  102681. v22z = v32z;
  102682. t1x = v1x - v0x;
  102683. t1y = v1y - v0y;
  102684. t1z = v1z - v0z;
  102685. t2x = v3x - v0x;
  102686. t2y = v3y - v0y;
  102687. t2z = v3z - v0z;
  102688. nx = t1y * t2z - t1z * t2y;
  102689. ny = t1z * t2x - t1x * t2z;
  102690. nz = t1x * t2y - t1y * t2x;
  102691. continue;
  102692. }
  102693. if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
  102694. v1x = v3x;
  102695. v1y = v3y;
  102696. v1z = v3z;
  102697. v11x = v31x;
  102698. v11y = v31y;
  102699. v11z = v31z;
  102700. v12x = v32x;
  102701. v12y = v32y;
  102702. v12z = v32z;
  102703. t1x = v3x - v0x;
  102704. t1y = v3y - v0y;
  102705. t1z = v3z - v0z;
  102706. t2x = v2x - v0x;
  102707. t2y = v2y - v0y;
  102708. t2z = v2z - v0z;
  102709. nx = t1y * t2z - t1z * t2y;
  102710. ny = t1z * t2x - t1x * t2z;
  102711. nz = t1x * t2y - t1y * t2x;
  102712. continue;
  102713. }
  102714. var hit = false;
  102715. while (true) {
  102716. t1x = v2x - v1x;
  102717. t1y = v2y - v1y;
  102718. t1z = v2z - v1z;
  102719. t2x = v3x - v1x;
  102720. t2y = v3y - v1y;
  102721. t2z = v3z - v1z;
  102722. nx = t1y * t2z - t1z * t2y;
  102723. ny = t1z * t2x - t1x * t2z;
  102724. nz = t1x * t2y - t1y * t2x;
  102725. len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  102726. nx *= len;
  102727. ny *= len;
  102728. nz *= len;
  102729. if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
  102730. var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
  102731. var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
  102732. var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
  102733. var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
  102734. var sum = b0 + b1 + b2 + b3;
  102735. if (sum <= 0) {
  102736. b0 = 0;
  102737. b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
  102738. b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
  102739. b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
  102740. sum = b1 + b2 + b3;
  102741. }
  102742. var inv = 1 / sum;
  102743. p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
  102744. p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
  102745. p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
  102746. p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
  102747. p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
  102748. p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
  102749. hit = true;
  102750. }
  102751. this.supportPoint(c1, -nx, -ny, -nz, sup);
  102752. var v41x = sup.x;
  102753. var v41y = sup.y;
  102754. var v41z = sup.z;
  102755. this.supportPoint(c2, nx, ny, nz, sup);
  102756. var v42x = sup.x;
  102757. var v42y = sup.y;
  102758. var v42z = sup.z;
  102759. var v4x = v42x - v41x;
  102760. var v4y = v42y - v41y;
  102761. var v4z = v42z - v41z;
  102762. var separation = -(v4x * nx + v4y * ny + v4z * nz);
  102763. if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
  102764. if (hit) {
  102765. sep.init(-nx, -ny, -nz);
  102766. pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
  102767. dep.x = separation;
  102768. return true;
  102769. }
  102770. return false;
  102771. }
  102772. if (
  102773. (v4y * v1z - v4z * v1y) * v0x +
  102774. (v4z * v1x - v4x * v1z) * v0y +
  102775. (v4x * v1y - v4y * v1x) * v0z < 0
  102776. ) {
  102777. if (
  102778. (v4y * v2z - v4z * v2y) * v0x +
  102779. (v4z * v2x - v4x * v2z) * v0y +
  102780. (v4x * v2y - v4y * v2x) * v0z < 0
  102781. ) {
  102782. v1x = v4x;
  102783. v1y = v4y;
  102784. v1z = v4z;
  102785. v11x = v41x;
  102786. v11y = v41y;
  102787. v11z = v41z;
  102788. v12x = v42x;
  102789. v12y = v42y;
  102790. v12z = v42z;
  102791. } else {
  102792. v3x = v4x;
  102793. v3y = v4y;
  102794. v3z = v4z;
  102795. v31x = v41x;
  102796. v31y = v41y;
  102797. v31z = v41z;
  102798. v32x = v42x;
  102799. v32y = v42y;
  102800. v32z = v42z;
  102801. }
  102802. } else {
  102803. if (
  102804. (v4y * v3z - v4z * v3y) * v0x +
  102805. (v4z * v3x - v4x * v3z) * v0y +
  102806. (v4x * v3y - v4y * v3x) * v0z < 0
  102807. ) {
  102808. v2x = v4x;
  102809. v2y = v4y;
  102810. v2z = v4z;
  102811. v21x = v41x;
  102812. v21y = v41y;
  102813. v21z = v41z;
  102814. v22x = v42x;
  102815. v22y = v42y;
  102816. v22z = v42z;
  102817. } else {
  102818. v1x = v4x;
  102819. v1y = v4y;
  102820. v1z = v4z;
  102821. v11x = v41x;
  102822. v11y = v41y;
  102823. v11z = v41z;
  102824. v12x = v42x;
  102825. v12y = v42y;
  102826. v12z = v42z;
  102827. }
  102828. }
  102829. }
  102830. }
  102831. //return false;
  102832. };
  102833. OIMO.CylinderCylinderCollisionDetector.prototype.supportPoint = function (c, dx, dy, dz, out) {
  102834. var rot = c.rotation.elements;
  102835. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  102836. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  102837. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  102838. var radx = ldx;
  102839. var radz = ldz;
  102840. var len = radx * radx + radz * radz;
  102841. var rad = c.radius;
  102842. var hh = c.halfHeight;
  102843. var ox;
  102844. var oy;
  102845. var oz;
  102846. if (len == 0) {
  102847. if (ldy < 0) {
  102848. ox = rad;
  102849. oy = -hh;
  102850. oz = 0;
  102851. } else {
  102852. ox = rad;
  102853. oy = hh;
  102854. oz = 0;
  102855. }
  102856. } else {
  102857. len = c.radius / OIMO.sqrt(len);
  102858. if (ldy < 0) {
  102859. ox = radx * len;
  102860. oy = -hh;
  102861. oz = radz * len;
  102862. } else {
  102863. ox = radx * len;
  102864. oy = hh;
  102865. oz = radz * len;
  102866. }
  102867. }
  102868. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  102869. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  102870. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  102871. out.init(ldx, ldy, ldz);
  102872. };
  102873. OIMO.CylinderCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  102874. var c1;
  102875. var c2;
  102876. if (shape1.id < shape2.id) {
  102877. c1 = shape1;
  102878. c2 = shape2;
  102879. } else {
  102880. c1 = shape2;
  102881. c2 = shape1;
  102882. }
  102883. var p1 = c1.position;
  102884. var p2 = c2.position;
  102885. var p1x = p1.x;
  102886. var p1y = p1.y;
  102887. var p1z = p1.z;
  102888. var p2x = p2.x;
  102889. var p2y = p2.y;
  102890. var p2z = p2.z;
  102891. var h1 = c1.halfHeight;
  102892. var h2 = c2.halfHeight;
  102893. var n1 = c1.normalDirection;
  102894. var n2 = c2.normalDirection;
  102895. var d1 = c1.halfDirection;
  102896. var d2 = c2.halfDirection;
  102897. var r1 = c1.radius;
  102898. var r2 = c2.radius;
  102899. var n1x = n1.x;
  102900. var n1y = n1.y;
  102901. var n1z = n1.z;
  102902. var n2x = n2.x;
  102903. var n2y = n2.y;
  102904. var n2z = n2.z;
  102905. var d1x = d1.x;
  102906. var d1y = d1.y;
  102907. var d1z = d1.z;
  102908. var d2x = d2.x;
  102909. var d2y = d2.y;
  102910. var d2z = d2.z;
  102911. var dx = p1x - p2x;
  102912. var dy = p1y - p2y;
  102913. var dz = p1z - p2z;
  102914. var len;
  102915. var len1;
  102916. var len2;
  102917. var c;
  102918. var c1x;
  102919. var c1y;
  102920. var c1z;
  102921. var c2x;
  102922. var c2y;
  102923. var c2z;
  102924. var tx;
  102925. var ty;
  102926. var tz;
  102927. var sx;
  102928. var sy;
  102929. var sz;
  102930. var ex;
  102931. var ey;
  102932. var ez;
  102933. var depth1;
  102934. var depth2;
  102935. var dot;
  102936. var t1;
  102937. var t2;
  102938. var sep = new OIMO.Vec3();
  102939. var pos = new OIMO.Vec3();
  102940. var dep = new OIMO.Vec3();
  102941. if (!this.getSep(c1, c2, sep, pos, dep)) return;
  102942. var dot1 = sep.x * n1x + sep.y * n1y + sep.z * n1z;
  102943. var dot2 = sep.x * n2x + sep.y * n2y + sep.z * n2z;
  102944. var right1 = dot1 > 0;
  102945. var right2 = dot2 > 0;
  102946. if (!right1) dot1 = -dot1;
  102947. if (!right2) dot2 = -dot2;
  102948. var state = 0;
  102949. if (dot1 > 0.999 || dot2 > 0.999) {
  102950. if (dot1 > dot2) state = 1;
  102951. else state = 2;
  102952. }
  102953. var nx;
  102954. var ny;
  102955. var nz;
  102956. var depth = dep.x;
  102957. var r00;
  102958. var r01;
  102959. var r02;
  102960. var r10;
  102961. var r11;
  102962. var r12;
  102963. var r20;
  102964. var r21;
  102965. var r22;
  102966. var px;
  102967. var py;
  102968. var pz;
  102969. var pd;
  102970. var a;
  102971. var b;
  102972. var e;
  102973. var f;
  102974. nx = sep.x;
  102975. ny = sep.y;
  102976. nz = sep.z;
  102977. switch (state) {
  102978. case 0:
  102979. manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, depth, false);
  102980. break;
  102981. case 1:
  102982. if (right1) {
  102983. c1x = p1x + d1x;
  102984. c1y = p1y + d1y;
  102985. c1z = p1z + d1z;
  102986. nx = n1x;
  102987. ny = n1y;
  102988. nz = n1z;
  102989. } else {
  102990. c1x = p1x - d1x;
  102991. c1y = p1y - d1y;
  102992. c1z = p1z - d1z;
  102993. nx = -n1x;
  102994. ny = -n1y;
  102995. nz = -n1z;
  102996. }
  102997. dot = nx * n2x + ny * n2y + nz * n2z;
  102998. if (dot < 0) len = h2;
  102999. else len = -h2;
  103000. c2x = p2x + len * n2x;
  103001. c2y = p2y + len * n2y;
  103002. c2z = p2z + len * n2z;
  103003. if (dot2 >= 0.999999) {
  103004. tx = -ny;
  103005. ty = nz;
  103006. tz = nx;
  103007. } else {
  103008. tx = nx;
  103009. ty = ny;
  103010. tz = nz;
  103011. }
  103012. len = tx * n2x + ty * n2y + tz * n2z;
  103013. dx = len * n2x - tx;
  103014. dy = len * n2y - ty;
  103015. dz = len * n2z - tz;
  103016. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  103017. if (len == 0) break;
  103018. len = r2 / len;
  103019. dx *= len;
  103020. dy *= len;
  103021. dz *= len;
  103022. tx = c2x + dx;
  103023. ty = c2y + dy;
  103024. tz = c2z + dz;
  103025. if (dot < -0.96 || dot > 0.96) {
  103026. r00 = n2x * n2x * 1.5 - 0.5;
  103027. r01 = n2x * n2y * 1.5 - n2z * 0.866025403;
  103028. r02 = n2x * n2z * 1.5 + n2y * 0.866025403;
  103029. r10 = n2y * n2x * 1.5 + n2z * 0.866025403;
  103030. r11 = n2y * n2y * 1.5 - 0.5;
  103031. r12 = n2y * n2z * 1.5 - n2x * 0.866025403;
  103032. r20 = n2z * n2x * 1.5 - n2y * 0.866025403;
  103033. r21 = n2z * n2y * 1.5 + n2x * 0.866025403;
  103034. r22 = n2z * n2z * 1.5 - 0.5;
  103035. px = tx;
  103036. py = ty;
  103037. pz = tz;
  103038. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  103039. tx = px - pd * nx - c1x;
  103040. ty = py - pd * ny - c1y;
  103041. tz = pz - pd * nz - c1z;
  103042. len = tx * tx + ty * ty + tz * tz;
  103043. if (len > r1 * r1) {
  103044. len = r1 / OIMO.sqrt(len);
  103045. tx *= len;
  103046. ty *= len;
  103047. tz *= len;
  103048. }
  103049. px = c1x + tx;
  103050. py = c1y + ty;
  103051. pz = c1z + tz;
  103052. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  103053. px = dx * r00 + dy * r01 + dz * r02;
  103054. py = dx * r10 + dy * r11 + dz * r12;
  103055. pz = dx * r20 + dy * r21 + dz * r22;
  103056. px = (dx = px) + c2x;
  103057. py = (dy = py) + c2y;
  103058. pz = (dz = pz) + c2z;
  103059. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  103060. if (pd <= 0) {
  103061. tx = px - pd * nx - c1x;
  103062. ty = py - pd * ny - c1y;
  103063. tz = pz - pd * nz - c1z;
  103064. len = tx * tx + ty * ty + tz * tz;
  103065. if (len > r1 * r1) {
  103066. len = r1 / OIMO.sqrt(len);
  103067. tx *= len;
  103068. ty *= len;
  103069. tz *= len;
  103070. }
  103071. px = c1x + tx;
  103072. py = c1y + ty;
  103073. pz = c1z + tz;
  103074. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  103075. }
  103076. px = dx * r00 + dy * r01 + dz * r02;
  103077. py = dx * r10 + dy * r11 + dz * r12;
  103078. pz = dx * r20 + dy * r21 + dz * r22;
  103079. px = (dx = px) + c2x;
  103080. py = (dy = py) + c2y;
  103081. pz = (dz = pz) + c2z;
  103082. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  103083. if (pd <= 0) {
  103084. tx = px - pd * nx - c1x;
  103085. ty = py - pd * ny - c1y;
  103086. tz = pz - pd * nz - c1z;
  103087. len = tx * tx + ty * ty + tz * tz;
  103088. if (len > r1 * r1) {
  103089. len = r1 / OIMO.sqrt(len);
  103090. tx *= len;
  103091. ty *= len;
  103092. tz *= len;
  103093. }
  103094. px = c1x + tx;
  103095. py = c1y + ty;
  103096. pz = c1z + tz;
  103097. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  103098. }
  103099. } else {
  103100. sx = tx;
  103101. sy = ty;
  103102. sz = tz;
  103103. depth1 = nx * (sx - c1x) + ny * (sy - c1y) + nz * (sz - c1z);
  103104. sx -= depth1 * nx;
  103105. sy -= depth1 * ny;
  103106. sz -= depth1 * nz;
  103107. if (dot > 0) {
  103108. ex = tx + n2x * h2 * 2;
  103109. ey = ty + n2y * h2 * 2;
  103110. ez = tz + n2z * h2 * 2;
  103111. } else {
  103112. ex = tx - n2x * h2 * 2;
  103113. ey = ty - n2y * h2 * 2;
  103114. ez = tz - n2z * h2 * 2;
  103115. }
  103116. depth2 = nx * (ex - c1x) + ny * (ey - c1y) + nz * (ez - c1z);
  103117. ex -= depth2 * nx;
  103118. ey -= depth2 * ny;
  103119. ez -= depth2 * nz;
  103120. dx = c1x - sx;
  103121. dy = c1y - sy;
  103122. dz = c1z - sz;
  103123. tx = ex - sx;
  103124. ty = ey - sy;
  103125. tz = ez - sz;
  103126. a = dx * dx + dy * dy + dz * dz;
  103127. b = dx * tx + dy * ty + dz * tz;
  103128. e = tx * tx + ty * ty + tz * tz;
  103129. f = b * b - e * (a - r1 * r1);
  103130. if (f < 0) break;
  103131. f = OIMO.sqrt(f);
  103132. t1 = (b + f) / e;
  103133. t2 = (b - f) / e;
  103134. if (t2 < t1) {
  103135. len = t1;
  103136. t1 = t2;
  103137. t2 = len;
  103138. }
  103139. if (t2 > 1) t2 = 1;
  103140. if (t1 < 0) t1 = 0;
  103141. tx = sx + (ex - sx) * t1;
  103142. ty = sy + (ey - sy) * t1;
  103143. tz = sz + (ez - sz) * t1;
  103144. ex = sx + (ex - sx) * t2;
  103145. ey = sy + (ey - sy) * t2;
  103146. ez = sz + (ez - sz) * t2;
  103147. sx = tx;
  103148. sy = ty;
  103149. sz = tz;
  103150. len = depth1 + (depth2 - depth1) * t1;
  103151. depth2 = depth1 + (depth2 - depth1) * t2;
  103152. depth1 = len;
  103153. if (depth1 < 0) manifold.addPoint(sx, sy, sz, nx, ny, nz, pd, false);
  103154. if (depth2 < 0) manifold.addPoint(ex, ey, ez, nx, ny, nz, pd, false);
  103155. }
  103156. break;
  103157. case 2:
  103158. if (right2) {
  103159. c2x = p2x - d2x;
  103160. c2y = p2y - d2y;
  103161. c2z = p2z - d2z;
  103162. nx = -n2x;
  103163. ny = -n2y;
  103164. nz = -n2z;
  103165. } else {
  103166. c2x = p2x + d2x;
  103167. c2y = p2y + d2y;
  103168. c2z = p2z + d2z;
  103169. nx = n2x;
  103170. ny = n2y;
  103171. nz = n2z;
  103172. }
  103173. dot = nx * n1x + ny * n1y + nz * n1z;
  103174. if (dot < 0) len = h1;
  103175. else len = -h1;
  103176. c1x = p1x + len * n1x;
  103177. c1y = p1y + len * n1y;
  103178. c1z = p1z + len * n1z;
  103179. if (dot1 >= 0.999999) {
  103180. tx = -ny;
  103181. ty = nz;
  103182. tz = nx;
  103183. } else {
  103184. tx = nx;
  103185. ty = ny;
  103186. tz = nz;
  103187. }
  103188. len = tx * n1x + ty * n1y + tz * n1z;
  103189. dx = len * n1x - tx;
  103190. dy = len * n1y - ty;
  103191. dz = len * n1z - tz;
  103192. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  103193. if (len == 0) break;
  103194. len = r1 / len;
  103195. dx *= len;
  103196. dy *= len;
  103197. dz *= len;
  103198. tx = c1x + dx;
  103199. ty = c1y + dy;
  103200. tz = c1z + dz;
  103201. if (dot < -0.96 || dot > 0.96) {
  103202. r00 = n1x * n1x * 1.5 - 0.5;
  103203. r01 = n1x * n1y * 1.5 - n1z * 0.866025403;
  103204. r02 = n1x * n1z * 1.5 + n1y * 0.866025403;
  103205. r10 = n1y * n1x * 1.5 + n1z * 0.866025403;
  103206. r11 = n1y * n1y * 1.5 - 0.5;
  103207. r12 = n1y * n1z * 1.5 - n1x * 0.866025403;
  103208. r20 = n1z * n1x * 1.5 - n1y * 0.866025403;
  103209. r21 = n1z * n1y * 1.5 + n1x * 0.866025403;
  103210. r22 = n1z * n1z * 1.5 - 0.5;
  103211. px = tx;
  103212. py = ty;
  103213. pz = tz;
  103214. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  103215. tx = px - pd * nx - c2x;
  103216. ty = py - pd * ny - c2y;
  103217. tz = pz - pd * nz - c2z;
  103218. len = tx * tx + ty * ty + tz * tz;
  103219. if (len > r2 * r2) {
  103220. len = r2 / OIMO.sqrt(len);
  103221. tx *= len;
  103222. ty *= len;
  103223. tz *= len;
  103224. }
  103225. px = c2x + tx;
  103226. py = c2y + ty;
  103227. pz = c2z + tz;
  103228. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  103229. px = dx * r00 + dy * r01 + dz * r02;
  103230. py = dx * r10 + dy * r11 + dz * r12;
  103231. pz = dx * r20 + dy * r21 + dz * r22;
  103232. px = (dx = px) + c1x;
  103233. py = (dy = py) + c1y;
  103234. pz = (dz = pz) + c1z;
  103235. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  103236. if (pd <= 0) {
  103237. tx = px - pd * nx - c2x;
  103238. ty = py - pd * ny - c2y;
  103239. tz = pz - pd * nz - c2z;
  103240. len = tx * tx + ty * ty + tz * tz;
  103241. if (len > r2 * r2) {
  103242. len = r2 / OIMO.sqrt(len);
  103243. tx *= len;
  103244. ty *= len;
  103245. tz *= len;
  103246. }
  103247. px = c2x + tx;
  103248. py = c2y + ty;
  103249. pz = c2z + tz;
  103250. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  103251. }
  103252. px = dx * r00 + dy * r01 + dz * r02;
  103253. py = dx * r10 + dy * r11 + dz * r12;
  103254. pz = dx * r20 + dy * r21 + dz * r22;
  103255. px = (dx = px) + c1x;
  103256. py = (dy = py) + c1y;
  103257. pz = (dz = pz) + c1z;
  103258. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  103259. if (pd <= 0) {
  103260. tx = px - pd * nx - c2x;
  103261. ty = py - pd * ny - c2y;
  103262. tz = pz - pd * nz - c2z;
  103263. len = tx * tx + ty * ty + tz * tz;
  103264. if (len > r2 * r2) {
  103265. len = r2 / OIMO.sqrt(len);
  103266. tx *= len;
  103267. ty *= len;
  103268. tz *= len;
  103269. }
  103270. px = c2x + tx;
  103271. py = c2y + ty;
  103272. pz = c2z + tz;
  103273. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  103274. }
  103275. } else {
  103276. sx = tx;
  103277. sy = ty;
  103278. sz = tz;
  103279. depth1 = nx * (sx - c2x) + ny * (sy - c2y) + nz * (sz - c2z);
  103280. sx -= depth1 * nx;
  103281. sy -= depth1 * ny;
  103282. sz -= depth1 * nz;
  103283. if (dot > 0) {
  103284. ex = tx + n1x * h1 * 2;
  103285. ey = ty + n1y * h1 * 2;
  103286. ez = tz + n1z * h1 * 2;
  103287. } else {
  103288. ex = tx - n1x * h1 * 2;
  103289. ey = ty - n1y * h1 * 2;
  103290. ez = tz - n1z * h1 * 2;
  103291. }
  103292. depth2 = nx * (ex - c2x) + ny * (ey - c2y) + nz * (ez - c2z);
  103293. ex -= depth2 * nx;
  103294. ey -= depth2 * ny;
  103295. ez -= depth2 * nz;
  103296. dx = c2x - sx;
  103297. dy = c2y - sy;
  103298. dz = c2z - sz;
  103299. tx = ex - sx;
  103300. ty = ey - sy;
  103301. tz = ez - sz;
  103302. a = dx * dx + dy * dy + dz * dz;
  103303. b = dx * tx + dy * ty + dz * tz;
  103304. e = tx * tx + ty * ty + tz * tz;
  103305. f = b * b - e * (a - r2 * r2);
  103306. if (f < 0) break;
  103307. f = OIMO.sqrt(f);
  103308. t1 = (b + f) / e;
  103309. t2 = (b - f) / e;
  103310. if (t2 < t1) {
  103311. len = t1;
  103312. t1 = t2;
  103313. t2 = len;
  103314. }
  103315. if (t2 > 1) t2 = 1;
  103316. if (t1 < 0) t1 = 0;
  103317. tx = sx + (ex - sx) * t1;
  103318. ty = sy + (ey - sy) * t1;
  103319. tz = sz + (ez - sz) * t1;
  103320. ex = sx + (ex - sx) * t2;
  103321. ey = sy + (ey - sy) * t2;
  103322. ez = sz + (ez - sz) * t2;
  103323. sx = tx;
  103324. sy = ty;
  103325. sz = tz;
  103326. len = depth1 + (depth2 - depth1) * t1;
  103327. depth2 = depth1 + (depth2 - depth1) * t2;
  103328. depth1 = len;
  103329. if (depth1 < 0) {
  103330. manifold.addPoint(sx, sy, sz, -nx, -ny, -nz, depth1, false);
  103331. }
  103332. if (depth2 < 0) {
  103333. manifold.addPoint(ex, ey, ez, -nx, -ny, -nz, depth2, false);
  103334. }
  103335. }
  103336. break;
  103337. }
  103338. };
  103339. OIMO.SphereCylinderCollisionDetector = function (flip) {
  103340. OIMO.CollisionDetector.call(this);
  103341. this.flip = flip;
  103342. };
  103343. OIMO.SphereCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  103344. OIMO.SphereCylinderCollisionDetector.prototype.constructor = OIMO.SphereCylinderCollisionDetector;
  103345. OIMO.SphereCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  103346. var s;
  103347. var c;
  103348. if (this.flip) {
  103349. s = shape2;
  103350. c = shape1;
  103351. } else {
  103352. s = shape1;
  103353. c = shape2;
  103354. }
  103355. var ps = s.position;
  103356. var psx = ps.x;
  103357. var psy = ps.y;
  103358. var psz = ps.z;
  103359. var pc = c.position;
  103360. var pcx = pc.x;
  103361. var pcy = pc.y;
  103362. var pcz = pc.z;
  103363. var dirx = c.normalDirection.x;
  103364. var diry = c.normalDirection.y;
  103365. var dirz = c.normalDirection.z;
  103366. var rads = s.radius;
  103367. var radc = c.radius;
  103368. var rad2 = rads + radc;
  103369. var halfh = c.halfHeight;
  103370. var dx = psx - pcx;
  103371. var dy = psy - pcy;
  103372. var dz = psz - pcz;
  103373. var dot = dx * dirx + dy * diry + dz * dirz;
  103374. if (dot < -halfh - rads || dot > halfh + rads) return;
  103375. var cx = pcx + dot * dirx;
  103376. var cy = pcy + dot * diry;
  103377. var cz = pcz + dot * dirz;
  103378. var d2x = psx - cx;
  103379. var d2y = psy - cy;
  103380. var d2z = psz - cz;
  103381. var len = d2x * d2x + d2y * d2y + d2z * d2z;
  103382. if (len > rad2 * rad2) return;
  103383. if (len > radc * radc) {
  103384. len = radc / OIMO.sqrt(len);
  103385. d2x *= len;
  103386. d2y *= len;
  103387. d2z *= len;
  103388. }
  103389. if (dot < -halfh) dot = -halfh;
  103390. else if (dot > halfh) dot = halfh;
  103391. cx = pcx + dot * dirx + d2x;
  103392. cy = pcy + dot * diry + d2y;
  103393. cz = pcz + dot * dirz + d2z;
  103394. dx = cx - psx;
  103395. dy = cy - psy;
  103396. dz = cz - psz;
  103397. len = dx * dx + dy * dy + dz * dz;
  103398. var invLen;
  103399. if (len > 0 && len < rads * rads) {
  103400. len = OIMO.sqrt(len);
  103401. invLen = 1 / len;
  103402. dx *= invLen;
  103403. dy *= invLen;
  103404. dz *= invLen;
  103405. ///result.addContactInfo(psx+dx*rads,psy+dy*rads,psz+dz*rads,dx,dy,dz,len-rads,s,c,0,0,false);
  103406. manifold.addPoint(psx + dx * rads, psy + dy * rads, psz + dz * rads, dx, dy, dz, len - rads, this.flip);
  103407. }
  103408. };
  103409. /**
  103410. * Class for checking collisions between 2 tetras,
  103411. * a shape that is made with 4 vertices and 4 faces
  103412. * arranged in triangles. With this algorigthm, soft
  103413. * body physics are possible and easier to implement.
  103414. * @author xprogram
  103415. */
  103416. OIMO.TetraTetraCollisionDetector = function () {
  103417. OIMO.CollisionDetector.call(this);
  103418. };
  103419. OIMO.TetraTetraCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  103420. OIMO.TetraTetraCollisionDetector.prototype.constructor = OIMO.TetraTetraCollisionDetector;
  103421. OIMO.TetraTetraCollisionDetector.prototype.detectCollision = function (tet1, tet2, manifold) {
  103422. /*
  103423. * What we are doing:
  103424. * Each tetra is represented by four 3D triangles. The only
  103425. * quick way of finding if another tetra is within the other
  103426. * tetra is to see if a single vertex is within the triangles
  103427. * of the other tetra. So, for example, a tetra is represented
  103428. * by points B, C, D and E with triangles BCD, BCE, DCE and BDE.
  103429. * There is another tetra with a vertex A which was detected for
  103430. * collision by the broadphase. Now, if the point A is between ALL
  103431. * triangles of the other tetra (BCD, BCE, etc.) then the collision
  103432. * is valid and we can pass point A to the manifold. Since the only
  103433. * points on the tetra are the 4 vertices, collision detection is
  103434. * not so complex. However, it can be time-consuming because we
  103435. * need to split the 3D triangles into three 2D triangles each for
  103436. * collision detection.
  103437. */
  103438. var i, j, vec, fs1 = tet1.faces, vs1 = tet1.verts, fs2 = tet2.faces, vs2 = tet2.verts;
  103439. var j1, j2, j3, ts = 0; // Triangle vertices `j1`, `j2` and `j3`
  103440. // fs is undeclared
  103441. var fs = fs1;
  103442. for (i = 0; i < 4; i++) {
  103443. vec = vs1[i];
  103444. for (j = 0; j < 4; j++) {
  103445. j1 = vs2[fs[i].a];
  103446. j2 = vs2[fs[i].b];
  103447. j3 = vs2[fs[i].c];
  103448. if (
  103449. tricheck(pt(vec.x, vec.y), pt(j1.x, j1.y), pt(j2.x, j2.y), pt(j3.x, j3.y)) &&
  103450. tricheck(pt(vec.x, vec.z), pt(j1.x, j1.z), pt(j2.x, j2.z), pt(j3.x, j3.z)) &&
  103451. tricheck(pt(vec.z, vec.y), pt(j1.z, j1.y), pt(j2.z, j2.y), pt(j3.z, j3.y))
  103452. )
  103453. ts++;
  103454. if (ts === 4) // Only add point if it is inside all 4 triangles
  103455. manifold.addPoint(vec);
  103456. }
  103457. }
  103458. };
  103459. // Taken from: http://jsfiddle.net/PerroAZUL/zdaY8/1/
  103460. function tricheck(p, p0, p1, p2) {
  103461. var A = 0.5 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  103462. var sg = A < 0 ? -1 : 1;
  103463. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sg;
  103464. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sg;
  103465. return s > 0 && t > 0 && (s + t) < 2 * A * sg;
  103466. }
  103467. function pt(x, y) { return { x: x, y: y }; }
  103468. /**
  103469. * An axis-aligned bounding box.
  103470. * @author saharan
  103471. * @author lo-th
  103472. */
  103473. OIMO.AABB = function (minX, maxX, minY, maxY, minZ, maxZ) {
  103474. this.elements = new OIMO_ARRAY_TYPE(6);
  103475. var te = this.elements;
  103476. te[0] = minX || 0; te[1] = minY || 0; te[2] = minZ || 0;
  103477. te[3] = maxX || 0; te[4] = maxY || 0; te[5] = maxZ || 0;
  103478. };
  103479. OIMO.AABB.prototype = {
  103480. constructor: OIMO.AABB,
  103481. set: function (minX, maxX, minY, maxY, minZ, maxZ) {
  103482. var te = this.elements;
  103483. te[0] = minX; te[3] = maxX;
  103484. te[1] = minY; te[4] = maxY;
  103485. te[2] = minZ; te[5] = maxZ;
  103486. return this;
  103487. },
  103488. intersectTest: function (aabb) {
  103489. var te = this.elements;
  103490. var ue = aabb.elements;
  103491. 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];
  103492. },
  103493. intersectTestTwo: function (aabb) {
  103494. var te = this.elements;
  103495. var ue = aabb.elements;
  103496. 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];
  103497. },
  103498. clone: function () {
  103499. return new this.constructor().fromArray(this.elements);
  103500. },
  103501. copy: function (aabb, margin) {
  103502. var m = margin || 0;
  103503. var me = aabb.elements;
  103504. this.set(me[0] - m, me[3] + m, me[1] - m, me[4] + m, me[2] - m, me[5] + m);
  103505. return this;
  103506. },
  103507. fromArray: function (array) {
  103508. this.elements.set(array);
  103509. return this;
  103510. },
  103511. // Set this AABB to the combined AABB of aabb1 and aabb2.
  103512. combine: function (aabb1, aabb2) {
  103513. var a = aabb1.elements;
  103514. var b = aabb2.elements;
  103515. var te = this.elements;
  103516. te[0] = a[0] < b[0] ? a[0] : b[0];
  103517. te[1] = a[1] < b[1] ? a[1] : b[1];
  103518. te[2] = a[2] < b[2] ? a[2] : b[2];
  103519. te[3] = a[3] > b[3] ? a[3] : b[3];
  103520. te[4] = a[4] > b[4] ? a[4] : b[4];
  103521. te[5] = a[5] > b[5] ? a[5] : b[5];
  103522. return this;
  103523. },
  103524. // Get the surface area.
  103525. surfaceArea: function () {
  103526. var te = this.elements;
  103527. var a = te[3] - te[0];
  103528. var h = te[4] - te[1];
  103529. var d = te[5] - te[2];
  103530. return 2 * (a * (h + d) + h * d);
  103531. },
  103532. // Get whether the AABB intersects with the point or not.
  103533. intersectsWithPoint: function (x, y, z) {
  103534. var te = this.elements;
  103535. return x >= te[0] && x <= te[3] && y >= te[1] && y <= te[4] && z >= te[2] && z <= te[5];
  103536. },
  103537. /**
  103538. * Set the AABB from an array
  103539. * of vertices. From THREE.
  103540. * @author mrdoob
  103541. * @author xprogram
  103542. */
  103543. setFromPoints: function (arr) {
  103544. this.makeEmpty();
  103545. for (var i = 0; i < arr.length; i++) {
  103546. this.expandByPoint(arr[i]);
  103547. }
  103548. },
  103549. makeEmpty: function () {
  103550. this.set(-Infinity, -Infinity, -Infinity, Infinity, Infinity, Infinity);
  103551. },
  103552. expandByPoint: function (pt) {
  103553. var te = this.elements;
  103554. this.set(
  103555. OIMO.min(te[0], pt.x), OIMO.min(te[1], pt.y), OIMO.min(te[2], pt.z),
  103556. OIMO.max(te[3], pt.x), OIMO.max(te[4], pt.y), OIMO.max(te[5], pt.z)
  103557. );
  103558. }
  103559. };
  103560. /**
  103561. * A proxy is used for broad-phase collecting pairs that can be colliding.
  103562. */
  103563. OIMO.Proxy = function (shape) {
  103564. // The parent shape.
  103565. this.shape = shape;
  103566. // The axis-aligned bounding box.
  103567. this.aabb = shape.aabb;
  103568. };
  103569. OIMO.Proxy.prototype = {
  103570. constructor: OIMO.Proxy,
  103571. // Update the proxy.
  103572. update: function () {
  103573. OIMO.Error("Proxy", "Inheritance error.");
  103574. }
  103575. };
  103576. /**
  103577. * A basic implementation of proxies.
  103578. * @author saharan
  103579. */
  103580. OIMO.BasicProxy = function (shape) {
  103581. OIMO.Proxy.call(this, shape);
  103582. this.id = OIMO.proxyID++;
  103583. };
  103584. OIMO.BasicProxy.prototype = Object.create(OIMO.Proxy.prototype);
  103585. OIMO.BasicProxy.prototype.constructor = OIMO.BasicProxy;
  103586. OIMO.BasicProxy.prototype.update = function () {
  103587. };
  103588. /**
  103589. * The broad-phase is used for collecting all possible pairs for collision.
  103590. */
  103591. OIMO.BroadPhase = function () {
  103592. this.types = OIMO.BR_NULL;
  103593. this.numPairChecks = 0;
  103594. this.numPairs = 0;
  103595. this.pairs = [];
  103596. };
  103597. OIMO.BroadPhase.prototype = {
  103598. constructor: OIMO.BroadPhase,
  103599. /**
  103600. * Create a new proxy.
  103601. * @param shape
  103602. * @return
  103603. */
  103604. createProxy: function (shape) {
  103605. OIMO.Error("BroadPhase", "Inheritance error.");
  103606. },
  103607. /**
  103608. * Add the proxy into the broad-phase.
  103609. * @param proxy
  103610. */
  103611. addProxy: function (proxy) {
  103612. OIMO.Error("BroadPhase", "Inheritance error.");
  103613. },
  103614. /**
  103615. * Remove the proxy from the broad-phase.
  103616. * @param proxy
  103617. */
  103618. removeProxy: function (proxy) {
  103619. OIMO.Error("BroadPhase", "Inheritance error.");
  103620. },
  103621. /**
  103622. * Returns whether the pair is available or not.
  103623. * @param s1
  103624. * @param s2
  103625. * @return
  103626. */
  103627. isAvailablePair: function (s1, s2) {
  103628. var b1 = s1.parent;
  103629. var b2 = s2.parent;
  103630. if (b1 == b2 || // same parents
  103631. (!b1.isDynamic && !b2.isDynamic) || // static or kinematic object
  103632. (s1.belongsTo & s2.collidesWith) == 0 ||
  103633. (s2.belongsTo & s1.collidesWith) == 0 // collision filtering
  103634. ) { return false; }
  103635. var js;
  103636. if (b1.numJoints < b2.numJoints) js = b1.jointLink;
  103637. else js = b2.jointLink;
  103638. while (js !== null) {
  103639. var joint = js.joint;
  103640. if (!joint.allowCollision && ((joint.body1 == b1 && joint.body2 == b2) || (joint.body1 == b2 && joint.body2 == b1))) { return false; }
  103641. js = js.next;
  103642. }
  103643. return true;
  103644. },
  103645. // Detect overlapping pairs.
  103646. detectPairs: function () {
  103647. // clear old
  103648. this.pairs = [];
  103649. this.numPairs = 0;
  103650. this.numPairChecks = 0;
  103651. this.collectPairs();
  103652. },
  103653. collectPairs: function () {
  103654. OIMO.Error("BroadPhase", "Inheritance error.");
  103655. },
  103656. addPair: function (s1, s2) {
  103657. var pair = new OIMO.Pair(s1, s2);
  103658. this.pairs.push(pair);
  103659. this.numPairs++;
  103660. }
  103661. };
  103662. /**
  103663. * A broad-phase algorithm with brute-force search.
  103664. * This always checks for all possible pairs.
  103665. */
  103666. OIMO.BruteForceBroadPhase = function () {
  103667. OIMO.BroadPhase.call(this);
  103668. this.types = OIMO.BR_BRUTE_FORCE;;
  103669. //this.numProxies=0;
  103670. ///this.maxProxies = 256;
  103671. this.proxies = [];
  103672. //this.proxies.length = 256;
  103673. };
  103674. OIMO.BruteForceBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  103675. OIMO.BruteForceBroadPhase.prototype.constructor = OIMO.BruteForceBroadPhase;
  103676. OIMO.BruteForceBroadPhase.prototype.createProxy = function (shape) {
  103677. return new OIMO.BasicProxy(shape);
  103678. };
  103679. OIMO.BruteForceBroadPhase.prototype.addProxy = function (proxy) {
  103680. /*if(this.numProxies==this.maxProxies){
  103681. //this.maxProxies<<=1;
  103682. this.maxProxies*=2;
  103683. var newProxies=[];
  103684. newProxies.length = this.maxProxies;
  103685. var i = this.numProxies;
  103686. while(i--){
  103687. //for(var i=0, l=this.numProxies;i<l;i++){
  103688. newProxies[i]=this.proxies[i];
  103689. }
  103690. this.proxies=newProxies;
  103691. }*/
  103692. //this.proxies[this.numProxies++] = proxy;
  103693. this.proxies.push(proxy);
  103694. //this.numProxies++;
  103695. };
  103696. OIMO.BruteForceBroadPhase.prototype.removeProxy = function (proxy) {
  103697. var n = this.proxies.indexOf(proxy);
  103698. if (n > -1) {
  103699. this.proxies.splice(n, 1);
  103700. //this.numProxies--;
  103701. }
  103702. /*var i = this.numProxies;
  103703. while(i--){
  103704. //for(var i=0, l=this.numProxies;i<l;i++){
  103705. if(this.proxies[i] == proxy){
  103706. this.proxies[i] = this.proxies[--this.numProxies];
  103707. this.proxies[this.numProxies] = null;
  103708. return;
  103709. }
  103710. }*/
  103711. };
  103712. OIMO.BruteForceBroadPhase.prototype.collectPairs = function () {
  103713. var i = 0, j, p1, p2;
  103714. var px = this.proxies;
  103715. var l = px.length;//this.numProxies;
  103716. //var ar1 = [];
  103717. //var ar2 = [];
  103718. //for( i = px.length ; i-- ; ar1[ i ] = px[ i ] ){};
  103719. //for( i = px.length ; i-- ; ar2[ i ] = px[ i ] ){};
  103720. //var ar1 = JSON.parse(JSON.stringify(this.proxies))
  103721. //var ar2 = JSON.parse(JSON.stringify(this.proxies))
  103722. this.numPairChecks = l * (l - 1) >> 1;
  103723. //this.numPairChecks=this.numProxies*(this.numProxies-1)*0.5;
  103724. while (i < l) {
  103725. p1 = px[i++];
  103726. j = i + 1;
  103727. while (j < l) {
  103728. p2 = px[j++];
  103729. if (p1.aabb.intersectTest(p2.aabb) || !this.isAvailablePair(p1.shape, p2.shape)) continue;
  103730. this.addPair(p1.shape, p2.shape);
  103731. }
  103732. }
  103733. };
  103734. /**
  103735. * A pair of shapes that may collide.
  103736. * @author saharan
  103737. */
  103738. OIMO.Pair = function (s1, s2) {
  103739. // The first shape.
  103740. this.shape1 = s1 || null;
  103741. // The second shape.
  103742. this.shape2 = s2 || null;
  103743. };
  103744. /**
  103745. * A projection axis for sweep and prune broad-phase.
  103746. * @author saharan
  103747. */
  103748. OIMO.SAPAxis = function () {
  103749. this.numElements = 0;
  103750. this.bufferSize = 256;
  103751. this.elements = [];
  103752. this.elements.length = this.bufferSize;
  103753. this.stack = new OIMO_ARRAY_TYPE(64);
  103754. };
  103755. OIMO.SAPAxis.prototype = {
  103756. constructor: OIMO.SAPAxis,
  103757. addElements: function (min, max) {
  103758. if (this.numElements + 2 >= this.bufferSize) {
  103759. //this.bufferSize<<=1;
  103760. this.bufferSize *= 2;
  103761. var newElements = [];
  103762. var i = this.numElements;
  103763. while (i--) {
  103764. //for(var i=0, l=this.numElements; i<l; i++){
  103765. newElements[i] = this.elements[i];
  103766. }
  103767. }
  103768. this.elements[this.numElements++] = min;
  103769. this.elements[this.numElements++] = max;
  103770. },
  103771. removeElements: function (min, max) {
  103772. var minIndex = -1;
  103773. var maxIndex = -1;
  103774. for (var i = 0, l = this.numElements; i < l; i++) {
  103775. var e = this.elements[i];
  103776. if (e == min || e == max) {
  103777. if (minIndex == -1) {
  103778. minIndex = i;
  103779. } else {
  103780. maxIndex = i;
  103781. break;
  103782. }
  103783. }
  103784. }
  103785. for (i = minIndex + 1, l = maxIndex; i < l; i++) {
  103786. this.elements[i - 1] = this.elements[i];
  103787. }
  103788. for (i = maxIndex + 1, l = this.numElements; i < l; i++) {
  103789. this.elements[i - 2] = this.elements[i];
  103790. }
  103791. this.elements[--this.numElements] = null;
  103792. this.elements[--this.numElements] = null;
  103793. },
  103794. sort: function () {
  103795. var count = 0;
  103796. var threshold = 1;
  103797. while ((this.numElements >> threshold) != 0) threshold++;
  103798. threshold = threshold * this.numElements >> 2;
  103799. count = 0;
  103800. var giveup = false;
  103801. var elements = this.elements;
  103802. for (var i = 1, l = this.numElements; i < l; i++) { // try insertion sort
  103803. var tmp = elements[i];
  103804. var pivot = tmp.value;
  103805. var tmp2 = elements[i - 1];
  103806. if (tmp2.value > pivot) {
  103807. var j = i;
  103808. do {
  103809. elements[j] = tmp2;
  103810. if (--j == 0) break;
  103811. tmp2 = elements[j - 1];
  103812. } while (tmp2.value > pivot);
  103813. elements[j] = tmp;
  103814. count += i - j;
  103815. if (count > threshold) {
  103816. giveup = true; // stop and use quick sort
  103817. break;
  103818. }
  103819. }
  103820. }
  103821. if (!giveup) return;
  103822. count = 2; var stack = this.stack;
  103823. stack[0] = 0;
  103824. stack[1] = this.numElements - 1;
  103825. while (count > 0) {
  103826. var right = stack[--count];
  103827. var left = stack[--count];
  103828. var diff = right - left;
  103829. if (diff > 16) { // quick sort
  103830. //var mid=left+(diff>>1);
  103831. var mid = left + (OIMO.floor(diff * 0.5));
  103832. tmp = elements[mid];
  103833. elements[mid] = elements[right];
  103834. elements[right] = tmp;
  103835. pivot = tmp.value;
  103836. i = left - 1;
  103837. j = right;
  103838. while (true) {
  103839. var ei;
  103840. var ej;
  103841. do { ei = elements[++i]; } while (ei.value < pivot);
  103842. do { ej = elements[--j]; } while (pivot < ej.value && j != left);
  103843. if (i >= j) break;
  103844. elements[i] = ej;
  103845. elements[j] = ei;
  103846. }
  103847. elements[right] = elements[i];
  103848. elements[i] = tmp;
  103849. if (i - left > right - i) {
  103850. stack[count++] = left;
  103851. stack[count++] = i - 1;
  103852. stack[count++] = i + 1;
  103853. stack[count++] = right;
  103854. } else {
  103855. stack[count++] = i + 1;
  103856. stack[count++] = right;
  103857. stack[count++] = left;
  103858. stack[count++] = i - 1;
  103859. }
  103860. } else {
  103861. for (i = left + 1; i <= right; i++) {
  103862. tmp = elements[i];
  103863. pivot = tmp.value;
  103864. tmp2 = elements[i - 1];
  103865. if (tmp2.value > pivot) {
  103866. j = i;
  103867. do {
  103868. elements[j] = tmp2;
  103869. if (--j == 0) break;
  103870. tmp2 = elements[j - 1];
  103871. } while (tmp2.value > pivot);
  103872. elements[j] = tmp;
  103873. }
  103874. }
  103875. }
  103876. }
  103877. },
  103878. calculateTestCount: function () {
  103879. var num = 1;
  103880. var sum = 0;
  103881. for (var i = 1, l = this.numElements; i < l; i++) {
  103882. if (this.elements[i].max) {
  103883. num--;
  103884. } else {
  103885. sum += num;
  103886. num++;
  103887. }
  103888. }
  103889. return sum;
  103890. }
  103891. }
  103892. /**
  103893. * A broad-phase collision detection algorithm using sweep and prune.
  103894. * @author saharan
  103895. * @author lo-th
  103896. */
  103897. OIMO.SAPBroadPhase = function () {
  103898. OIMO.BroadPhase.call(this);
  103899. this.types = OIMO.BR_SWEEP_AND_PRUNE;
  103900. this.numElementsD = 0;
  103901. this.numElementsS = 0;
  103902. // dynamic proxies
  103903. this.axesD = [
  103904. new OIMO.SAPAxis(),
  103905. new OIMO.SAPAxis(),
  103906. new OIMO.SAPAxis()
  103907. ];
  103908. // static or sleeping proxies
  103909. this.axesS = [
  103910. new OIMO.SAPAxis(),
  103911. new OIMO.SAPAxis(),
  103912. new OIMO.SAPAxis()
  103913. ];
  103914. this.index1 = 0;
  103915. this.index2 = 1;
  103916. };
  103917. OIMO.SAPBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  103918. OIMO.SAPBroadPhase.prototype.constructor = OIMO.SAPBroadPhase;
  103919. OIMO.SAPBroadPhase.prototype.createProxy = function (shape) {
  103920. return new OIMO.SAPProxy(this, shape);
  103921. };
  103922. OIMO.SAPBroadPhase.prototype.addProxy = function (proxy) {
  103923. var p = proxy;
  103924. if (p.isDynamic()) {
  103925. this.axesD[0].addElements(p.min[0], p.max[0]);
  103926. this.axesD[1].addElements(p.min[1], p.max[1]);
  103927. this.axesD[2].addElements(p.min[2], p.max[2]);
  103928. p.belongsTo = 1;
  103929. this.numElementsD += 2;
  103930. } else {
  103931. this.axesS[0].addElements(p.min[0], p.max[0]);
  103932. this.axesS[1].addElements(p.min[1], p.max[1]);
  103933. this.axesS[2].addElements(p.min[2], p.max[2]);
  103934. p.belongsTo = 2;
  103935. this.numElementsS += 2;
  103936. }
  103937. };
  103938. OIMO.SAPBroadPhase.prototype.removeProxy = function (proxy) {
  103939. var p = proxy;
  103940. if (p.belongsTo == 0) return;
  103941. /*else if ( p.belongsTo == 1 ) {
  103942. this.axesD[0].removeElements( p.min[0], p.max[0] );
  103943. this.axesD[1].removeElements( p.min[1], p.max[1] );
  103944. this.axesD[2].removeElements( p.min[2], p.max[2] );
  103945. this.numElementsD -= 2;
  103946. } else if ( p.belongsTo == 2 ) {
  103947. this.axesS[0].removeElements( p.min[0], p.max[0] );
  103948. this.axesS[1].removeElements( p.min[1], p.max[1] );
  103949. this.axesS[2].removeElements( p.min[2], p.max[2] );
  103950. this.numElementsS -= 2;
  103951. }*/
  103952. switch (p.belongsTo) {
  103953. case 1:
  103954. this.axesD[0].removeElements(p.min[0], p.max[0]);
  103955. this.axesD[1].removeElements(p.min[1], p.max[1]);
  103956. this.axesD[2].removeElements(p.min[2], p.max[2]);
  103957. this.numElementsD -= 2;
  103958. break;
  103959. case 2:
  103960. this.axesS[0].removeElements(p.min[0], p.max[0]);
  103961. this.axesS[1].removeElements(p.min[1], p.max[1]);
  103962. this.axesS[2].removeElements(p.min[2], p.max[2]);
  103963. this.numElementsS -= 2;
  103964. break;
  103965. }
  103966. p.belongsTo = 0;
  103967. };
  103968. OIMO.SAPBroadPhase.prototype.collectPairs = function () {
  103969. if (this.numElementsD == 0) return;
  103970. var axis1 = this.axesD[this.index1];
  103971. var axis2 = this.axesD[this.index2];
  103972. axis1.sort();
  103973. axis2.sort();
  103974. var count1 = axis1.calculateTestCount();
  103975. var count2 = axis2.calculateTestCount();
  103976. var elementsD;
  103977. var elementsS;
  103978. if (count1 <= count2) {// select the best axis
  103979. axis2 = this.axesS[this.index1];
  103980. axis2.sort();
  103981. elementsD = axis1.elements;
  103982. elementsS = axis2.elements;
  103983. } else {
  103984. axis1 = this.axesS[this.index2];
  103985. axis1.sort();
  103986. elementsD = axis2.elements;
  103987. elementsS = axis1.elements;
  103988. this.index1 ^= this.index2;
  103989. this.index2 ^= this.index1;
  103990. this.index1 ^= this.index2;
  103991. }
  103992. var activeD;
  103993. var activeS;
  103994. var p = 0;
  103995. var q = 0;
  103996. while (p < this.numElementsD) {
  103997. var e1;
  103998. var dyn;
  103999. if (q == this.numElementsS) {
  104000. e1 = elementsD[p];
  104001. dyn = true;
  104002. p++;
  104003. } else {
  104004. var d = elementsD[p];
  104005. var s = elementsS[q];
  104006. if (d.value < s.value) {
  104007. e1 = d;
  104008. dyn = true;
  104009. p++;
  104010. } else {
  104011. e1 = s;
  104012. dyn = false;
  104013. q++;
  104014. }
  104015. }
  104016. if (!e1.max) {
  104017. var s1 = e1.proxy.shape;
  104018. var min1 = e1.min1.value;
  104019. var max1 = e1.max1.value;
  104020. var min2 = e1.min2.value;
  104021. var max2 = e1.max2.value;
  104022. for (var e2 = activeD; e2 != null; e2 = e2.pair) {// test for dynamic
  104023. var s2 = e2.proxy.shape;
  104024. this.numPairChecks++;
  104025. if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
  104026. this.addPair(s1, s2);
  104027. }
  104028. if (dyn) {
  104029. for (e2 = activeS; e2 != null; e2 = e2.pair) {// test for static
  104030. s2 = e2.proxy.shape;
  104031. this.numPairChecks++;
  104032. if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
  104033. this.addPair(s1, s2);
  104034. }
  104035. e1.pair = activeD;
  104036. activeD = e1;
  104037. } else {
  104038. e1.pair = activeS;
  104039. activeS = e1;
  104040. }
  104041. } else {
  104042. var min = e1.pair;
  104043. if (dyn) {
  104044. if (min == activeD) {
  104045. activeD = activeD.pair;
  104046. continue;
  104047. } else {
  104048. e1 = activeD;
  104049. }
  104050. } else {
  104051. if (min == activeS) {
  104052. activeS = activeS.pair;
  104053. continue;
  104054. } else {
  104055. e1 = activeS;
  104056. }
  104057. }
  104058. do {
  104059. e2 = e1.pair;
  104060. if (e2 == min) {
  104061. e1.pair = e2.pair;
  104062. break;
  104063. }
  104064. e1 = e2;
  104065. } while (e1 != null);
  104066. }
  104067. }
  104068. this.index2 = (this.index1 | this.index2) ^ 3;
  104069. };
  104070. /**
  104071. * An element of proxies.
  104072. * @author saharan
  104073. */
  104074. OIMO.SAPElement = function (proxy, max) {
  104075. // The parent proxy
  104076. this.proxy = proxy;
  104077. // The pair element.
  104078. this.pair = null;
  104079. // The minimum element on other axis.
  104080. this.min1 = null;
  104081. // The maximum element on other axis.
  104082. this.max1 = null;
  104083. // The minimum element on other axis.
  104084. this.min2 = null;
  104085. // The maximum element on other axis.
  104086. this.max2 = null;
  104087. // Whether the element has maximum value or not.
  104088. this.max = max;
  104089. // The value of the element.
  104090. this.value = 0;
  104091. };
  104092. /**
  104093. * A proxy for sweep and prune broad-phase.
  104094. * @author saharan
  104095. * @author lo-th
  104096. */
  104097. OIMO.SAPProxy = function (sap, shape) {
  104098. OIMO.Proxy.call(this, shape);
  104099. // Type of the axis to which the proxy belongs to. [0:none, 1:dynamic, 2:static]
  104100. this.belongsTo = 0;
  104101. // The maximum elements on each axis.
  104102. this.max = [];
  104103. // The minimum elements on each axis.
  104104. this.min = [];
  104105. this.sap = sap;
  104106. this.min[0] = new OIMO.SAPElement(this, false);
  104107. this.max[0] = new OIMO.SAPElement(this, true);
  104108. this.min[1] = new OIMO.SAPElement(this, false);
  104109. this.max[1] = new OIMO.SAPElement(this, true);
  104110. this.min[2] = new OIMO.SAPElement(this, false);
  104111. this.max[2] = new OIMO.SAPElement(this, true);
  104112. this.max[0].pair = this.min[0];
  104113. this.max[1].pair = this.min[1];
  104114. this.max[2].pair = this.min[2];
  104115. this.min[0].min1 = this.min[1];
  104116. this.min[0].max1 = this.max[1];
  104117. this.min[0].min2 = this.min[2];
  104118. this.min[0].max2 = this.max[2];
  104119. this.min[1].min1 = this.min[0];
  104120. this.min[1].max1 = this.max[0];
  104121. this.min[1].min2 = this.min[2];
  104122. this.min[1].max2 = this.max[2];
  104123. this.min[2].min1 = this.min[0];
  104124. this.min[2].max1 = this.max[0];
  104125. this.min[2].min2 = this.min[1];
  104126. this.min[2].max2 = this.max[1];
  104127. };
  104128. OIMO.SAPProxy.prototype = Object.create(OIMO.Proxy.prototype);
  104129. OIMO.SAPProxy.prototype.constructor = OIMO.SAPProxy;
  104130. // Returns whether the proxy is dynamic or not.
  104131. OIMO.SAPProxy.prototype.isDynamic = function () {
  104132. var body = this.shape.parent;
  104133. return body.isDynamic && !body.sleeping;
  104134. };
  104135. OIMO.SAPProxy.prototype.update = function () {
  104136. var te = this.aabb.elements;
  104137. this.min[0].value = te[0];
  104138. this.min[1].value = te[1];
  104139. this.min[2].value = te[2];
  104140. this.max[0].value = te[3];
  104141. this.max[1].value = te[4];
  104142. this.max[2].value = te[5];
  104143. if (this.belongsTo == 1 && !this.isDynamic() || this.belongsTo == 2 && this.isDynamic()) {
  104144. this.sap.removeProxy(this);
  104145. this.sap.addProxy(this);
  104146. }
  104147. };
  104148. /**
  104149. * A dynamic bounding volume tree for the broad-phase algorithm.
  104150. * @author saharan
  104151. * @author lo-th
  104152. */
  104153. OIMO.DBVT = function () {
  104154. // The root of the tree.
  104155. this.root = null;
  104156. this.freeNodes = [];
  104157. this.freeNodes.length = 16384;
  104158. this.numFreeNodes = 0;
  104159. this.aabb = new OIMO.AABB();
  104160. };
  104161. OIMO.DBVT.prototype = {
  104162. constructor: OIMO.DBVT,
  104163. /**
  104164. * Move a leaf.
  104165. * @param leaf
  104166. */
  104167. moveLeaf: function (leaf) {
  104168. this.deleteLeaf(leaf);
  104169. this.insertLeaf(leaf);
  104170. },
  104171. /**
  104172. * Insert a leaf to the tree.
  104173. * @param node
  104174. */
  104175. insertLeaf: function (leaf) {
  104176. if (this.root == null) {
  104177. this.root = leaf;
  104178. return;
  104179. }
  104180. var lb = leaf.aabb;
  104181. var sibling = this.root;
  104182. var oldArea;
  104183. var newArea;
  104184. while (sibling.proxy == null) { // descend the node to search the best pair
  104185. var c1 = sibling.child1;
  104186. var c2 = sibling.child2;
  104187. var b = sibling.aabb;
  104188. var c1b = c1.aabb;
  104189. var c2b = c2.aabb;
  104190. oldArea = b.surfaceArea();
  104191. this.aabb.combine(lb, b);
  104192. newArea = this.aabb.surfaceArea();
  104193. var creatingCost = newArea * 2;
  104194. var incrementalCost = (newArea - oldArea) * 2; // cost of creating a new pair with the node
  104195. var discendingCost1 = incrementalCost;
  104196. this.aabb.combine(lb, c1b);
  104197. if (c1.proxy != null) {
  104198. // leaf cost = area(combined aabb)
  104199. discendingCost1 += this.aabb.surfaceArea();
  104200. } else {
  104201. // node cost = area(combined aabb) - area(old aabb)
  104202. discendingCost1 += this.aabb.surfaceArea() - c1b.surfaceArea();
  104203. }
  104204. var discendingCost2 = incrementalCost;
  104205. this.aabb.combine(lb, c2b);
  104206. if (c2.proxy != null) {
  104207. // leaf cost = area(combined aabb)
  104208. discendingCost2 += this.aabb.surfaceArea();
  104209. } else {
  104210. // node cost = area(combined aabb) - area(old aabb)
  104211. discendingCost2 += this.aabb.surfaceArea() - c2b.surfaceArea();
  104212. }
  104213. if (discendingCost1 < discendingCost2) {
  104214. if (creatingCost < discendingCost1) {
  104215. break;// stop descending
  104216. } else {
  104217. sibling = c1;// descend into first child
  104218. }
  104219. } else {
  104220. if (creatingCost < discendingCost2) {
  104221. break;// stop descending
  104222. } else {
  104223. sibling = c2;// descend into second child
  104224. }
  104225. }
  104226. }
  104227. var oldParent = sibling.parent;
  104228. var newParent;
  104229. if (this.numFreeNodes > 0) {
  104230. newParent = this.freeNodes[--this.numFreeNodes];
  104231. } else {
  104232. newParent = new OIMO.DBVTNode();
  104233. }
  104234. newParent.parent = oldParent;
  104235. newParent.child1 = leaf;
  104236. newParent.child2 = sibling;
  104237. newParent.aabb.combine(leaf.aabb, sibling.aabb);
  104238. newParent.height = sibling.height + 1;
  104239. sibling.parent = newParent;
  104240. leaf.parent = newParent;
  104241. if (sibling == this.root) {
  104242. // replace root
  104243. this.root = newParent;
  104244. } else {
  104245. // replace child
  104246. if (oldParent.child1 == sibling) {
  104247. oldParent.child1 = newParent;
  104248. } else {
  104249. oldParent.child2 = newParent;
  104250. }
  104251. }
  104252. // update whole tree
  104253. do {
  104254. newParent = this.balance(newParent);
  104255. this.fix(newParent);
  104256. newParent = newParent.parent;
  104257. } while (newParent != null);
  104258. },
  104259. getBalance: function (node) {
  104260. if (node.proxy != null) return 0;
  104261. return node.child1.height - node.child2.height;
  104262. },
  104263. /*print:function(node,indent,text){
  104264. var hasChild=node.proxy==null;
  104265. if(hasChild)text=this.print(node.child1,indent+1,text);
  104266. for(var i=indent*2;i>=0;i--){
  104267. text+=" ";
  104268. }
  104269. text+=(hasChild?this.getBalance(node):"["+node.proxy.aabb.minX+"]")+"\n";
  104270. if(hasChild)text=this.print(node.child2,indent+1,text);
  104271. return text;
  104272. },*/
  104273. /**
  104274. * Delete a leaf from the tree.
  104275. * @param node
  104276. */
  104277. deleteLeaf: function (leaf) {
  104278. if (leaf == this.root) {
  104279. this.root = null;
  104280. return;
  104281. }
  104282. var parent = leaf.parent;
  104283. var sibling;
  104284. if (parent.child1 == leaf) {
  104285. sibling = parent.child2;
  104286. } else {
  104287. sibling = parent.child1;
  104288. }
  104289. if (parent == this.root) {
  104290. this.root = sibling;
  104291. sibling.parent = null;
  104292. return;
  104293. }
  104294. var grandParent = parent.parent;
  104295. sibling.parent = grandParent;
  104296. if (grandParent.child1 == parent) {
  104297. grandParent.child1 = sibling;
  104298. } else {
  104299. grandParent.child2 = sibling;
  104300. }
  104301. if (this.numFreeNodes < 16384) {
  104302. this.freeNodes[this.numFreeNodes++] = parent;
  104303. }
  104304. do {
  104305. grandParent = this.balance(grandParent);
  104306. this.fix(grandParent);
  104307. grandParent = grandParent.parent;
  104308. } while (grandParent != null);
  104309. },
  104310. balance: function (node) {
  104311. var nh = node.height;
  104312. if (nh < 2) {
  104313. return node;
  104314. }
  104315. var p = node.parent;
  104316. var l = node.child1;
  104317. var r = node.child2;
  104318. var lh = l.height;
  104319. var rh = r.height;
  104320. var balance = lh - rh;
  104321. var t;// for bit operation
  104322. // [ N ]
  104323. // / \
  104324. // [ L ] [ R ]
  104325. // / \ / \
  104326. // [L-L] [L-R] [R-L] [R-R]
  104327. // Is the tree balanced?
  104328. if (balance > 1) {
  104329. var ll = l.child1;
  104330. var lr = l.child2;
  104331. var llh = ll.height;
  104332. var lrh = lr.height;
  104333. // Is L-L higher than L-R?
  104334. if (llh > lrh) {
  104335. // set N to L-R
  104336. l.child2 = node;
  104337. node.parent = l;
  104338. // [ L ]
  104339. // / \
  104340. // [L-L] [ N ]
  104341. // / \ / \
  104342. // [...] [...] [ L ] [ R ]
  104343. // set L-R
  104344. node.child1 = lr;
  104345. lr.parent = node;
  104346. // [ L ]
  104347. // / \
  104348. // [L-L] [ N ]
  104349. // / \ / \
  104350. // [...] [...] [L-R] [ R ]
  104351. // fix bounds and heights
  104352. node.aabb.combine(lr.aabb, r.aabb);
  104353. t = lrh - rh;
  104354. node.height = lrh - (t & t >> 31) + 1;
  104355. l.aabb.combine(ll.aabb, node.aabb);
  104356. t = llh - nh;
  104357. l.height = llh - (t & t >> 31) + 1;
  104358. } else {
  104359. // set N to L-L
  104360. l.child1 = node;
  104361. node.parent = l;
  104362. // [ L ]
  104363. // / \
  104364. // [ N ] [L-R]
  104365. // / \ / \
  104366. // [ L ] [ R ] [...] [...]
  104367. // set L-L
  104368. node.child1 = ll;
  104369. ll.parent = node;
  104370. // [ L ]
  104371. // / \
  104372. // [ N ] [L-R]
  104373. // / \ / \
  104374. // [L-L] [ R ] [...] [...]
  104375. // fix bounds and heights
  104376. node.aabb.combine(ll.aabb, r.aabb);
  104377. t = llh - rh;
  104378. node.height = llh - (t & t >> 31) + 1;
  104379. l.aabb.combine(node.aabb, lr.aabb);
  104380. t = nh - lrh;
  104381. l.height = nh - (t & t >> 31) + 1;
  104382. }
  104383. // set new parent of L
  104384. if (p != null) {
  104385. if (p.child1 == node) {
  104386. p.child1 = l;
  104387. } else {
  104388. p.child2 = l;
  104389. }
  104390. } else {
  104391. this.root = l;
  104392. }
  104393. l.parent = p;
  104394. return l;
  104395. } else if (balance < -1) {
  104396. var rl = r.child1;
  104397. var rr = r.child2;
  104398. var rlh = rl.height;
  104399. var rrh = rr.height;
  104400. // Is R-L higher than R-R?
  104401. if (rlh > rrh) {
  104402. // set N to R-R
  104403. r.child2 = node;
  104404. node.parent = r;
  104405. // [ R ]
  104406. // / \
  104407. // [R-L] [ N ]
  104408. // / \ / \
  104409. // [...] [...] [ L ] [ R ]
  104410. // set R-R
  104411. node.child2 = rr;
  104412. rr.parent = node;
  104413. // [ R ]
  104414. // / \
  104415. // [R-L] [ N ]
  104416. // / \ / \
  104417. // [...] [...] [ L ] [R-R]
  104418. // fix bounds and heights
  104419. node.aabb.combine(l.aabb, rr.aabb);
  104420. t = lh - rrh;
  104421. node.height = lh - (t & t >> 31) + 1;
  104422. r.aabb.combine(rl.aabb, node.aabb);
  104423. t = rlh - nh;
  104424. r.height = rlh - (t & t >> 31) + 1;
  104425. } else {
  104426. // set N to R-L
  104427. r.child1 = node;
  104428. node.parent = r;
  104429. // [ R ]
  104430. // / \
  104431. // [ N ] [R-R]
  104432. // / \ / \
  104433. // [ L ] [ R ] [...] [...]
  104434. // set R-L
  104435. node.child2 = rl;
  104436. rl.parent = node;
  104437. // [ R ]
  104438. // / \
  104439. // [ N ] [R-R]
  104440. // / \ / \
  104441. // [ L ] [R-L] [...] [...]
  104442. // fix bounds and heights
  104443. node.aabb.combine(l.aabb, rl.aabb);
  104444. t = lh - rlh;
  104445. node.height = lh - (t & t >> 31) + 1;
  104446. r.aabb.combine(node.aabb, rr.aabb);
  104447. t = nh - rrh;
  104448. r.height = nh - (t & t >> 31) + 1;
  104449. }
  104450. // set new parent of R
  104451. if (p != null) {
  104452. if (p.child1 == node) {
  104453. p.child1 = r;
  104454. } else {
  104455. p.child2 = r;
  104456. }
  104457. } else {
  104458. this.root = r;
  104459. }
  104460. r.parent = p;
  104461. return r;
  104462. }
  104463. return node;
  104464. },
  104465. fix: function (node) {
  104466. var c1 = node.child1;
  104467. var c2 = node.child2;
  104468. node.aabb.combine(c1.aabb, c2.aabb);
  104469. //var h1 = c1.height;
  104470. //var h2 = c2.height;
  104471. node.height = c1.height < c2.height ? c2.height + 1 : c1.height + 1;
  104472. /*if( h1 < h2 ) {
  104473. node.height = h2+1;
  104474. }else{
  104475. node.height = h1+1;
  104476. }*/
  104477. }
  104478. }
  104479. /**
  104480. * A broad-phase algorithm using dynamic bounding volume tree.
  104481. * @author saharan
  104482. * @author lo-th
  104483. */
  104484. OIMO.DBVTBroadPhase = function () {
  104485. OIMO.BroadPhase.call(this);
  104486. this.types = OIMO.BR_BOUNDING_VOLUME_TREE;
  104487. this.tree = new OIMO.DBVT();
  104488. this.stack = [];
  104489. this.leaves = [];
  104490. this.numLeaves = 0;
  104491. };
  104492. OIMO.DBVTBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  104493. OIMO.DBVTBroadPhase.prototype.constructor = OIMO.DBVTBroadPhase;
  104494. OIMO.DBVTBroadPhase.prototype.createProxy = function (shape) {
  104495. return new OIMO.DBVTProxy(shape);
  104496. };
  104497. OIMO.DBVTBroadPhase.prototype.addProxy = function (proxy) {
  104498. this.tree.insertLeaf(proxy.leaf);
  104499. this.leaves.push(proxy.leaf);
  104500. this.numLeaves++;
  104501. };
  104502. OIMO.DBVTBroadPhase.prototype.removeProxy = function (proxy) {
  104503. this.tree.deleteLeaf(proxy.leaf);
  104504. var n = this.leaves.indexOf(proxy.leaf);
  104505. if (n > -1) {
  104506. this.leaves.splice(n, 1);
  104507. this.numLeaves--;
  104508. }
  104509. };
  104510. OIMO.DBVTBroadPhase.prototype.collectPairs = function () {
  104511. if (this.numLeaves < 2) return;
  104512. var leaf, margin = 0.1, i = this.numLeaves;
  104513. while (i--) {
  104514. leaf = this.leaves[i];
  104515. if (leaf.proxy.aabb.intersectTestTwo(leaf.aabb)) {
  104516. leaf.aabb.copy(leaf.proxy.aabb, margin);
  104517. this.tree.deleteLeaf(leaf);
  104518. this.tree.insertLeaf(leaf);
  104519. this.collide(leaf, this.tree.root);
  104520. }
  104521. }
  104522. };
  104523. OIMO.DBVTBroadPhase.prototype.collide = function (node1, node2) {
  104524. var stackCount = 2;
  104525. var s1, s2, n1, n2, l1, l2;
  104526. this.stack[0] = node1;
  104527. this.stack[1] = node2;
  104528. while (stackCount > 0) {
  104529. n1 = this.stack[--stackCount];
  104530. n2 = this.stack[--stackCount];
  104531. l1 = n1.proxy != null;
  104532. l2 = n2.proxy != null;
  104533. this.numPairChecks++;
  104534. if (l1 && l2) {
  104535. s1 = n1.proxy.shape;
  104536. s2 = n2.proxy.shape;
  104537. if (s1 == s2 || s1.aabb.intersectTest(s2.aabb) || !this.isAvailablePair(s1, s2)) continue;
  104538. this.addPair(s1, s2);
  104539. } else {
  104540. if (n1.aabb.intersectTest(n2.aabb)) continue;
  104541. /*if(stackCount+4>=this.maxStack){// expand the stack
  104542. //this.maxStack<<=1;
  104543. this.maxStack*=2;
  104544. var newStack = [];// vector
  104545. newStack.length = this.maxStack;
  104546. for(var i=0;i<stackCount;i++){
  104547. newStack[i] = this.stack[i];
  104548. }
  104549. this.stack = newStack;
  104550. }*/
  104551. if (l2 || !l1 && (n1.aabb.surfaceArea() > n2.aabb.surfaceArea())) {
  104552. this.stack[stackCount++] = n1.child1;
  104553. this.stack[stackCount++] = n2;
  104554. this.stack[stackCount++] = n1.child2;
  104555. this.stack[stackCount++] = n2;
  104556. } else {
  104557. this.stack[stackCount++] = n1;
  104558. this.stack[stackCount++] = n2.child1;
  104559. this.stack[stackCount++] = n1;
  104560. this.stack[stackCount++] = n2.child2;
  104561. }
  104562. }
  104563. }
  104564. };
  104565. /**
  104566. * A node of the dynamic bounding volume tree.
  104567. * @author saharan
  104568. */
  104569. OIMO.DBVTNode = function () {
  104570. // The first child node of this node.
  104571. this.child1 = null;
  104572. // The second child node of this node.
  104573. this.child2 = null;
  104574. // The parent node of this tree.
  104575. this.parent = null;
  104576. // The proxy of this node. This has no value if this node is not leaf.
  104577. this.proxy = null;
  104578. // The maximum distance from leaf nodes.
  104579. this.height = 0;
  104580. // The AABB of this node.
  104581. this.aabb = new OIMO.AABB();
  104582. };
  104583. /**
  104584. * A proxy for dynamic bounding volume tree broad-phase.
  104585. * @author saharan
  104586. */
  104587. OIMO.DBVTProxy = function (shape) {
  104588. OIMO.Proxy.call(this, shape);
  104589. // The leaf of the proxy.
  104590. this.leaf = new OIMO.DBVTNode();
  104591. this.leaf.proxy = this;
  104592. };
  104593. OIMO.DBVTProxy.prototype = Object.create(OIMO.Proxy.prototype);
  104594. OIMO.DBVTProxy.prototype.constructor = OIMO.DBVTProxy;
  104595. OIMO.DBVTProxy.prototype.update = function () {
  104596. };
  104597. OIMO.World.prototype.add = function (obj) {
  104598. obj = obj || {};
  104599. var type = obj.type || "box";
  104600. if (typeof type === 'string') type = [type];// single shape
  104601. if (type[0].substring(0, 5) == 'joint') { // is joint
  104602. if (type[0] === 'joint') type[0] = 'jointHinge';
  104603. var axe1 = obj.axe1 || [1, 0, 0];
  104604. var axe2 = obj.axe2 || [1, 0, 0];
  104605. var pos1 = obj.pos1 || [0, 0, 0];
  104606. var pos2 = obj.pos2 || [0, 0, 0];
  104607. pos1 = pos1.map(function (x) { return x * OIMO.INV_SCALE; });
  104608. pos2 = pos2.map(function (x) { return x * OIMO.INV_SCALE; });
  104609. var min, max;
  104610. if (type[0] === "jointDistance") {
  104611. min = obj.min || 0;
  104612. max = obj.max || 10;
  104613. min = min * OIMO.INV_SCALE;
  104614. max = max * OIMO.INV_SCALE;
  104615. } else {
  104616. min = obj.min || 57.29578;
  104617. max = obj.max || 0;
  104618. min = min * OIMO.degtorad;
  104619. max = max * OIMO.degtorad;
  104620. }
  104621. var limit = obj.limit || null;
  104622. var spring = obj.spring || null;
  104623. var motor = obj.motor || null;
  104624. // joint setting
  104625. var jc = new OIMO.JointConfig();
  104626. jc.allowCollision = obj.collision || false;;
  104627. jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
  104628. jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
  104629. jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
  104630. jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
  104631. if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = this.getByName(obj.body1);
  104632. if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = this.getByName(obj.body2);
  104633. jc.body1 = obj.body1;
  104634. jc.body2 = obj.body2;
  104635. var joint;
  104636. switch (type[0]) {
  104637. case "jointDistance": joint = new OIMO.DistanceJoint(jc, min, max);
  104638. if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);
  104639. if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
  104640. break;
  104641. case "jointHinge": joint = new OIMO.HingeJoint(jc, min, max);
  104642. if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
  104643. if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
  104644. break;
  104645. case "jointPrisme": joint = new OIMO.PrismaticJoint(jc, min, max); break;
  104646. case "jointSlide": joint = new OIMO.SliderJoint(jc, min, max); break;
  104647. case "jointBall": joint = new OIMO.BallAndSocketJoint(jc); break;
  104648. case "jointWheel": joint = new OIMO.WheelJoint(jc);
  104649. if (limit !== null) joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
  104650. if (spring !== null) joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
  104651. if (motor !== null) joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
  104652. break;
  104653. }
  104654. joint.name = obj.name || '';
  104655. // finaly add to physics world
  104656. this.addJoint(joint);
  104657. return joint;
  104658. } else { // is body
  104659. // I'm dynamique or not
  104660. var move = obj.move || false;
  104661. // I can sleep or not
  104662. var noSleep = obj.noSleep || false;
  104663. // My start position
  104664. var p = obj.pos || [0, 0, 0];
  104665. p = p.map(function (x) { return x * OIMO.INV_SCALE; });
  104666. // My size
  104667. var s = obj.size || [1, 1, 1];
  104668. s = s.map(function (x) { return x * OIMO.INV_SCALE; });
  104669. // My rotation in degre
  104670. var rot = obj.rot || [0, 0, 0];
  104671. rot = rot.map(function (x) { return x * OIMO.degtorad; });
  104672. var r = [];
  104673. for (var i = 0; i < rot.length / 3; i++) {
  104674. var tmp = OIMO.EulerToAxis(rot[i + 0], rot[i + 1], rot[i + 2]);
  104675. r.push(tmp[0]); r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
  104676. }
  104677. // My physics setting
  104678. var sc = new OIMO.ShapeConfig();
  104679. if (obj.sc !== undefined) sc = obj.sc;
  104680. if (obj.config) {
  104681. // The density of the shape.
  104682. sc.density = obj.config[0] === undefined ? 1 : obj.config[0];
  104683. // The coefficient of friction of the shape.
  104684. sc.friction = obj.config[1] === undefined ? 0.4 : obj.config[1];
  104685. // The coefficient of restitution of the shape.
  104686. sc.restitution = obj.config[2] === undefined ? 0.2 : obj.config[2];
  104687. // The bits of the collision groups to which the shape belongs.
  104688. sc.belongsTo = obj.config[3] || 1;
  104689. //sc.belongsTo = obj.config[3] === undefined ? 1 : obj.config[3];
  104690. // The bits of the collision groups with which the shape collides.
  104691. sc.collidesWith = obj.config[4] || 0xffffffff;
  104692. //sc.collidesWith = obj.config[4] === undefined ? 0xffffffff : obj.config[4];
  104693. }
  104694. // direct physics setting
  104695. if (obj.density !== undefined) sc.density = obj.density;
  104696. if (obj.friction !== undefined) sc.friction = obj.friction;
  104697. if (obj.restitution !== undefined) sc.restitution = obj.restitution;
  104698. if (obj.belongsTo !== undefined) sc.belongsTo = obj.belongsTo;
  104699. if (obj.collidesWith !== undefined) sc.collidesWith = obj.collidesWith;
  104700. if (obj.massPos) {
  104701. obj.massPos = obj.massPos.map(function (x) { return x * OIMO.INV_SCALE; });
  104702. sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
  104703. }
  104704. if (obj.massRot) {
  104705. obj.massRot = obj.massRot.map(function (x) { return x * OIMO.degtorad; });
  104706. sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
  104707. }
  104708. // My rigidbody
  104709. var body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
  104710. // My shapes
  104711. var shapes = [];
  104712. //if( typeof type === 'string' ) type = [type];// single shape
  104713. var n, n2;
  104714. for (var i = 0; i < type.length; i++) {
  104715. n = i * 3;
  104716. n2 = i * 4;
  104717. switch (type[i]) {
  104718. case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n]); break;
  104719. case "cylinder": shapes[i] = new OIMO.CylinderShape(sc, s[n], s[n + 1]); break;
  104720. case "box": shapes[i] = new OIMO.BoxShape(sc, s[n], s[n + 1], s[n + 2]); break;
  104721. }
  104722. body.addShape(shapes[i]);
  104723. if (i > 0) {
  104724. //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
  104725. shapes[i].relativePosition = new OIMO.Vec3(p[n], p[n + 1], p[n + 2]);
  104726. if (r[n2 + 0]) shapes[i].relativeRotation = [r[n2], r[n2 + 1], r[n2 + 2], r[n2 + 3]];
  104727. }
  104728. }
  104729. // I'm static or i move
  104730. if (move) {
  104731. if (obj.massPos || obj.massRot) body.setupMass(0x1, false);
  104732. else body.setupMass(0x1, true);
  104733. if (noSleep) body.allowSleep = false;
  104734. else body.allowSleep = true;
  104735. } else {
  104736. body.setupMass(0x2);
  104737. }
  104738. body.name = obj.name || ' ';
  104739. // finaly add to physics world
  104740. this.addRigidBody(body);
  104741. return body;
  104742. }
  104743. }
  104744. //UMD simplified
  104745. var root = this;
  104746. if (!root['OIMO']) {
  104747. if (true)
  104748. module.exports = OIMO;
  104749. else if (typeof define === 'function' && define.amd)
  104750. define([], function () {
  104751. return OIMO;
  104752. });
  104753. else if (typeof exports === 'object')
  104754. exports["OIMO"] = OIMO;
  104755. else {
  104756. root["OIMO"] = OIMO;
  104757. }
  104758. }
  104759. /***/ }),
  104760. /* 19 */
  104761. /***/ (function(module, exports, __webpack_require__) {
  104762. "use strict";
  104763. Object.defineProperty(exports, "__esModule", { value: true });
  104764. var babylonjs_1 = __webpack_require__(0);
  104765. var helper_1 = __webpack_require__(2);
  104766. var TemplateManager = (function () {
  104767. function TemplateManager(containerElement) {
  104768. this.containerElement = containerElement;
  104769. this.templates = {};
  104770. this.onInit = new babylonjs_1.Observable();
  104771. this.onLoaded = new babylonjs_1.Observable();
  104772. this.onStateChange = new babylonjs_1.Observable();
  104773. this.onAllLoaded = new babylonjs_1.Observable();
  104774. this.onEventTriggered = new babylonjs_1.Observable();
  104775. this.eventManager = new eventManager_1.EventManager(this);
  104776. }
  104777. TemplateManager.prototype.initTemplate = function (templates) {
  104778. var _this = this;
  104779. var internalInit = function (dependencyMap, name, parentTemplate) {
  104780. var template = _this.templates[name];
  104781. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  104782. return internalInit(dependencyMap[childName], childName, template);
  104783. });
  104784. var addToParent = function () {
  104785. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  104786. template.appendTo(containingElement);
  104787. _this.checkLoadedState();
  104788. };
  104789. if (parentTemplate && !parentTemplate.parent) {
  104790. parentTemplate.onAppended.add(function () {
  104791. addToParent();
  104792. });
  104793. }
  104794. else {
  104795. addToParent();
  104796. }
  104797. return template;
  104798. };
  104799. return this.buildHTMLTree(templates).then(function (htmlTree) {
  104800. if (_this.templates['main']) {
  104801. internalInit(htmlTree, 'main');
  104802. }
  104803. else {
  104804. _this.checkLoadedState();
  104805. }
  104806. return;
  104807. });
  104808. };
  104809. TemplateManager.prototype.buildHTMLTree = function (templates) {
  104810. var _this = this;
  104811. var promises = Object.keys(templates).map(function (name) {
  104812. if (!templates[name])
  104813. return Promise.resolve(false);
  104814. var template = new Template(name, templates[name]);
  104815. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  104816. _this.templates[name] = template;
  104817. return template.initPromise;
  104818. });
  104819. return Promise.all(promises).then(function () {
  104820. var templateStructure = {};
  104821. var buildTree = function (parentObject, name) {
  104822. _this.templates[name].isInHtmlTree = true;
  104823. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  104824. childNodes.forEach(function (element) {
  104825. parentObject[element] = {};
  104826. buildTree(parentObject[element], element);
  104827. });
  104828. };
  104829. if (_this.templates['main']) {
  104830. buildTree(templateStructure, "main");
  104831. }
  104832. return templateStructure;
  104833. });
  104834. };
  104835. TemplateManager.prototype.getCanvas = function () {
  104836. return this.containerElement.querySelector('canvas');
  104837. };
  104838. TemplateManager.prototype.getTemplate = function (name) {
  104839. return this.templates[name];
  104840. };
  104841. TemplateManager.prototype.checkLoadedState = function () {
  104842. var _this = this;
  104843. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  104844. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  104845. });
  104846. if (done) {
  104847. this.onAllLoaded.notifyObservers(this);
  104848. }
  104849. };
  104850. TemplateManager.prototype.dispose = function () {
  104851. var _this = this;
  104852. Object.keys(this.templates).forEach(function (template) {
  104853. _this.templates[template].dispose();
  104854. });
  104855. this.onInit.clear();
  104856. this.onAllLoaded.clear();
  104857. this.onEventTriggered.clear();
  104858. this.onLoaded.clear();
  104859. this.onStateChange.clear();
  104860. };
  104861. return TemplateManager;
  104862. }());
  104863. exports.TemplateManager = TemplateManager;
  104864. var Handlebars = __webpack_require__(20);
  104865. var eventManager_1 = __webpack_require__(21);
  104866. Handlebars.registerHelper('eachInMap', function (map, block) {
  104867. var out = '';
  104868. Object.keys(map).map(function (prop) {
  104869. var data = map[prop];
  104870. if (typeof data === 'object') {
  104871. data.id = data.id || prop;
  104872. out += block.fn(data);
  104873. }
  104874. else {
  104875. out += block.fn({ id: prop, value: data });
  104876. }
  104877. });
  104878. return out;
  104879. });
  104880. var Template = (function () {
  104881. function Template(name, _configuration) {
  104882. var _this = this;
  104883. this.name = name;
  104884. this._configuration = _configuration;
  104885. this.onInit = new babylonjs_1.Observable();
  104886. this.onLoaded = new babylonjs_1.Observable();
  104887. this.onAppended = new babylonjs_1.Observable();
  104888. this.onStateChange = new babylonjs_1.Observable();
  104889. this.onEventTriggered = new babylonjs_1.Observable();
  104890. this.loadRequests = [];
  104891. this.isLoaded = false;
  104892. this.isShown = false;
  104893. this.isInHtmlTree = false;
  104894. this.onInit.notifyObservers(this);
  104895. var htmlContentPromise = this.getTemplateAsHtml(_configuration);
  104896. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  104897. if (htmlTemplate) {
  104898. _this.htmlTemplate = htmlTemplate;
  104899. var compiledTemplate = Handlebars.compile(htmlTemplate);
  104900. var config = _this._configuration.params || {};
  104901. var rawHtml = compiledTemplate(config);
  104902. _this.fragment = document.createRange().createContextualFragment(rawHtml);
  104903. _this.isLoaded = true;
  104904. _this.isShown = true;
  104905. _this.onLoaded.notifyObservers(_this);
  104906. }
  104907. return _this;
  104908. });
  104909. }
  104910. Template.prototype.updateParams = function (params) {
  104911. this._configuration.params = params;
  104912. if (this.isLoaded) {
  104913. this.dispose();
  104914. }
  104915. var compiledTemplate = Handlebars.compile(this.htmlTemplate);
  104916. var config = this._configuration.params || {};
  104917. var rawHtml = compiledTemplate(config);
  104918. this.fragment = document.createRange().createContextualFragment(rawHtml);
  104919. if (this.parent) {
  104920. this.appendTo(this.parent, true);
  104921. }
  104922. };
  104923. Object.defineProperty(Template.prototype, "configuration", {
  104924. get: function () {
  104925. return this._configuration;
  104926. },
  104927. enumerable: true,
  104928. configurable: true
  104929. });
  104930. Template.prototype.getChildElements = function () {
  104931. var childrenArray = [];
  104932. var children = this.fragment.children;
  104933. if (!children) {
  104934. children = this.fragment.querySelectorAll('*');
  104935. }
  104936. for (var i = 0; i < children.length; ++i) {
  104937. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  104938. }
  104939. return childrenArray;
  104940. };
  104941. Template.prototype.appendTo = function (parent, forceRemove) {
  104942. var _this = this;
  104943. if (this.parent) {
  104944. if (forceRemove) {
  104945. this.parent.removeChild(this.fragment);
  104946. }
  104947. else {
  104948. return;
  104949. }
  104950. }
  104951. this.parent = parent;
  104952. if (this._configuration.id) {
  104953. this.parent.id = this._configuration.id;
  104954. }
  104955. this.fragment = this.parent.appendChild(this.fragment);
  104956. setTimeout(function () {
  104957. _this.registerEvents();
  104958. _this.onAppended.notifyObservers(_this);
  104959. });
  104960. };
  104961. Template.prototype.show = function (visibilityFunction) {
  104962. var _this = this;
  104963. if (this.isHiding)
  104964. return Promise.resolve(this);
  104965. return Promise.resolve().then(function () {
  104966. _this.isShowing = true;
  104967. if (visibilityFunction) {
  104968. return visibilityFunction(_this);
  104969. }
  104970. else {
  104971. _this.parent.style.display = 'flex';
  104972. return _this;
  104973. }
  104974. }).then(function () {
  104975. _this.isShown = true;
  104976. _this.isShowing = false;
  104977. _this.onStateChange.notifyObservers(_this);
  104978. return _this;
  104979. });
  104980. };
  104981. Template.prototype.hide = function (visibilityFunction) {
  104982. var _this = this;
  104983. if (this.isShowing)
  104984. return Promise.resolve(this);
  104985. return Promise.resolve().then(function () {
  104986. _this.isHiding = true;
  104987. if (visibilityFunction) {
  104988. return visibilityFunction(_this);
  104989. }
  104990. else {
  104991. _this.parent.style.display = 'hide';
  104992. return _this;
  104993. }
  104994. }).then(function () {
  104995. _this.isShown = false;
  104996. _this.isHiding = false;
  104997. _this.onStateChange.notifyObservers(_this);
  104998. return _this;
  104999. });
  105000. };
  105001. Template.prototype.dispose = function () {
  105002. this.onAppended.clear();
  105003. this.onEventTriggered.clear();
  105004. this.onInit.clear();
  105005. this.onLoaded.clear();
  105006. this.onStateChange.clear();
  105007. this.isLoaded = false;
  105008. this.parent.removeChild(this.fragment);
  105009. this.loadRequests.forEach(function (request) {
  105010. request.abort();
  105011. });
  105012. };
  105013. Template.prototype.getTemplateAsHtml = function (templateConfig) {
  105014. var _this = this;
  105015. if (!templateConfig) {
  105016. return Promise.reject('No templateConfig provided');
  105017. }
  105018. else if (templateConfig.html !== undefined) {
  105019. return Promise.resolve(templateConfig.html);
  105020. }
  105021. else {
  105022. var location_1 = getTemplateLocation(templateConfig);
  105023. if (helper_1.isUrl(location_1)) {
  105024. return new Promise(function (resolve, reject) {
  105025. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  105026. resolve(data);
  105027. }, undefined, undefined, false, function (request, error) {
  105028. reject(error);
  105029. });
  105030. _this.loadRequests.push(fileRequest);
  105031. });
  105032. }
  105033. else {
  105034. location_1 = location_1.replace('#', '');
  105035. var element = document.getElementById(location_1);
  105036. if (element) {
  105037. return Promise.resolve(element.innerHTML);
  105038. }
  105039. else {
  105040. return Promise.reject('Template ID not found');
  105041. }
  105042. }
  105043. }
  105044. };
  105045. Template.prototype.registerEvents = function () {
  105046. var _this = this;
  105047. this.registeredEvents = this.registeredEvents || [];
  105048. if (this.registeredEvents.length) {
  105049. this.registeredEvents.forEach(function (evt) {
  105050. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  105051. });
  105052. }
  105053. if (this._configuration.events) {
  105054. var _loop_1 = function (eventName) {
  105055. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  105056. var functionToFire_1 = function (selector, event) {
  105057. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  105058. };
  105059. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  105060. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, '#' + this_1.parent.id), false);
  105061. }
  105062. else if (typeof this_1._configuration.events[eventName] === 'object') {
  105063. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  105064. var event_1 = this_1._configuration.events[eventName] || {};
  105065. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  105066. if (selector && selector.indexOf('#') !== 0) {
  105067. selector = '#' + selector;
  105068. }
  105069. var htmlElement = _this.parent.querySelector(selector);
  105070. if (htmlElement) {
  105071. var binding = functionToFire_1.bind(_this, selector);
  105072. htmlElement.addEventListener(eventName, binding, false);
  105073. _this.registeredEvents.push({
  105074. htmlElement: htmlElement,
  105075. eventName: eventName,
  105076. function: binding
  105077. });
  105078. }
  105079. });
  105080. }
  105081. }
  105082. };
  105083. var this_1 = this;
  105084. for (var eventName in this._configuration.events) {
  105085. _loop_1(eventName);
  105086. }
  105087. }
  105088. };
  105089. return Template;
  105090. }());
  105091. exports.Template = Template;
  105092. function getTemplateLocation(templateConfig) {
  105093. if (!templateConfig || typeof templateConfig === 'string') {
  105094. return templateConfig;
  105095. }
  105096. else {
  105097. return templateConfig.location;
  105098. }
  105099. }
  105100. exports.getTemplateLocation = getTemplateLocation;
  105101. /***/ }),
  105102. /* 20 */
  105103. /***/ (function(module, exports, __webpack_require__) {
  105104. /**!
  105105. @license
  105106. handlebars v4.0.11
  105107. Copyright (C) 2011-2017 by Yehuda Katz
  105108. Permission is hereby granted, free of charge, to any person obtaining a copy
  105109. of this software and associated documentation files (the "Software"), to deal
  105110. in the Software without restriction, including without limitation the rights
  105111. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  105112. copies of the Software, and to permit persons to whom the Software is
  105113. furnished to do so, subject to the following conditions:
  105114. The above copyright notice and this permission notice shall be included in
  105115. all copies or substantial portions of the Software.
  105116. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  105117. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  105118. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  105119. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  105120. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  105121. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  105122. THE SOFTWARE.
  105123. */
  105124. !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],
  105125. 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){
  105126. 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"]}])});
  105127. /***/ }),
  105128. /* 21 */
  105129. /***/ (function(module, exports, __webpack_require__) {
  105130. "use strict";
  105131. Object.defineProperty(exports, "__esModule", { value: true });
  105132. var EventManager = (function () {
  105133. function EventManager(templateManager) {
  105134. var _this = this;
  105135. this.templateManager = templateManager;
  105136. this.callbacksContainer = {};
  105137. this.templateManager.onEventTriggered.add(function (eventData) {
  105138. _this.eventTriggered(eventData);
  105139. });
  105140. }
  105141. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  105142. if (!this.callbacksContainer[templateName]) {
  105143. this.callbacksContainer[templateName] = [];
  105144. }
  105145. this.callbacksContainer[templateName].push({
  105146. eventType: eventType,
  105147. callback: callback
  105148. });
  105149. };
  105150. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  105151. var callbackDefs = this.callbacksContainer[templateName] || [];
  105152. this.callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  105153. };
  105154. EventManager.prototype.eventTriggered = function (data) {
  105155. var templateName = data.template.name;
  105156. var eventType = data.event.type;
  105157. var selector = data.selector;
  105158. var callbackDefs = this.callbacksContainer[templateName] || [];
  105159. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  105160. callbackDef.callback(data);
  105161. });
  105162. };
  105163. return EventManager;
  105164. }());
  105165. exports.EventManager = EventManager;
  105166. /***/ }),
  105167. /* 22 */
  105168. /***/ (function(module, exports, __webpack_require__) {
  105169. "use strict";
  105170. Object.defineProperty(exports, "__esModule", { value: true });
  105171. var mappers_1 = __webpack_require__(1);
  105172. var types_1 = __webpack_require__(23);
  105173. var deepmerge = __webpack_require__(13);
  105174. var babylonjs_1 = __webpack_require__(0);
  105175. var ConfigurationLoader = (function () {
  105176. function ConfigurationLoader() {
  105177. this.configurationCache = {};
  105178. this.loadRequests = [];
  105179. }
  105180. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  105181. var _this = this;
  105182. if (initConfig === void 0) { initConfig = {}; }
  105183. var loadedConfig = deepmerge({}, initConfig);
  105184. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  105185. loadedConfig = deepmerge(extendedConfiguration, loadedConfig);
  105186. if (loadedConfig.configuration) {
  105187. var mapperType_1 = "json";
  105188. return Promise.resolve().then(function () {
  105189. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  105190. var url = '';
  105191. if (typeof loadedConfig.configuration === "string") {
  105192. url = loadedConfig.configuration;
  105193. }
  105194. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  105195. url = loadedConfig.configuration.url;
  105196. var type = loadedConfig.configuration.mapper;
  105197. if (!type) {
  105198. type = loadedConfig.configuration.url.split('.').pop();
  105199. }
  105200. mapperType_1 = type || mapperType_1;
  105201. }
  105202. return _this.loadFile(url);
  105203. }
  105204. else {
  105205. if (typeof loadedConfig.configuration === "object") {
  105206. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  105207. return loadedConfig.configuration.payload || {};
  105208. }
  105209. return {};
  105210. }
  105211. }).then(function (data) {
  105212. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  105213. var parsed = mapper.map(data);
  105214. var merged = deepmerge(loadedConfig, parsed);
  105215. if (callback)
  105216. callback(merged);
  105217. return merged;
  105218. });
  105219. }
  105220. else {
  105221. if (callback)
  105222. callback(loadedConfig);
  105223. return Promise.resolve(loadedConfig);
  105224. }
  105225. };
  105226. ConfigurationLoader.prototype.dispose = function () {
  105227. this.loadRequests.forEach(function (request) {
  105228. request.abort();
  105229. });
  105230. };
  105231. ConfigurationLoader.prototype.loadFile = function (url) {
  105232. var _this = this;
  105233. var cacheReference = this.configurationCache;
  105234. if (cacheReference[url]) {
  105235. return Promise.resolve(cacheReference[url]);
  105236. }
  105237. return new Promise(function (resolve, reject) {
  105238. var fileRequest = babylonjs_1.Tools.LoadFile(url, resolve, undefined, undefined, false, function (request, error) {
  105239. reject(error);
  105240. });
  105241. _this.loadRequests.push(fileRequest);
  105242. });
  105243. };
  105244. return ConfigurationLoader;
  105245. }());
  105246. exports.ConfigurationLoader = ConfigurationLoader;
  105247. exports.configurationLoader = new ConfigurationLoader();
  105248. exports.default = exports.configurationLoader;
  105249. /***/ }),
  105250. /* 23 */
  105251. /***/ (function(module, exports, __webpack_require__) {
  105252. "use strict";
  105253. Object.defineProperty(exports, "__esModule", { value: true });
  105254. var minimal_1 = __webpack_require__(24);
  105255. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  105256. var default_1 = __webpack_require__(25);
  105257. exports.defaultConfiguration = default_1.defaultConfiguration;
  105258. var getConfigurationType = function (type) {
  105259. switch (type) {
  105260. case 'default':
  105261. return default_1.defaultConfiguration;
  105262. case 'minimal':
  105263. return minimal_1.minimalConfiguration;
  105264. case 'none':
  105265. return {};
  105266. default:
  105267. return default_1.defaultConfiguration;
  105268. }
  105269. };
  105270. exports.getConfigurationType = getConfigurationType;
  105271. /***/ }),
  105272. /* 24 */
  105273. /***/ (function(module, exports, __webpack_require__) {
  105274. "use strict";
  105275. Object.defineProperty(exports, "__esModule", { value: true });
  105276. exports.minimalConfiguration = {
  105277. version: "0.1",
  105278. templates: {
  105279. main: {
  105280. html: __webpack_require__(6)
  105281. },
  105282. loadingScreen: {
  105283. html: __webpack_require__(7),
  105284. params: {
  105285. backgroundColor: "#000000",
  105286. loadingImage: __webpack_require__(8)
  105287. }
  105288. },
  105289. viewer: {
  105290. html: __webpack_require__(9),
  105291. },
  105292. overlay: {
  105293. html: __webpack_require__(10),
  105294. params: {
  105295. closeImage: __webpack_require__(11),
  105296. closeText: 'Close'
  105297. }
  105298. },
  105299. error: {
  105300. html: __webpack_require__(12)
  105301. }
  105302. },
  105303. engine: {
  105304. antialiasing: true
  105305. }
  105306. };
  105307. /***/ }),
  105308. /* 25 */
  105309. /***/ (function(module, exports, __webpack_require__) {
  105310. "use strict";
  105311. Object.defineProperty(exports, "__esModule", { value: true });
  105312. exports.defaultConfiguration = {
  105313. version: "3.2.0-alpha4",
  105314. templates: {
  105315. main: {
  105316. html: __webpack_require__(6)
  105317. },
  105318. loadingScreen: {
  105319. html: __webpack_require__(7),
  105320. params: {
  105321. backgroundColor: "#000000",
  105322. loadingImage: __webpack_require__(8)
  105323. }
  105324. },
  105325. viewer: {
  105326. html: __webpack_require__(9),
  105327. events: {
  105328. pointerout: true,
  105329. pointerdown: true,
  105330. pointerup: true
  105331. }
  105332. },
  105333. navBar: {
  105334. html: __webpack_require__(26),
  105335. params: {
  105336. buttons: {
  105337. "fullscreen-button": {
  105338. altText: "Fullscreen",
  105339. image: __webpack_require__(27)
  105340. }
  105341. },
  105342. visibilityTimeout: 2000
  105343. },
  105344. events: {
  105345. pointerdown: { 'fullscreen-button': true },
  105346. pointerover: true
  105347. }
  105348. },
  105349. overlay: {
  105350. html: __webpack_require__(10),
  105351. params: {
  105352. closeImage: __webpack_require__(11),
  105353. closeText: 'Close'
  105354. }
  105355. },
  105356. help: {
  105357. html: __webpack_require__(28)
  105358. },
  105359. share: {
  105360. html: __webpack_require__(29)
  105361. },
  105362. error: {
  105363. html: __webpack_require__(12)
  105364. }
  105365. },
  105366. camera: {
  105367. behaviors: {
  105368. autoRotate: 0,
  105369. framing: {
  105370. type: 2,
  105371. zoomOnBoundingInfo: true,
  105372. zoomStopsAnimation: false
  105373. }
  105374. }
  105375. },
  105376. skybox: {
  105377. pbr: true,
  105378. blur: 0.7,
  105379. infiniteDIstance: false,
  105380. },
  105381. ground: true,
  105382. engine: {
  105383. antialiasing: true
  105384. },
  105385. scene: {
  105386. imageProcessingConfiguration: {
  105387. exposure: 1.4,
  105388. contrast: 1.66,
  105389. toneMappingEnabled: true
  105390. }
  105391. }
  105392. };
  105393. /***/ }),
  105394. /* 26 */
  105395. /***/ (function(module, exports) {
  105396. 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>";
  105397. /***/ }),
  105398. /* 27 */
  105399. /***/ (function(module, exports) {
  105400. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQAAAAB/ecQqAAAAAnRSTlMAAHaTzTgAAAAeSURBVHgBY6ASsP/A/wcXZQNGhCkyAfE24HUndQAAXlkXcQ24P7gAAAAASUVORK5CYII="
  105401. /***/ }),
  105402. /* 28 */
  105403. /***/ (function(module, exports) {
  105404. module.exports = "HELP";
  105405. /***/ }),
  105406. /* 29 */
  105407. /***/ (function(module, exports) {
  105408. module.exports = "SHARE";
  105409. /***/ }),
  105410. /* 30 */
  105411. /***/ (function(module, exports, __webpack_require__) {
  105412. "use strict";
  105413. Object.defineProperty(exports, "__esModule", { value: true });
  105414. var babylonjs_1 = __webpack_require__(0);
  105415. var modelAnimation_1 = __webpack_require__(31);
  105416. var ViewerModel = (function () {
  105417. function ViewerModel(_modelConfiguration, _scene, disableAutoLoad) {
  105418. if (disableAutoLoad === void 0) { disableAutoLoad = false; }
  105419. this._modelConfiguration = _modelConfiguration;
  105420. this._scene = _scene;
  105421. this.onLoadedObservable = new babylonjs_1.Observable();
  105422. this.onLoadErrorObservable = new babylonjs_1.Observable();
  105423. this.onLoadProgressObservable = new babylonjs_1.Observable();
  105424. this._animations = [];
  105425. if (!disableAutoLoad) {
  105426. this._initLoad();
  105427. }
  105428. }
  105429. ViewerModel.prototype.load = function () {
  105430. if (this.loader) {
  105431. babylonjs_1.Tools.Error("Model was already loaded or in the process of loading.");
  105432. }
  105433. else {
  105434. this._initLoad();
  105435. }
  105436. };
  105437. ViewerModel.prototype.getAnimationNames = function () {
  105438. return this._animations.map(function (a) { return a.name; });
  105439. };
  105440. ViewerModel.prototype._getAnimationByName = function (name) {
  105441. var filtered = this._animations.filter(function (a) { return a.name === name; });
  105442. if (filtered.length === 1) {
  105443. return filtered[0];
  105444. }
  105445. else {
  105446. return null;
  105447. }
  105448. };
  105449. ViewerModel.prototype.playAnimation = function (name) {
  105450. var animation = this._getAnimationByName(name);
  105451. if (animation) {
  105452. if (this.currentAnimation) {
  105453. this.currentAnimation.stop();
  105454. }
  105455. this.currentAnimation = animation;
  105456. animation.start();
  105457. return animation;
  105458. }
  105459. else {
  105460. throw new Error("animation not found - " + name);
  105461. }
  105462. };
  105463. ViewerModel.prototype._initLoad = function () {
  105464. var _this = this;
  105465. if (!this._modelConfiguration || !this._modelConfiguration.url) {
  105466. return babylonjs_1.Tools.Error("No model URL to load.");
  105467. }
  105468. var parts = this._modelConfiguration.url.split('/');
  105469. var filename = parts.pop() || this._modelConfiguration.url;
  105470. var base = parts.length ? parts.join('/') + '/' : './';
  105471. var plugin = this._modelConfiguration.loader;
  105472. var animationsArray = this._scene.animationGroups.slice();
  105473. this.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, this._scene, function (meshes, particleSystems, skeletons) {
  105474. meshes.forEach(function (mesh) {
  105475. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  105476. });
  105477. _this.meshes = meshes;
  105478. _this.particleSystems = particleSystems;
  105479. _this.skeletons = skeletons;
  105480. if (_this.loader.name === 'gltf') {
  105481. _this._scene.animationGroups.forEach(function (ag) {
  105482. if (animationsArray.indexOf(ag) === -1) {
  105483. _this._animations.push(new modelAnimation_1.GroupModelAnimation(ag));
  105484. }
  105485. });
  105486. }
  105487. else {
  105488. skeletons.forEach(function (skeleton, idx) {
  105489. var ag = new BABYLON.AnimationGroup("animation-" + idx, _this._scene);
  105490. skeleton.getAnimatables().forEach(function (a) {
  105491. if (a.animations[0]) {
  105492. ag.addTargetedAnimation(a.animations[0], a);
  105493. }
  105494. });
  105495. _this._animations.push(new modelAnimation_1.GroupModelAnimation(ag));
  105496. });
  105497. }
  105498. if (_this._modelConfiguration.animation) {
  105499. if (_this._modelConfiguration.animation.playOnce) {
  105500. _this._animations.forEach(function (a) {
  105501. a.playMode = modelAnimation_1.AnimationPlayMode.ONCE;
  105502. });
  105503. }
  105504. if (_this._modelConfiguration.animation.autoStart && _this._animations.length) {
  105505. var animationName = _this._modelConfiguration.animation.autoStart === true ?
  105506. _this._animations[0].name : _this._modelConfiguration.animation.autoStart;
  105507. _this.playAnimation(animationName);
  105508. }
  105509. }
  105510. _this.onLoadedObservable.notifyObserversWithPromise(_this);
  105511. }, function (progressEvent) {
  105512. _this.onLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  105513. }, function (e, m, exception) {
  105514. _this.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception });
  105515. }, plugin);
  105516. this.loader['animationStartMode'] = 0;
  105517. };
  105518. ViewerModel.prototype.dispose = function () {
  105519. this.particleSystems.forEach(function (ps) { return ps.dispose(); });
  105520. this.skeletons.forEach(function (s) { return s.dispose(); });
  105521. this._animations.forEach(function (ag) { return ag.dispose(); });
  105522. this.meshes.forEach(function (m) { return m.dispose(); });
  105523. };
  105524. return ViewerModel;
  105525. }());
  105526. exports.ViewerModel = ViewerModel;
  105527. /***/ }),
  105528. /* 31 */
  105529. /***/ (function(module, exports, __webpack_require__) {
  105530. "use strict";
  105531. Object.defineProperty(exports, "__esModule", { value: true });
  105532. var AnimationPlayMode;
  105533. (function (AnimationPlayMode) {
  105534. AnimationPlayMode[AnimationPlayMode["ONCE"] = 0] = "ONCE";
  105535. AnimationPlayMode[AnimationPlayMode["LOOP"] = 1] = "LOOP";
  105536. })(AnimationPlayMode = exports.AnimationPlayMode || (exports.AnimationPlayMode = {}));
  105537. var AnimationState;
  105538. (function (AnimationState) {
  105539. AnimationState[AnimationState["INIT"] = 0] = "INIT";
  105540. AnimationState[AnimationState["PLAYING"] = 1] = "PLAYING";
  105541. AnimationState[AnimationState["PAUSED"] = 2] = "PAUSED";
  105542. AnimationState[AnimationState["STOPPED"] = 3] = "STOPPED";
  105543. AnimationState[AnimationState["ENDED"] = 4] = "ENDED";
  105544. })(AnimationState = exports.AnimationState || (exports.AnimationState = {}));
  105545. var GroupModelAnimation = (function () {
  105546. function GroupModelAnimation(_animationGroup) {
  105547. var _this = this;
  105548. this._animationGroup = _animationGroup;
  105549. this._state = AnimationState.INIT;
  105550. this._playMode = AnimationPlayMode.LOOP;
  105551. this._animationGroup.onAnimationEndObservable.add(function () {
  105552. _this.stop();
  105553. _this._state = AnimationState.ENDED;
  105554. });
  105555. }
  105556. Object.defineProperty(GroupModelAnimation.prototype, "name", {
  105557. get: function () {
  105558. return this._animationGroup.name;
  105559. },
  105560. enumerable: true,
  105561. configurable: true
  105562. });
  105563. Object.defineProperty(GroupModelAnimation.prototype, "state", {
  105564. get: function () {
  105565. return this._state;
  105566. },
  105567. enumerable: true,
  105568. configurable: true
  105569. });
  105570. Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", {
  105571. get: function () {
  105572. return this._animationGroup.speedRatio;
  105573. },
  105574. set: function (value) {
  105575. this._animationGroup.speedRatio = value;
  105576. },
  105577. enumerable: true,
  105578. configurable: true
  105579. });
  105580. Object.defineProperty(GroupModelAnimation.prototype, "frames", {
  105581. get: function () {
  105582. var animationFrames = this._animationGroup.targetedAnimations.map(function (ta) {
  105583. var keys = ta.animation.getKeys();
  105584. return keys[keys.length - 1].frame;
  105585. });
  105586. return Math.max.apply(null, animationFrames);
  105587. },
  105588. enumerable: true,
  105589. configurable: true
  105590. });
  105591. Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", {
  105592. get: function () {
  105593. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  105594. var animatable = this._animationGroup.animatables[i];
  105595. var animations = animatable.getAnimations();
  105596. if (!animations || !animations.length) {
  105597. continue;
  105598. }
  105599. for (var idx = 0; idx < animations.length; ++idx) {
  105600. if (animations[idx].currentFrame) {
  105601. return animations[idx].currentFrame;
  105602. }
  105603. }
  105604. }
  105605. return 0;
  105606. },
  105607. enumerable: true,
  105608. configurable: true
  105609. });
  105610. Object.defineProperty(GroupModelAnimation.prototype, "fps", {
  105611. get: function () {
  105612. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  105613. var animatable = this._animationGroup.animatables[i];
  105614. var animations = animatable.getAnimations();
  105615. if (!animations || !animations.length) {
  105616. continue;
  105617. }
  105618. for (var idx = 0; idx < animations.length; ++idx) {
  105619. if (animations[idx].animation && animations[idx].animation.framePerSecond) {
  105620. return animations[idx].animation.framePerSecond;
  105621. }
  105622. }
  105623. }
  105624. return 0;
  105625. },
  105626. enumerable: true,
  105627. configurable: true
  105628. });
  105629. Object.defineProperty(GroupModelAnimation.prototype, "playMode", {
  105630. get: function () {
  105631. return this._playMode;
  105632. },
  105633. set: function (value) {
  105634. if (value === this._playMode) {
  105635. return;
  105636. }
  105637. this._playMode = value;
  105638. if (this.state === AnimationState.PLAYING) {
  105639. this._animationGroup.play(this._playMode === AnimationPlayMode.LOOP);
  105640. }
  105641. else {
  105642. this._animationGroup.reset();
  105643. this._state = AnimationState.INIT;
  105644. }
  105645. },
  105646. enumerable: true,
  105647. configurable: true
  105648. });
  105649. GroupModelAnimation.prototype.reset = function () {
  105650. this._animationGroup.reset();
  105651. };
  105652. GroupModelAnimation.prototype.restart = function () {
  105653. this._animationGroup.restart();
  105654. };
  105655. GroupModelAnimation.prototype.goToFrame = function (frameNumber) {
  105656. this._animationGroup['_animatables'].forEach(function (a) {
  105657. a.goToFrame(frameNumber);
  105658. });
  105659. };
  105660. GroupModelAnimation.prototype.start = function () {
  105661. this._animationGroup.start(this.playMode === AnimationPlayMode.LOOP, this.speedRatio);
  105662. if (this._animationGroup.isStarted) {
  105663. this._state = AnimationState.PLAYING;
  105664. }
  105665. };
  105666. GroupModelAnimation.prototype.pause = function () {
  105667. this._animationGroup.pause();
  105668. this._state = AnimationState.PAUSED;
  105669. };
  105670. GroupModelAnimation.prototype.stop = function () {
  105671. this._animationGroup.stop();
  105672. if (!this._animationGroup.isStarted) {
  105673. this._state = AnimationState.STOPPED;
  105674. }
  105675. };
  105676. GroupModelAnimation.prototype.dispose = function () {
  105677. this._animationGroup.dispose();
  105678. };
  105679. return GroupModelAnimation;
  105680. }());
  105681. exports.GroupModelAnimation = GroupModelAnimation;
  105682. /***/ }),
  105683. /* 32 */
  105684. /***/ (function(module, exports, __webpack_require__) {
  105685. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  105686. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  105687. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  105688. 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;
  105689. return c > 3 && r && Object.defineProperty(target, key, r), r;
  105690. };
  105691. var __extends = (this && this.__extends) || (function () {
  105692. var extendStatics = Object.setPrototypeOf ||
  105693. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  105694. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  105695. return function (d, b) {
  105696. extendStatics(d, b);
  105697. function __() { this.constructor = d; }
  105698. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  105699. };
  105700. })();
  105701. (function universalModuleDefinition(root, factory) {
  105702. if(true)
  105703. module.exports = factory(__webpack_require__(0));
  105704. else if(typeof define === 'function' && define.amd)
  105705. define("babylonjs-loaders", ["babylonjs"], factory);
  105706. else if(typeof exports === 'object')
  105707. exports["babylonjs-loaders"] = factory(require("babylonjs"));
  105708. else {
  105709. root["BABYLON"] = factory(root["BABYLON"]);
  105710. }
  105711. })(this, function(BABYLON) {
  105712. "use strict";
  105713. var BABYLON;
  105714. (function (BABYLON) {
  105715. var STLFileLoader = /** @class */ (function () {
  105716. function STLFileLoader() {
  105717. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  105718. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  105719. 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;
  105720. 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;
  105721. this.name = "stl";
  105722. // force data to come in as an ArrayBuffer
  105723. // we'll convert to string if it looks like it's an ASCII .stl
  105724. this.extensions = {
  105725. ".stl": { isBinary: true },
  105726. };
  105727. }
  105728. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  105729. var matches;
  105730. if (this.isBinary(data)) {
  105731. // binary .stl
  105732. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  105733. this.parseBinary(babylonMesh, data);
  105734. if (meshes) {
  105735. meshes.push(babylonMesh);
  105736. }
  105737. return true;
  105738. }
  105739. // ASCII .stl
  105740. // convert to string
  105741. var array_buffer = new Uint8Array(data);
  105742. var str = '';
  105743. for (var i = 0; i < data.byteLength; i++) {
  105744. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  105745. }
  105746. data = str;
  105747. while (matches = this.solidPattern.exec(data)) {
  105748. var meshName = matches[1];
  105749. var meshNameFromEnd = matches[3];
  105750. if (meshName != meshNameFromEnd) {
  105751. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  105752. return false;
  105753. }
  105754. // check meshesNames
  105755. if (meshesNames && meshName) {
  105756. if (meshesNames instanceof Array) {
  105757. if (!meshesNames.indexOf(meshName)) {
  105758. continue;
  105759. }
  105760. }
  105761. else {
  105762. if (meshName !== meshesNames) {
  105763. continue;
  105764. }
  105765. }
  105766. }
  105767. // stl mesh name can be empty as well
  105768. meshName = meshName || "stlmesh";
  105769. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  105770. this.parseASCII(babylonMesh, matches[2]);
  105771. if (meshes) {
  105772. meshes.push(babylonMesh);
  105773. }
  105774. }
  105775. return true;
  105776. };
  105777. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  105778. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  105779. if (result) {
  105780. scene.createDefaultCameraOrLight();
  105781. }
  105782. return result;
  105783. };
  105784. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  105785. var container = new BABYLON.AssetContainer(scene);
  105786. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  105787. container.removeAllFromScene();
  105788. return container;
  105789. };
  105790. STLFileLoader.prototype.isBinary = function (data) {
  105791. // check if file size is correct for binary stl
  105792. var faceSize, nFaces, reader;
  105793. reader = new DataView(data);
  105794. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  105795. nFaces = reader.getUint32(80, true);
  105796. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  105797. return true;
  105798. }
  105799. // check characters higher than ASCII to confirm binary
  105800. var fileLength = reader.byteLength;
  105801. for (var index = 0; index < fileLength; index++) {
  105802. if (reader.getUint8(index) > 127) {
  105803. return true;
  105804. }
  105805. }
  105806. return false;
  105807. };
  105808. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  105809. var reader = new DataView(data);
  105810. var faces = reader.getUint32(80, true);
  105811. var dataOffset = 84;
  105812. var faceLength = 12 * 4 + 2;
  105813. var offset = 0;
  105814. var positions = new Float32Array(faces * 3 * 3);
  105815. var normals = new Float32Array(faces * 3 * 3);
  105816. var indices = new Uint32Array(faces * 3);
  105817. var indicesCount = 0;
  105818. for (var face = 0; face < faces; face++) {
  105819. var start = dataOffset + face * faceLength;
  105820. var normalX = reader.getFloat32(start, true);
  105821. var normalY = reader.getFloat32(start + 4, true);
  105822. var normalZ = reader.getFloat32(start + 8, true);
  105823. for (var i = 1; i <= 3; i++) {
  105824. var vertexstart = start + i * 12;
  105825. // ordering is intentional to match ascii import
  105826. positions[offset] = reader.getFloat32(vertexstart, true);
  105827. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  105828. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  105829. normals[offset] = normalX;
  105830. normals[offset + 2] = normalY;
  105831. normals[offset + 1] = normalZ;
  105832. offset += 3;
  105833. }
  105834. indices[indicesCount] = indicesCount++;
  105835. indices[indicesCount] = indicesCount++;
  105836. indices[indicesCount] = indicesCount++;
  105837. }
  105838. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  105839. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  105840. mesh.setIndices(indices);
  105841. mesh.computeWorldMatrix(true);
  105842. };
  105843. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  105844. var positions = [];
  105845. var normals = [];
  105846. var indices = [];
  105847. var indicesCount = 0;
  105848. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  105849. var matches;
  105850. while (matches = this.facetsPattern.exec(solidData)) {
  105851. var facet = matches[1];
  105852. //one normal per face
  105853. var normalMatches = this.normalPattern.exec(facet);
  105854. this.normalPattern.lastIndex = 0;
  105855. if (!normalMatches) {
  105856. continue;
  105857. }
  105858. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  105859. var vertexMatch;
  105860. while (vertexMatch = this.vertexPattern.exec(facet)) {
  105861. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  105862. normals.push(normal[0], normal[1], normal[2]);
  105863. }
  105864. indices.push(indicesCount++, indicesCount++, indicesCount++);
  105865. this.vertexPattern.lastIndex = 0;
  105866. }
  105867. this.facetsPattern.lastIndex = 0;
  105868. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  105869. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  105870. mesh.setIndices(indices);
  105871. mesh.computeWorldMatrix(true);
  105872. };
  105873. return STLFileLoader;
  105874. }());
  105875. BABYLON.STLFileLoader = STLFileLoader;
  105876. if (BABYLON.SceneLoader) {
  105877. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  105878. }
  105879. })(BABYLON || (BABYLON = {}));
  105880. //# sourceMappingURL=babylon.stlFileLoader.js.map
  105881. "use strict";
  105882. var BABYLON;
  105883. (function (BABYLON) {
  105884. /**
  105885. * Class reading and parsing the MTL file bundled with the obj file.
  105886. */
  105887. var MTLFileLoader = /** @class */ (function () {
  105888. function MTLFileLoader() {
  105889. // All material loaded from the mtl will be set here
  105890. this.materials = [];
  105891. }
  105892. /**
  105893. * This function will read the mtl file and create each material described inside
  105894. * This function could be improve by adding :
  105895. * -some component missing (Ni, Tf...)
  105896. * -including the specific options available
  105897. *
  105898. * @param scene
  105899. * @param data
  105900. * @param rootUrl
  105901. */
  105902. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  105903. if (data instanceof ArrayBuffer) {
  105904. return;
  105905. }
  105906. //Split the lines from the file
  105907. var lines = data.split('\n');
  105908. //Space char
  105909. var delimiter_pattern = /\s+/;
  105910. //Array with RGB colors
  105911. var color;
  105912. //New material
  105913. var material = null;
  105914. //Look at each line
  105915. for (var i = 0; i < lines.length; i++) {
  105916. var line = lines[i].trim();
  105917. // Blank line or comment
  105918. if (line.length === 0 || line.charAt(0) === '#') {
  105919. continue;
  105920. }
  105921. //Get the first parameter (keyword)
  105922. var pos = line.indexOf(' ');
  105923. var key = (pos >= 0) ? line.substring(0, pos) : line;
  105924. key = key.toLowerCase();
  105925. //Get the data following the key
  105926. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  105927. //This mtl keyword will create the new material
  105928. if (key === "newmtl") {
  105929. //Check if it is the first material.
  105930. // Materials specifications are described after this keyword.
  105931. if (material) {
  105932. //Add the previous material in the material array.
  105933. this.materials.push(material);
  105934. }
  105935. //Create a new material.
  105936. // value is the name of the material read in the mtl file
  105937. material = new BABYLON.StandardMaterial(value, scene);
  105938. }
  105939. else if (key === "kd" && material) {
  105940. // Diffuse color (color under white light) using RGB values
  105941. //value = "r g b"
  105942. color = value.split(delimiter_pattern, 3).map(parseFloat);
  105943. //color = [r,g,b]
  105944. //Set tghe color into the material
  105945. material.diffuseColor = BABYLON.Color3.FromArray(color);
  105946. }
  105947. else if (key === "ka" && material) {
  105948. // Ambient color (color under shadow) using RGB values
  105949. //value = "r g b"
  105950. color = value.split(delimiter_pattern, 3).map(parseFloat);
  105951. //color = [r,g,b]
  105952. //Set tghe color into the material
  105953. material.ambientColor = BABYLON.Color3.FromArray(color);
  105954. }
  105955. else if (key === "ks" && material) {
  105956. // Specular color (color when light is reflected from shiny surface) using RGB values
  105957. //value = "r g b"
  105958. color = value.split(delimiter_pattern, 3).map(parseFloat);
  105959. //color = [r,g,b]
  105960. //Set the color into the material
  105961. material.specularColor = BABYLON.Color3.FromArray(color);
  105962. }
  105963. else if (key === "ke" && material) {
  105964. // Emissive color using RGB values
  105965. color = value.split(delimiter_pattern, 3).map(parseFloat);
  105966. material.emissiveColor = BABYLON.Color3.FromArray(color);
  105967. }
  105968. else if (key === "ns" && material) {
  105969. //value = "Integer"
  105970. material.specularPower = parseFloat(value);
  105971. }
  105972. else if (key === "d" && material) {
  105973. //d is dissolve for current material. It mean alpha for BABYLON
  105974. material.alpha = parseFloat(value);
  105975. //Texture
  105976. //This part can be improved by adding the possible options of texture
  105977. }
  105978. else if (key === "map_ka" && material) {
  105979. // ambient texture map with a loaded image
  105980. //We must first get the folder of the image
  105981. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105982. }
  105983. else if (key === "map_kd" && material) {
  105984. // Diffuse texture map with a loaded image
  105985. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105986. }
  105987. else if (key === "map_ks" && material) {
  105988. // Specular texture map with a loaded image
  105989. //We must first get the folder of the image
  105990. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105991. }
  105992. else if (key === "map_ns") {
  105993. //Specular
  105994. //Specular highlight component
  105995. //We must first get the folder of the image
  105996. //
  105997. //Not supported by BABYLON
  105998. //
  105999. // continue;
  106000. }
  106001. else if (key === "map_bump" && material) {
  106002. //The bump texture
  106003. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  106004. }
  106005. else if (key === "map_d" && material) {
  106006. // The dissolve of the material
  106007. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  106008. //Options for illumination
  106009. }
  106010. else if (key === "illum") {
  106011. //Illumination
  106012. if (value === "0") {
  106013. //That mean Kd == Kd
  106014. }
  106015. else if (value === "1") {
  106016. //Color on and Ambient on
  106017. }
  106018. else if (value === "2") {
  106019. //Highlight on
  106020. }
  106021. else if (value === "3") {
  106022. //Reflection on and Ray trace on
  106023. }
  106024. else if (value === "4") {
  106025. //Transparency: Glass on, Reflection: Ray trace on
  106026. }
  106027. else if (value === "5") {
  106028. //Reflection: Fresnel on and Ray trace on
  106029. }
  106030. else if (value === "6") {
  106031. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  106032. }
  106033. else if (value === "7") {
  106034. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  106035. }
  106036. else if (value === "8") {
  106037. //Reflection on and Ray trace off
  106038. }
  106039. else if (value === "9") {
  106040. //Transparency: Glass on, Reflection: Ray trace off
  106041. }
  106042. else if (value === "10") {
  106043. //Casts shadows onto invisible surfaces
  106044. }
  106045. }
  106046. else {
  106047. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  106048. }
  106049. }
  106050. //At the end of the file, add the last material
  106051. if (material) {
  106052. this.materials.push(material);
  106053. }
  106054. };
  106055. /**
  106056. * Gets the texture for the material.
  106057. *
  106058. * If the material is imported from input file,
  106059. * We sanitize the url to ensure it takes the textre from aside the material.
  106060. *
  106061. * @param rootUrl The root url to load from
  106062. * @param value The value stored in the mtl
  106063. * @return The Texture
  106064. */
  106065. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  106066. if (!value) {
  106067. return null;
  106068. }
  106069. var url = rootUrl;
  106070. // Load from input file.
  106071. if (rootUrl === "file:") {
  106072. var lastDelimiter = value.lastIndexOf("\\");
  106073. if (lastDelimiter === -1) {
  106074. lastDelimiter = value.lastIndexOf("/");
  106075. }
  106076. if (lastDelimiter > -1) {
  106077. url += value.substr(lastDelimiter + 1);
  106078. }
  106079. else {
  106080. url += value;
  106081. }
  106082. }
  106083. else {
  106084. url += value;
  106085. }
  106086. return new BABYLON.Texture(url, scene);
  106087. };
  106088. return MTLFileLoader;
  106089. }());
  106090. BABYLON.MTLFileLoader = MTLFileLoader;
  106091. var OBJFileLoader = /** @class */ (function () {
  106092. function OBJFileLoader() {
  106093. this.name = "obj";
  106094. this.extensions = ".obj";
  106095. this.obj = /^o/;
  106096. this.group = /^g/;
  106097. this.mtllib = /^mtllib /;
  106098. this.usemtl = /^usemtl /;
  106099. this.smooth = /^s /;
  106100. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  106101. // vn float float float
  106102. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  106103. // vt float float
  106104. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  106105. // f vertex vertex vertex ...
  106106. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  106107. // f vertex/uvs vertex/uvs vertex/uvs ...
  106108. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  106109. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  106110. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  106111. // f vertex//normal vertex//normal vertex//normal ...
  106112. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  106113. }
  106114. /**
  106115. * Calls synchronously the MTL file attached to this obj.
  106116. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  106117. * Without this function materials are not displayed in the first frame (but displayed after).
  106118. * In consequence it is impossible to get material information in your HTML file
  106119. *
  106120. * @param url The URL of the MTL file
  106121. * @param rootUrl
  106122. * @param onSuccess Callback function to be called when the MTL file is loaded
  106123. * @private
  106124. */
  106125. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  106126. //The complete path to the mtl file
  106127. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  106128. // Loads through the babylon tools to allow fileInput search.
  106129. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  106130. };
  106131. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  106132. //get the meshes from OBJ file
  106133. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  106134. //Push meshes from OBJ file into the variable mesh of this function
  106135. if (meshes) {
  106136. loadedMeshes.forEach(function (mesh) {
  106137. meshes.push(mesh);
  106138. });
  106139. }
  106140. return true;
  106141. };
  106142. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  106143. //Get the 3D model
  106144. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  106145. };
  106146. OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  106147. var container = new BABYLON.AssetContainer(scene);
  106148. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  106149. container.removeAllFromScene();
  106150. return container;
  106151. };
  106152. /**
  106153. * Read the OBJ file and create an Array of meshes.
  106154. * Each mesh contains all information given by the OBJ and the MTL file.
  106155. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  106156. *
  106157. * @param meshesNames
  106158. * @param scene BABYLON.Scene The scene where are displayed the data
  106159. * @param data String The content of the obj file
  106160. * @param rootUrl String The path to the folder
  106161. * @returns Array<AbstractMesh>
  106162. * @private
  106163. */
  106164. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  106165. var positions = []; //values for the positions of vertices
  106166. var normals = []; //Values for the normals
  106167. var uvs = []; //Values for the textures
  106168. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  106169. var handledMesh; //The current mesh of meshes array
  106170. var indicesForBabylon = []; //The list of indices for VertexData
  106171. var wrappedPositionForBabylon = []; //The list of position in vectors
  106172. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  106173. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  106174. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  106175. var curPositionInIndices = 0;
  106176. var hasMeshes = false; //Meshes are defined in the file
  106177. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  106178. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  106179. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  106180. var triangles = []; //Indices from new triangles coming from polygons
  106181. var materialNameFromObj = ""; //The name of the current material
  106182. var fileToLoad = ""; //The name of the mtlFile to load
  106183. var materialsFromMTLFile = new MTLFileLoader();
  106184. var objMeshName = ""; //The name of the current obj mesh
  106185. var increment = 1; //Id for meshes created by the multimaterial
  106186. var isFirstMaterial = true;
  106187. /**
  106188. * Search for obj in the given array.
  106189. * This function is called to check if a couple of data already exists in an array.
  106190. *
  106191. * If found, returns the index of the founded tuple index. Returns -1 if not found
  106192. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  106193. * @param obj Array<number>
  106194. * @returns {boolean}
  106195. */
  106196. var isInArray = function (arr, obj) {
  106197. if (!arr[obj[0]])
  106198. arr[obj[0]] = { normals: [], idx: [] };
  106199. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  106200. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  106201. };
  106202. var isInArrayUV = function (arr, obj) {
  106203. if (!arr[obj[0]])
  106204. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  106205. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  106206. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  106207. return arr[obj[0]].idx[idx];
  106208. }
  106209. return -1;
  106210. };
  106211. /**
  106212. * This function set the data for each triangle.
  106213. * Data are position, normals and uvs
  106214. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  106215. * If the tuple already exist, add only their indice
  106216. *
  106217. * @param indicePositionFromObj Integer The index in positions array
  106218. * @param indiceUvsFromObj Integer The index in uvs array
  106219. * @param indiceNormalFromObj Integer The index in normals array
  106220. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  106221. * @param textureVectorFromOBJ Vector3 The value of uvs
  106222. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  106223. */
  106224. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  106225. //Check if this tuple already exists in the list of tuples
  106226. var _index;
  106227. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  106228. _index = isInArrayUV(tuplePosNorm, [
  106229. indicePositionFromObj,
  106230. indiceNormalFromObj,
  106231. indiceUvsFromObj
  106232. ]);
  106233. }
  106234. else {
  106235. _index = isInArray(tuplePosNorm, [
  106236. indicePositionFromObj,
  106237. indiceNormalFromObj
  106238. ]);
  106239. }
  106240. //If it not exists
  106241. if (_index == -1) {
  106242. //Add an new indice.
  106243. //The array of indices is only an array with his length equal to the number of triangles - 1.
  106244. //We add vertices data in this order
  106245. indicesForBabylon.push(wrappedPositionForBabylon.length);
  106246. //Push the position of vertice for Babylon
  106247. //Each element is a BABYLON.Vector3(x,y,z)
  106248. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  106249. //Push the uvs for Babylon
  106250. //Each element is a BABYLON.Vector3(u,v)
  106251. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  106252. //Push the normals for Babylon
  106253. //Each element is a BABYLON.Vector3(x,y,z)
  106254. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  106255. //Add the tuple in the comparison list
  106256. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  106257. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  106258. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  106259. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  106260. }
  106261. else {
  106262. //The tuple already exists
  106263. //Add the index of the already existing tuple
  106264. //At this index we can get the value of position, normal and uvs of vertex
  106265. indicesForBabylon.push(_index);
  106266. }
  106267. };
  106268. /**
  106269. * Transform BABYLON.Vector() object onto 3 digits in an array
  106270. */
  106271. var unwrapData = function () {
  106272. //Every array has the same length
  106273. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  106274. //Push the x, y, z values of each element in the unwrapped array
  106275. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  106276. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  106277. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  106278. }
  106279. // Reset arrays for the next new meshes
  106280. wrappedPositionForBabylon = [];
  106281. wrappedNormalsForBabylon = [];
  106282. wrappedUvsForBabylon = [];
  106283. tuplePosNorm = [];
  106284. curPositionInIndices = 0;
  106285. };
  106286. /**
  106287. * Create triangles from polygons by recursion
  106288. * The best to understand how it works is to draw it in the same time you get the recursion.
  106289. * It is important to notice that a triangle is a polygon
  106290. * We get 4 patterns of face defined in OBJ File :
  106291. * facePattern1 = ["1","2","3","4","5","6"]
  106292. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  106293. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  106294. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  106295. * Each pattern is divided by the same method
  106296. * @param face Array[String] The indices of elements
  106297. * @param v Integer The variable to increment
  106298. */
  106299. var getTriangles = function (face, v) {
  106300. //Work for each element of the array
  106301. if (v + 1 < face.length) {
  106302. //Add on the triangle variable the indexes to obtain triangles
  106303. triangles.push(face[0], face[v], face[v + 1]);
  106304. //Incrementation for recursion
  106305. v += 1;
  106306. //Recursion
  106307. getTriangles(face, v);
  106308. }
  106309. //Result obtained after 2 iterations:
  106310. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  106311. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  106312. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  106313. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  106314. };
  106315. /**
  106316. * Create triangles and push the data for each polygon for the pattern 1
  106317. * In this pattern we get vertice positions
  106318. * @param face
  106319. * @param v
  106320. */
  106321. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  106322. //Get the indices of triangles for each polygon
  106323. getTriangles(face, v);
  106324. //For each element in the triangles array.
  106325. //This var could contains 1 to an infinity of triangles
  106326. for (var k = 0; k < triangles.length; k++) {
  106327. // Set position indice
  106328. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  106329. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  106330. positions[indicePositionFromObj], //Get the vectors data
  106331. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  106332. );
  106333. }
  106334. //Reset variable for the next line
  106335. triangles = [];
  106336. };
  106337. /**
  106338. * Create triangles and push the data for each polygon for the pattern 2
  106339. * In this pattern we get vertice positions and uvsu
  106340. * @param face
  106341. * @param v
  106342. */
  106343. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  106344. //Get the indices of triangles for each polygon
  106345. getTriangles(face, v);
  106346. for (var k = 0; k < triangles.length; k++) {
  106347. //triangle[k] = "1/1"
  106348. //Split the data for getting position and uv
  106349. var point = triangles[k].split("/"); // ["1", "1"]
  106350. //Set position indice
  106351. var indicePositionFromObj = parseInt(point[0]) - 1;
  106352. //Set uv indice
  106353. var indiceUvsFromObj = parseInt(point[1]) - 1;
  106354. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  106355. positions[indicePositionFromObj], //Get the values for each element
  106356. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  106357. );
  106358. }
  106359. //Reset variable for the next line
  106360. triangles = [];
  106361. };
  106362. /**
  106363. * Create triangles and push the data for each polygon for the pattern 3
  106364. * In this pattern we get vertice positions, uvs and normals
  106365. * @param face
  106366. * @param v
  106367. */
  106368. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  106369. //Get the indices of triangles for each polygon
  106370. getTriangles(face, v);
  106371. for (var k = 0; k < triangles.length; k++) {
  106372. //triangle[k] = "1/1/1"
  106373. //Split the data for getting position, uv, and normals
  106374. var point = triangles[k].split("/"); // ["1", "1", "1"]
  106375. // Set position indice
  106376. var indicePositionFromObj = parseInt(point[0]) - 1;
  106377. // Set uv indice
  106378. var indiceUvsFromObj = parseInt(point[1]) - 1;
  106379. // Set normal indice
  106380. var indiceNormalFromObj = parseInt(point[2]) - 1;
  106381. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  106382. );
  106383. }
  106384. //Reset variable for the next line
  106385. triangles = [];
  106386. };
  106387. /**
  106388. * Create triangles and push the data for each polygon for the pattern 4
  106389. * In this pattern we get vertice positions and normals
  106390. * @param face
  106391. * @param v
  106392. */
  106393. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  106394. getTriangles(face, v);
  106395. for (var k = 0; k < triangles.length; k++) {
  106396. //triangle[k] = "1//1"
  106397. //Split the data for getting position and normals
  106398. var point = triangles[k].split("//"); // ["1", "1"]
  106399. // We check indices, and normals
  106400. var indicePositionFromObj = parseInt(point[0]) - 1;
  106401. var indiceNormalFromObj = parseInt(point[1]) - 1;
  106402. setData(indicePositionFromObj, 1, //Default value for uv
  106403. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  106404. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  106405. }
  106406. //Reset variable for the next line
  106407. triangles = [];
  106408. };
  106409. var addPreviousObjMesh = function () {
  106410. //Check if it is not the first mesh. Otherwise we don't have data.
  106411. if (meshesFromObj.length > 0) {
  106412. //Get the previous mesh for applying the data about the faces
  106413. //=> in obj file, faces definition append after the name of the mesh
  106414. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  106415. //Set the data into Array for the mesh
  106416. unwrapData();
  106417. // Reverse tab. Otherwise face are displayed in the wrong sens
  106418. indicesForBabylon.reverse();
  106419. //Set the information for the mesh
  106420. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  106421. handledMesh.indices = indicesForBabylon.slice();
  106422. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  106423. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  106424. handledMesh.uvs = unwrappedUVForBabylon.slice();
  106425. //Reset the array for the next mesh
  106426. indicesForBabylon = [];
  106427. unwrappedPositionsForBabylon = [];
  106428. unwrappedNormalsForBabylon = [];
  106429. unwrappedUVForBabylon = [];
  106430. }
  106431. };
  106432. //Main function
  106433. //Split the file into lines
  106434. var lines = data.split('\n');
  106435. //Look at each line
  106436. for (var i = 0; i < lines.length; i++) {
  106437. var line = lines[i].trim();
  106438. var result;
  106439. //Comment or newLine
  106440. if (line.length === 0 || line.charAt(0) === '#') {
  106441. continue;
  106442. //Get information about one position possible for the vertices
  106443. }
  106444. else if ((result = this.vertexPattern.exec(line)) !== null) {
  106445. //Create a Vector3 with the position x, y, z
  106446. //Value of result:
  106447. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  106448. //Add the Vector in the list of positions
  106449. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  106450. }
  106451. else if ((result = this.normalPattern.exec(line)) !== null) {
  106452. //Create a Vector3 with the normals x, y, z
  106453. //Value of result
  106454. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  106455. //Add the Vector in the list of normals
  106456. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  106457. }
  106458. else if ((result = this.uvPattern.exec(line)) !== null) {
  106459. //Create a Vector2 with the normals u, v
  106460. //Value of result
  106461. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  106462. //Add the Vector in the list of uvs
  106463. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  106464. //Identify patterns of faces
  106465. //Face could be defined in different type of pattern
  106466. }
  106467. else if ((result = this.facePattern3.exec(line)) !== null) {
  106468. //Value of result:
  106469. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  106470. //Set the data for this face
  106471. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  106472. 1);
  106473. }
  106474. else if ((result = this.facePattern4.exec(line)) !== null) {
  106475. //Value of result:
  106476. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  106477. //Set the data for this face
  106478. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  106479. 1);
  106480. }
  106481. else if ((result = this.facePattern2.exec(line)) !== null) {
  106482. //Value of result:
  106483. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  106484. //Set the data for this face
  106485. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  106486. 1);
  106487. }
  106488. else if ((result = this.facePattern1.exec(line)) !== null) {
  106489. //Value of result
  106490. //["f 1 2 3", "1 2 3"...]
  106491. //Set the data for this face
  106492. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  106493. 1);
  106494. //Define a mesh or an object
  106495. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  106496. }
  106497. else if (this.group.test(line) || this.obj.test(line)) {
  106498. //Create a new mesh corresponding to the name of the group.
  106499. //Definition of the mesh
  106500. var objMesh =
  106501. //Set the name of the current obj mesh
  106502. {
  106503. name: line.substring(2).trim(),
  106504. indices: undefined,
  106505. positions: undefined,
  106506. normals: undefined,
  106507. uvs: undefined,
  106508. materialName: ""
  106509. };
  106510. addPreviousObjMesh();
  106511. //Push the last mesh created with only the name
  106512. meshesFromObj.push(objMesh);
  106513. //Set this variable to indicate that now meshesFromObj has objects defined inside
  106514. hasMeshes = true;
  106515. isFirstMaterial = true;
  106516. increment = 1;
  106517. //Keyword for applying a material
  106518. }
  106519. else if (this.usemtl.test(line)) {
  106520. //Get the name of the material
  106521. materialNameFromObj = line.substring(7).trim();
  106522. //If this new material is in the same mesh
  106523. if (!isFirstMaterial) {
  106524. //Set the data for the previous mesh
  106525. addPreviousObjMesh();
  106526. //Create a new mesh
  106527. var objMesh =
  106528. //Set the name of the current obj mesh
  106529. {
  106530. name: objMeshName + "_mm" + increment.toString(),
  106531. indices: undefined,
  106532. positions: undefined,
  106533. normals: undefined,
  106534. uvs: undefined,
  106535. materialName: materialNameFromObj
  106536. };
  106537. increment++;
  106538. //If meshes are already defined
  106539. meshesFromObj.push(objMesh);
  106540. }
  106541. //Set the material name if the previous line define a mesh
  106542. if (hasMeshes && isFirstMaterial) {
  106543. //Set the material name to the previous mesh (1 material per mesh)
  106544. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  106545. isFirstMaterial = false;
  106546. }
  106547. //Keyword for loading the mtl file
  106548. }
  106549. else if (this.mtllib.test(line)) {
  106550. //Get the name of mtl file
  106551. fileToLoad = line.substring(7).trim();
  106552. //Apply smoothing
  106553. }
  106554. else if (this.smooth.test(line)) {
  106555. // smooth shading => apply smoothing
  106556. //Toda y I don't know it work with babylon and with obj.
  106557. //With the obj file an integer is set
  106558. }
  106559. else {
  106560. //If there is another possibility
  106561. console.log("Unhandled expression at line : " + line);
  106562. }
  106563. }
  106564. //At the end of the file, add the last mesh into the meshesFromObj array
  106565. if (hasMeshes) {
  106566. //Set the data for the last mesh
  106567. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  106568. //Reverse indices for displaying faces in the good sens
  106569. indicesForBabylon.reverse();
  106570. //Get the good array
  106571. unwrapData();
  106572. //Set array
  106573. handledMesh.indices = indicesForBabylon;
  106574. handledMesh.positions = unwrappedPositionsForBabylon;
  106575. handledMesh.normals = unwrappedNormalsForBabylon;
  106576. handledMesh.uvs = unwrappedUVForBabylon;
  106577. }
  106578. //If any o or g keyword found, create a mesj with a random id
  106579. if (!hasMeshes) {
  106580. // reverse tab of indices
  106581. indicesForBabylon.reverse();
  106582. //Get positions normals uvs
  106583. unwrapData();
  106584. //Set data for one mesh
  106585. meshesFromObj.push({
  106586. name: BABYLON.Geometry.RandomId(),
  106587. indices: indicesForBabylon,
  106588. positions: unwrappedPositionsForBabylon,
  106589. normals: unwrappedNormalsForBabylon,
  106590. uvs: unwrappedUVForBabylon,
  106591. materialName: materialNameFromObj
  106592. });
  106593. }
  106594. //Create a BABYLON.Mesh list
  106595. var babylonMeshesArray = []; //The mesh for babylon
  106596. var materialToUse = new Array();
  106597. //Set data for each mesh
  106598. for (var j = 0; j < meshesFromObj.length; j++) {
  106599. //check meshesNames (stlFileLoader)
  106600. if (meshesNames && meshesFromObj[j].name) {
  106601. if (meshesNames instanceof Array) {
  106602. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  106603. continue;
  106604. }
  106605. }
  106606. else {
  106607. if (meshesFromObj[j].name !== meshesNames) {
  106608. continue;
  106609. }
  106610. }
  106611. }
  106612. //Get the current mesh
  106613. //Set the data with VertexBuffer for each mesh
  106614. handledMesh = meshesFromObj[j];
  106615. //Create a BABYLON.Mesh with the name of the obj mesh
  106616. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  106617. //Push the name of the material to an array
  106618. //This is indispensable for the importMesh function
  106619. materialToUse.push(meshesFromObj[j].materialName);
  106620. var vertexData = new BABYLON.VertexData(); //The container for the values
  106621. //Set the data for the babylonMesh
  106622. vertexData.positions = handledMesh.positions;
  106623. vertexData.normals = handledMesh.normals;
  106624. vertexData.uvs = handledMesh.uvs;
  106625. vertexData.indices = handledMesh.indices;
  106626. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  106627. vertexData.applyToMesh(babylonMesh);
  106628. //Push the mesh into an array
  106629. babylonMeshesArray.push(babylonMesh);
  106630. }
  106631. //load the materials
  106632. //Check if we have a file to load
  106633. if (fileToLoad !== "") {
  106634. //Load the file synchronously
  106635. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  106636. //Create materials thanks MTLLoader function
  106637. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  106638. //Look at each material loaded in the mtl file
  106639. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  106640. //Three variables to get all meshes with the same material
  106641. var startIndex = 0;
  106642. var _indices = [];
  106643. var _index;
  106644. //The material from MTL file is used in the meshes loaded
  106645. //Push the indice in an array
  106646. //Check if the material is not used for another mesh
  106647. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  106648. _indices.push(_index);
  106649. startIndex = _index + 1;
  106650. }
  106651. //If the material is not used dispose it
  106652. if (_index == -1 && _indices.length == 0) {
  106653. //If the material is not needed, remove it
  106654. materialsFromMTLFile.materials[n].dispose();
  106655. }
  106656. else {
  106657. for (var o = 0; o < _indices.length; o++) {
  106658. //Apply the material to the BABYLON.Mesh for each mesh with the material
  106659. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  106660. }
  106661. }
  106662. }
  106663. });
  106664. }
  106665. //Return an array with all BABYLON.Mesh
  106666. return babylonMeshesArray;
  106667. };
  106668. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  106669. return OBJFileLoader;
  106670. }());
  106671. BABYLON.OBJFileLoader = OBJFileLoader;
  106672. if (BABYLON.SceneLoader) {
  106673. //Add this loader into the register plugin
  106674. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  106675. }
  106676. })(BABYLON || (BABYLON = {}));
  106677. //# sourceMappingURL=babylon.objFileLoader.js.map
  106678. "use strict";
  106679. var BABYLON;
  106680. (function (BABYLON) {
  106681. var GLTFLoaderCoordinateSystemMode;
  106682. (function (GLTFLoaderCoordinateSystemMode) {
  106683. /**
  106684. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  106685. */
  106686. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  106687. /**
  106688. * Sets the useRightHandedSystem flag on the scene.
  106689. */
  106690. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  106691. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  106692. var GLTFLoaderAnimationStartMode;
  106693. (function (GLTFLoaderAnimationStartMode) {
  106694. /**
  106695. * No animation will start.
  106696. */
  106697. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  106698. /**
  106699. * The first animation will start.
  106700. */
  106701. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  106702. /**
  106703. * All animations will start.
  106704. */
  106705. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  106706. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  106707. var GLTFLoaderState;
  106708. (function (GLTFLoaderState) {
  106709. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  106710. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  106711. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  106712. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  106713. var GLTFFileLoader = /** @class */ (function () {
  106714. function GLTFFileLoader() {
  106715. // #region Common options
  106716. /**
  106717. * Raised when the asset has been parsed.
  106718. * The data.json property stores the glTF JSON.
  106719. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  106720. */
  106721. this.onParsedObservable = new BABYLON.Observable();
  106722. // #endregion
  106723. // #region V2 options
  106724. /**
  106725. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  106726. */
  106727. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  106728. /**
  106729. * The animation start mode (NONE, FIRST, ALL).
  106730. */
  106731. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  106732. /**
  106733. * Set to true to compile materials before raising the success callback.
  106734. */
  106735. this.compileMaterials = false;
  106736. /**
  106737. * Set to true to also compile materials with clip planes.
  106738. */
  106739. this.useClipPlane = false;
  106740. /**
  106741. * Set to true to compile shadow generators before raising the success callback.
  106742. */
  106743. this.compileShadowGenerators = false;
  106744. /**
  106745. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  106746. */
  106747. this.onMeshLoadedObservable = new BABYLON.Observable();
  106748. /**
  106749. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  106750. */
  106751. this.onTextureLoadedObservable = new BABYLON.Observable();
  106752. /**
  106753. * Raised when the loader creates a material after parsing the glTF properties of the material.
  106754. */
  106755. this.onMaterialLoadedObservable = new BABYLON.Observable();
  106756. /**
  106757. * Raised when the loader creates an animation group after parsing the glTF properties of the animation.
  106758. */
  106759. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  106760. /**
  106761. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  106762. * For assets with LODs, raised when all of the LODs are complete.
  106763. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  106764. */
  106765. this.onCompleteObservable = new BABYLON.Observable();
  106766. /**
  106767. * Raised when the loader is disposed.
  106768. */
  106769. this.onDisposeObservable = new BABYLON.Observable();
  106770. /**
  106771. * Raised after a loader extension is created.
  106772. * Set additional options for a loader extension in this event.
  106773. */
  106774. this.onExtensionLoadedObservable = new BABYLON.Observable();
  106775. // #endregion
  106776. this._loader = null;
  106777. this.name = "gltf";
  106778. this.extensions = {
  106779. ".gltf": { isBinary: false },
  106780. ".glb": { isBinary: true }
  106781. };
  106782. }
  106783. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  106784. set: function (callback) {
  106785. if (this._onParsedObserver) {
  106786. this.onParsedObservable.remove(this._onParsedObserver);
  106787. }
  106788. this._onParsedObserver = this.onParsedObservable.add(callback);
  106789. },
  106790. enumerable: true,
  106791. configurable: true
  106792. });
  106793. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  106794. set: function (callback) {
  106795. if (this._onMeshLoadedObserver) {
  106796. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  106797. }
  106798. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  106799. },
  106800. enumerable: true,
  106801. configurable: true
  106802. });
  106803. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  106804. set: function (callback) {
  106805. if (this._onTextureLoadedObserver) {
  106806. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  106807. }
  106808. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  106809. },
  106810. enumerable: true,
  106811. configurable: true
  106812. });
  106813. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  106814. set: function (callback) {
  106815. if (this._onMaterialLoadedObserver) {
  106816. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  106817. }
  106818. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  106819. },
  106820. enumerable: true,
  106821. configurable: true
  106822. });
  106823. Object.defineProperty(GLTFFileLoader.prototype, "onAnimationGroupLoaded", {
  106824. set: function (callback) {
  106825. if (this._onAnimationGroupLoadedObserver) {
  106826. this.onAnimationGroupLoadedObservable.remove(this._onAnimationGroupLoadedObserver);
  106827. }
  106828. this._onAnimationGroupLoadedObserver = this.onAnimationGroupLoadedObservable.add(callback);
  106829. },
  106830. enumerable: true,
  106831. configurable: true
  106832. });
  106833. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  106834. set: function (callback) {
  106835. if (this._onCompleteObserver) {
  106836. this.onCompleteObservable.remove(this._onCompleteObserver);
  106837. }
  106838. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  106839. },
  106840. enumerable: true,
  106841. configurable: true
  106842. });
  106843. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  106844. set: function (callback) {
  106845. if (this._onDisposeObserver) {
  106846. this.onDisposeObservable.remove(this._onDisposeObserver);
  106847. }
  106848. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  106849. },
  106850. enumerable: true,
  106851. configurable: true
  106852. });
  106853. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  106854. set: function (callback) {
  106855. if (this._onExtensionLoadedObserver) {
  106856. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  106857. }
  106858. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  106859. },
  106860. enumerable: true,
  106861. configurable: true
  106862. });
  106863. /**
  106864. * Gets a promise that resolves when the asset is completely loaded.
  106865. * @returns A promise that resolves when the asset is completely loaded.
  106866. */
  106867. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  106868. var _this = this;
  106869. return new Promise(function (resolve) {
  106870. _this.onCompleteObservable.add(function () {
  106871. resolve();
  106872. }, undefined, undefined, undefined, true);
  106873. });
  106874. };
  106875. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  106876. /**
  106877. * The loader state or null if not active.
  106878. */
  106879. get: function () {
  106880. return this._loader ? this._loader.state : null;
  106881. },
  106882. enumerable: true,
  106883. configurable: true
  106884. });
  106885. /**
  106886. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  106887. */
  106888. GLTFFileLoader.prototype.dispose = function () {
  106889. if (this._loader) {
  106890. this._loader.dispose();
  106891. this._loader = null;
  106892. }
  106893. this.onMeshLoadedObservable.clear();
  106894. this.onTextureLoadedObservable.clear();
  106895. this.onMaterialLoadedObservable.clear();
  106896. this.onDisposeObservable.notifyObservers(this);
  106897. this.onDisposeObservable.clear();
  106898. };
  106899. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  106900. var _this = this;
  106901. return Promise.resolve().then(function () {
  106902. var loaderData = _this._parse(data);
  106903. _this._loader = _this._getLoader(loaderData);
  106904. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  106905. });
  106906. };
  106907. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  106908. var _this = this;
  106909. return Promise.resolve().then(function () {
  106910. var loaderData = _this._parse(data);
  106911. _this._loader = _this._getLoader(loaderData);
  106912. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  106913. });
  106914. };
  106915. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  106916. var _this = this;
  106917. return Promise.resolve().then(function () {
  106918. var loaderData = _this._parse(data);
  106919. _this._loader = _this._getLoader(loaderData);
  106920. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  106921. var container = new BABYLON.AssetContainer(scene);
  106922. Array.prototype.push.apply(container.meshes, result.meshes);
  106923. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  106924. Array.prototype.push.apply(container.skeletons, result.skeletons);
  106925. container.removeAllFromScene();
  106926. return container;
  106927. });
  106928. });
  106929. };
  106930. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  106931. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  106932. };
  106933. GLTFFileLoader.prototype.createPlugin = function () {
  106934. return new GLTFFileLoader();
  106935. };
  106936. GLTFFileLoader.prototype._parse = function (data) {
  106937. var parsedData;
  106938. if (data instanceof ArrayBuffer) {
  106939. parsedData = GLTFFileLoader._parseBinary(data);
  106940. }
  106941. else {
  106942. parsedData = {
  106943. json: JSON.parse(data),
  106944. bin: null
  106945. };
  106946. }
  106947. this.onParsedObservable.notifyObservers(parsedData);
  106948. this.onParsedObservable.clear();
  106949. return parsedData;
  106950. };
  106951. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  106952. var _this = this;
  106953. var loaderVersion = { major: 2, minor: 0 };
  106954. var asset = loaderData.json.asset || {};
  106955. var version = GLTFFileLoader._parseVersion(asset.version);
  106956. if (!version) {
  106957. throw new Error("Invalid version: " + asset.version);
  106958. }
  106959. if (asset.minVersion !== undefined) {
  106960. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  106961. if (!minVersion) {
  106962. throw new Error("Invalid minimum version: " + asset.minVersion);
  106963. }
  106964. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  106965. throw new Error("Incompatible minimum version: " + asset.minVersion);
  106966. }
  106967. }
  106968. var createLoaders = {
  106969. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  106970. 2: GLTFFileLoader.CreateGLTFLoaderV2
  106971. };
  106972. var createLoader = createLoaders[version.major];
  106973. if (!createLoader) {
  106974. throw new Error("Unsupported version: " + asset.version);
  106975. }
  106976. var loader = createLoader();
  106977. loader.coordinateSystemMode = this.coordinateSystemMode;
  106978. loader.animationStartMode = this.animationStartMode;
  106979. loader.compileMaterials = this.compileMaterials;
  106980. loader.useClipPlane = this.useClipPlane;
  106981. loader.compileShadowGenerators = this.compileShadowGenerators;
  106982. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  106983. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  106984. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  106985. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  106986. loader.onCompleteObservable.add(function () {
  106987. _this.onMeshLoadedObservable.clear();
  106988. _this.onTextureLoadedObservable.clear();
  106989. _this.onMaterialLoadedObservable.clear();
  106990. _this.onCompleteObservable.notifyObservers(_this);
  106991. _this.onCompleteObservable.clear();
  106992. });
  106993. return loader;
  106994. };
  106995. GLTFFileLoader._parseBinary = function (data) {
  106996. var Binary = {
  106997. Magic: 0x46546C67
  106998. };
  106999. var binaryReader = new BinaryReader(data);
  107000. var magic = binaryReader.readUint32();
  107001. if (magic !== Binary.Magic) {
  107002. throw new Error("Unexpected magic: " + magic);
  107003. }
  107004. var version = binaryReader.readUint32();
  107005. switch (version) {
  107006. case 1: return GLTFFileLoader._parseV1(binaryReader);
  107007. case 2: return GLTFFileLoader._parseV2(binaryReader);
  107008. }
  107009. throw new Error("Unsupported version: " + version);
  107010. };
  107011. GLTFFileLoader._parseV1 = function (binaryReader) {
  107012. var ContentFormat = {
  107013. JSON: 0
  107014. };
  107015. var length = binaryReader.readUint32();
  107016. if (length != binaryReader.getLength()) {
  107017. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  107018. }
  107019. var contentLength = binaryReader.readUint32();
  107020. var contentFormat = binaryReader.readUint32();
  107021. var content;
  107022. switch (contentFormat) {
  107023. case ContentFormat.JSON: {
  107024. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  107025. break;
  107026. }
  107027. default: {
  107028. throw new Error("Unexpected content format: " + contentFormat);
  107029. }
  107030. }
  107031. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  107032. var body = binaryReader.readUint8Array(bytesRemaining);
  107033. return {
  107034. json: content,
  107035. bin: body
  107036. };
  107037. };
  107038. GLTFFileLoader._parseV2 = function (binaryReader) {
  107039. var ChunkFormat = {
  107040. JSON: 0x4E4F534A,
  107041. BIN: 0x004E4942
  107042. };
  107043. var length = binaryReader.readUint32();
  107044. if (length !== binaryReader.getLength()) {
  107045. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  107046. }
  107047. // JSON chunk
  107048. var chunkLength = binaryReader.readUint32();
  107049. var chunkFormat = binaryReader.readUint32();
  107050. if (chunkFormat !== ChunkFormat.JSON) {
  107051. throw new Error("First chunk format is not JSON");
  107052. }
  107053. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  107054. // Look for BIN chunk
  107055. var bin = null;
  107056. while (binaryReader.getPosition() < binaryReader.getLength()) {
  107057. var chunkLength_1 = binaryReader.readUint32();
  107058. var chunkFormat_1 = binaryReader.readUint32();
  107059. switch (chunkFormat_1) {
  107060. case ChunkFormat.JSON: {
  107061. throw new Error("Unexpected JSON chunk");
  107062. }
  107063. case ChunkFormat.BIN: {
  107064. bin = binaryReader.readUint8Array(chunkLength_1);
  107065. break;
  107066. }
  107067. default: {
  107068. // ignore unrecognized chunkFormat
  107069. binaryReader.skipBytes(chunkLength_1);
  107070. break;
  107071. }
  107072. }
  107073. }
  107074. return {
  107075. json: json,
  107076. bin: bin
  107077. };
  107078. };
  107079. GLTFFileLoader._parseVersion = function (version) {
  107080. if (version === "1.0" || version === "1.0.1") {
  107081. return {
  107082. major: 1,
  107083. minor: 0
  107084. };
  107085. }
  107086. var match = (version + "").match(/^(\d+)\.(\d+)/);
  107087. if (!match) {
  107088. return null;
  107089. }
  107090. return {
  107091. major: parseInt(match[1]),
  107092. minor: parseInt(match[2])
  107093. };
  107094. };
  107095. GLTFFileLoader._compareVersion = function (a, b) {
  107096. if (a.major > b.major)
  107097. return 1;
  107098. if (a.major < b.major)
  107099. return -1;
  107100. if (a.minor > b.minor)
  107101. return 1;
  107102. if (a.minor < b.minor)
  107103. return -1;
  107104. return 0;
  107105. };
  107106. GLTFFileLoader._decodeBufferToText = function (buffer) {
  107107. var result = "";
  107108. var length = buffer.byteLength;
  107109. for (var i = 0; i < length; i++) {
  107110. result += String.fromCharCode(buffer[i]);
  107111. }
  107112. return result;
  107113. };
  107114. // #endregion
  107115. // #region V1 options
  107116. GLTFFileLoader.IncrementalLoading = true;
  107117. GLTFFileLoader.HomogeneousCoordinates = false;
  107118. return GLTFFileLoader;
  107119. }());
  107120. BABYLON.GLTFFileLoader = GLTFFileLoader;
  107121. var BinaryReader = /** @class */ (function () {
  107122. function BinaryReader(arrayBuffer) {
  107123. this._arrayBuffer = arrayBuffer;
  107124. this._dataView = new DataView(arrayBuffer);
  107125. this._byteOffset = 0;
  107126. }
  107127. BinaryReader.prototype.getPosition = function () {
  107128. return this._byteOffset;
  107129. };
  107130. BinaryReader.prototype.getLength = function () {
  107131. return this._arrayBuffer.byteLength;
  107132. };
  107133. BinaryReader.prototype.readUint32 = function () {
  107134. var value = this._dataView.getUint32(this._byteOffset, true);
  107135. this._byteOffset += 4;
  107136. return value;
  107137. };
  107138. BinaryReader.prototype.readUint8Array = function (length) {
  107139. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  107140. this._byteOffset += length;
  107141. return value;
  107142. };
  107143. BinaryReader.prototype.skipBytes = function (length) {
  107144. this._byteOffset += length;
  107145. };
  107146. return BinaryReader;
  107147. }());
  107148. if (BABYLON.SceneLoader) {
  107149. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  107150. }
  107151. })(BABYLON || (BABYLON = {}));
  107152. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  107153. "use strict";
  107154. var BABYLON;
  107155. (function (BABYLON) {
  107156. var GLTF1;
  107157. (function (GLTF1) {
  107158. /**
  107159. * Enums
  107160. */
  107161. var EComponentType;
  107162. (function (EComponentType) {
  107163. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  107164. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  107165. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  107166. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  107167. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  107168. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  107169. var EShaderType;
  107170. (function (EShaderType) {
  107171. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  107172. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  107173. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  107174. var EParameterType;
  107175. (function (EParameterType) {
  107176. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  107177. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  107178. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  107179. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  107180. EParameterType[EParameterType["INT"] = 5124] = "INT";
  107181. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  107182. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  107183. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  107184. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  107185. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  107186. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  107187. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  107188. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  107189. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  107190. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  107191. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  107192. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  107193. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  107194. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  107195. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  107196. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  107197. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  107198. var ETextureWrapMode;
  107199. (function (ETextureWrapMode) {
  107200. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  107201. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  107202. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  107203. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  107204. var ETextureFilterType;
  107205. (function (ETextureFilterType) {
  107206. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  107207. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  107208. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  107209. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  107210. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  107211. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  107212. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  107213. var ETextureFormat;
  107214. (function (ETextureFormat) {
  107215. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  107216. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  107217. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  107218. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  107219. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  107220. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  107221. var ECullingType;
  107222. (function (ECullingType) {
  107223. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  107224. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  107225. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  107226. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  107227. var EBlendingFunction;
  107228. (function (EBlendingFunction) {
  107229. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  107230. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  107231. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  107232. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  107233. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  107234. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  107235. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  107236. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  107237. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  107238. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  107239. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  107240. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  107241. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  107242. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  107243. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  107244. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  107245. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  107246. })(BABYLON || (BABYLON = {}));
  107247. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  107248. "use strict";
  107249. var BABYLON;
  107250. (function (BABYLON) {
  107251. var GLTF1;
  107252. (function (GLTF1) {
  107253. /**
  107254. * Tokenizer. Used for shaders compatibility
  107255. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  107256. */
  107257. var ETokenType;
  107258. (function (ETokenType) {
  107259. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  107260. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  107261. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  107262. })(ETokenType || (ETokenType = {}));
  107263. var Tokenizer = /** @class */ (function () {
  107264. function Tokenizer(toParse) {
  107265. this._pos = 0;
  107266. this.currentToken = ETokenType.UNKNOWN;
  107267. this.currentIdentifier = "";
  107268. this.currentString = "";
  107269. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  107270. this._toParse = toParse;
  107271. this._maxPos = toParse.length;
  107272. }
  107273. Tokenizer.prototype.getNextToken = function () {
  107274. if (this.isEnd())
  107275. return ETokenType.END_OF_INPUT;
  107276. this.currentString = this.read();
  107277. this.currentToken = ETokenType.UNKNOWN;
  107278. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  107279. this.currentToken = ETokenType.IDENTIFIER;
  107280. this.currentIdentifier = this.currentString;
  107281. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  107282. this.currentIdentifier += this.currentString;
  107283. this.forward();
  107284. }
  107285. }
  107286. return this.currentToken;
  107287. };
  107288. Tokenizer.prototype.peek = function () {
  107289. return this._toParse[this._pos];
  107290. };
  107291. Tokenizer.prototype.read = function () {
  107292. return this._toParse[this._pos++];
  107293. };
  107294. Tokenizer.prototype.forward = function () {
  107295. this._pos++;
  107296. };
  107297. Tokenizer.prototype.isEnd = function () {
  107298. return this._pos >= this._maxPos;
  107299. };
  107300. return Tokenizer;
  107301. }());
  107302. /**
  107303. * Values
  107304. */
  107305. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  107306. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  107307. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  107308. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  107309. /**
  107310. * Parse
  107311. */
  107312. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  107313. for (var buf in parsedBuffers) {
  107314. var parsedBuffer = parsedBuffers[buf];
  107315. gltfRuntime.buffers[buf] = parsedBuffer;
  107316. gltfRuntime.buffersCount++;
  107317. }
  107318. };
  107319. var parseShaders = function (parsedShaders, gltfRuntime) {
  107320. for (var sha in parsedShaders) {
  107321. var parsedShader = parsedShaders[sha];
  107322. gltfRuntime.shaders[sha] = parsedShader;
  107323. gltfRuntime.shaderscount++;
  107324. }
  107325. };
  107326. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  107327. for (var object in parsedObjects) {
  107328. var parsedObject = parsedObjects[object];
  107329. gltfRuntime[runtimeProperty][object] = parsedObject;
  107330. }
  107331. };
  107332. /**
  107333. * Utils
  107334. */
  107335. var normalizeUVs = function (buffer) {
  107336. if (!buffer) {
  107337. return;
  107338. }
  107339. for (var i = 0; i < buffer.length / 2; i++) {
  107340. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  107341. }
  107342. };
  107343. var getAttribute = function (attributeParameter) {
  107344. if (attributeParameter.semantic === "NORMAL") {
  107345. return "normal";
  107346. }
  107347. else if (attributeParameter.semantic === "POSITION") {
  107348. return "position";
  107349. }
  107350. else if (attributeParameter.semantic === "JOINT") {
  107351. return "matricesIndices";
  107352. }
  107353. else if (attributeParameter.semantic === "WEIGHT") {
  107354. return "matricesWeights";
  107355. }
  107356. else if (attributeParameter.semantic === "COLOR") {
  107357. return "color";
  107358. }
  107359. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  107360. var channel = Number(attributeParameter.semantic.split("_")[1]);
  107361. return "uv" + (channel === 0 ? "" : channel + 1);
  107362. }
  107363. return null;
  107364. };
  107365. /**
  107366. * Loads and creates animations
  107367. */
  107368. var loadAnimations = function (gltfRuntime) {
  107369. for (var anim in gltfRuntime.animations) {
  107370. var animation = gltfRuntime.animations[anim];
  107371. if (!animation.channels || !animation.samplers) {
  107372. continue;
  107373. }
  107374. var lastAnimation = null;
  107375. for (var i = 0; i < animation.channels.length; i++) {
  107376. // Get parameters and load buffers
  107377. var channel = animation.channels[i];
  107378. var sampler = animation.samplers[channel.sampler];
  107379. if (!sampler) {
  107380. continue;
  107381. }
  107382. var inputData = null;
  107383. var outputData = null;
  107384. if (animation.parameters) {
  107385. inputData = animation.parameters[sampler.input];
  107386. outputData = animation.parameters[sampler.output];
  107387. }
  107388. else {
  107389. inputData = sampler.input;
  107390. outputData = sampler.output;
  107391. }
  107392. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  107393. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  107394. var targetID = channel.target.id;
  107395. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  107396. if (targetNode === null) {
  107397. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  107398. }
  107399. if (targetNode === null) {
  107400. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  107401. continue;
  107402. }
  107403. var isBone = targetNode instanceof BABYLON.Bone;
  107404. // Get target path (position, rotation or scaling)
  107405. var targetPath = channel.target.path;
  107406. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  107407. if (targetPathIndex !== -1) {
  107408. targetPath = babylonAnimationPaths[targetPathIndex];
  107409. }
  107410. // Determine animation type
  107411. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  107412. if (!isBone) {
  107413. if (targetPath === "rotationQuaternion") {
  107414. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  107415. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  107416. }
  107417. else {
  107418. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  107419. }
  107420. }
  107421. // Create animation and key frames
  107422. var babylonAnimation = null;
  107423. var keys = [];
  107424. var arrayOffset = 0;
  107425. var modifyKey = false;
  107426. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  107427. babylonAnimation = lastAnimation;
  107428. modifyKey = true;
  107429. }
  107430. if (!modifyKey) {
  107431. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  107432. }
  107433. // For each frame
  107434. for (var j = 0; j < bufferInput.length; j++) {
  107435. var value = null;
  107436. if (targetPath === "rotationQuaternion") {
  107437. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  107438. arrayOffset += 4;
  107439. }
  107440. else {
  107441. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  107442. arrayOffset += 3;
  107443. }
  107444. if (isBone) {
  107445. var bone = targetNode;
  107446. var translation = BABYLON.Vector3.Zero();
  107447. var rotationQuaternion = new BABYLON.Quaternion();
  107448. var scaling = BABYLON.Vector3.Zero();
  107449. // Warning on decompose
  107450. var mat = bone.getBaseMatrix();
  107451. if (modifyKey && lastAnimation) {
  107452. mat = lastAnimation.getKeys()[j].value;
  107453. }
  107454. mat.decompose(scaling, rotationQuaternion, translation);
  107455. if (targetPath === "position") {
  107456. translation = value;
  107457. }
  107458. else if (targetPath === "rotationQuaternion") {
  107459. rotationQuaternion = value;
  107460. }
  107461. else {
  107462. scaling = value;
  107463. }
  107464. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  107465. }
  107466. if (!modifyKey) {
  107467. keys.push({
  107468. frame: bufferInput[j],
  107469. value: value
  107470. });
  107471. }
  107472. else if (lastAnimation) {
  107473. lastAnimation.getKeys()[j].value = value;
  107474. }
  107475. }
  107476. // Finish
  107477. if (!modifyKey && babylonAnimation) {
  107478. babylonAnimation.setKeys(keys);
  107479. targetNode.animations.push(babylonAnimation);
  107480. }
  107481. lastAnimation = babylonAnimation;
  107482. gltfRuntime.scene.stopAnimation(targetNode);
  107483. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  107484. }
  107485. }
  107486. };
  107487. /**
  107488. * Returns the bones transformation matrix
  107489. */
  107490. var configureBoneTransformation = function (node) {
  107491. var mat = null;
  107492. if (node.translation || node.rotation || node.scale) {
  107493. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  107494. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  107495. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  107496. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  107497. }
  107498. else {
  107499. mat = BABYLON.Matrix.FromArray(node.matrix);
  107500. }
  107501. return mat;
  107502. };
  107503. /**
  107504. * Returns the parent bone
  107505. */
  107506. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  107507. // Try to find
  107508. for (var i = 0; i < newSkeleton.bones.length; i++) {
  107509. if (newSkeleton.bones[i].name === jointName) {
  107510. return newSkeleton.bones[i];
  107511. }
  107512. }
  107513. // Not found, search in gltf nodes
  107514. var nodes = gltfRuntime.nodes;
  107515. for (var nde in nodes) {
  107516. var node = nodes[nde];
  107517. if (!node.jointName) {
  107518. continue;
  107519. }
  107520. var children = node.children;
  107521. for (var i = 0; i < children.length; i++) {
  107522. var child = gltfRuntime.nodes[children[i]];
  107523. if (!child.jointName) {
  107524. continue;
  107525. }
  107526. if (child.jointName === jointName) {
  107527. var mat = configureBoneTransformation(node);
  107528. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  107529. bone.id = nde;
  107530. return bone;
  107531. }
  107532. }
  107533. }
  107534. return null;
  107535. };
  107536. /**
  107537. * Returns the appropriate root node
  107538. */
  107539. var getNodeToRoot = function (nodesToRoot, id) {
  107540. for (var i = 0; i < nodesToRoot.length; i++) {
  107541. var nodeToRoot = nodesToRoot[i];
  107542. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  107543. var child = nodeToRoot.node.children[j];
  107544. if (child === id) {
  107545. return nodeToRoot.bone;
  107546. }
  107547. }
  107548. }
  107549. return null;
  107550. };
  107551. /**
  107552. * Returns the node with the joint name
  107553. */
  107554. var getJointNode = function (gltfRuntime, jointName) {
  107555. var nodes = gltfRuntime.nodes;
  107556. var node = nodes[jointName];
  107557. if (node) {
  107558. return {
  107559. node: node,
  107560. id: jointName
  107561. };
  107562. }
  107563. for (var nde in nodes) {
  107564. node = nodes[nde];
  107565. if (node.jointName === jointName) {
  107566. return {
  107567. node: node,
  107568. id: nde
  107569. };
  107570. }
  107571. }
  107572. return null;
  107573. };
  107574. /**
  107575. * Checks if a nodes is in joints
  107576. */
  107577. var nodeIsInJoints = function (skins, id) {
  107578. for (var i = 0; i < skins.jointNames.length; i++) {
  107579. if (skins.jointNames[i] === id) {
  107580. return true;
  107581. }
  107582. }
  107583. return false;
  107584. };
  107585. /**
  107586. * Fills the nodes to root for bones and builds hierarchy
  107587. */
  107588. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  107589. // Creates nodes for root
  107590. for (var nde in gltfRuntime.nodes) {
  107591. var node = gltfRuntime.nodes[nde];
  107592. var id = nde;
  107593. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  107594. continue;
  107595. }
  107596. // Create node to root bone
  107597. var mat = configureBoneTransformation(node);
  107598. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  107599. bone.id = id;
  107600. nodesToRoot.push({ bone: bone, node: node, id: id });
  107601. }
  107602. // Parenting
  107603. for (var i = 0; i < nodesToRoot.length; i++) {
  107604. var nodeToRoot = nodesToRoot[i];
  107605. var children = nodeToRoot.node.children;
  107606. for (var j = 0; j < children.length; j++) {
  107607. var child = null;
  107608. for (var k = 0; k < nodesToRoot.length; k++) {
  107609. if (nodesToRoot[k].id === children[j]) {
  107610. child = nodesToRoot[k];
  107611. break;
  107612. }
  107613. }
  107614. if (child) {
  107615. child.bone._parent = nodeToRoot.bone;
  107616. nodeToRoot.bone.children.push(child.bone);
  107617. }
  107618. }
  107619. }
  107620. };
  107621. /**
  107622. * Imports a skeleton
  107623. */
  107624. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  107625. if (!newSkeleton) {
  107626. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  107627. }
  107628. if (!skins.babylonSkeleton) {
  107629. return newSkeleton;
  107630. }
  107631. // Find the root bones
  107632. var nodesToRoot = [];
  107633. var nodesToRootToAdd = [];
  107634. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  107635. newSkeleton.bones = [];
  107636. // Joints
  107637. for (var i = 0; i < skins.jointNames.length; i++) {
  107638. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  107639. if (!jointNode) {
  107640. continue;
  107641. }
  107642. var node = jointNode.node;
  107643. if (!node) {
  107644. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  107645. continue;
  107646. }
  107647. var id = jointNode.id;
  107648. // Optimize, if the bone already exists...
  107649. var existingBone = gltfRuntime.scene.getBoneByID(id);
  107650. if (existingBone) {
  107651. newSkeleton.bones.push(existingBone);
  107652. continue;
  107653. }
  107654. // Search for parent bone
  107655. var foundBone = false;
  107656. var parentBone = null;
  107657. for (var j = 0; j < i; j++) {
  107658. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  107659. if (!jointNode_1) {
  107660. continue;
  107661. }
  107662. var joint = jointNode_1.node;
  107663. if (!joint) {
  107664. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  107665. continue;
  107666. }
  107667. var children = joint.children;
  107668. if (!children) {
  107669. continue;
  107670. }
  107671. foundBone = false;
  107672. for (var k = 0; k < children.length; k++) {
  107673. if (children[k] === id) {
  107674. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  107675. foundBone = true;
  107676. break;
  107677. }
  107678. }
  107679. if (foundBone) {
  107680. break;
  107681. }
  107682. }
  107683. // Create bone
  107684. var mat = configureBoneTransformation(node);
  107685. if (!parentBone && nodesToRoot.length > 0) {
  107686. parentBone = getNodeToRoot(nodesToRoot, id);
  107687. if (parentBone) {
  107688. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  107689. nodesToRootToAdd.push(parentBone);
  107690. }
  107691. }
  107692. }
  107693. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  107694. bone.id = id;
  107695. }
  107696. // Polish
  107697. var bones = newSkeleton.bones;
  107698. newSkeleton.bones = [];
  107699. for (var i = 0; i < skins.jointNames.length; i++) {
  107700. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  107701. if (!jointNode) {
  107702. continue;
  107703. }
  107704. for (var j = 0; j < bones.length; j++) {
  107705. if (bones[j].id === jointNode.id) {
  107706. newSkeleton.bones.push(bones[j]);
  107707. break;
  107708. }
  107709. }
  107710. }
  107711. newSkeleton.prepare();
  107712. // Finish
  107713. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  107714. newSkeleton.bones.push(nodesToRootToAdd[i]);
  107715. }
  107716. return newSkeleton;
  107717. };
  107718. /**
  107719. * Imports a mesh and its geometries
  107720. */
  107721. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  107722. if (!newMesh) {
  107723. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  107724. newMesh.id = id;
  107725. }
  107726. if (!node.babylonNode) {
  107727. return newMesh;
  107728. }
  107729. var subMaterials = [];
  107730. var vertexData = null;
  107731. var verticesStarts = new Array();
  107732. var verticesCounts = new Array();
  107733. var indexStarts = new Array();
  107734. var indexCounts = new Array();
  107735. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  107736. var meshID = meshes[meshIndex];
  107737. var mesh = gltfRuntime.meshes[meshID];
  107738. if (!mesh) {
  107739. continue;
  107740. }
  107741. // Positions, normals and UVs
  107742. for (var i = 0; i < mesh.primitives.length; i++) {
  107743. // Temporary vertex data
  107744. var tempVertexData = new BABYLON.VertexData();
  107745. var primitive = mesh.primitives[i];
  107746. if (primitive.mode !== 4) {
  107747. // continue;
  107748. }
  107749. var attributes = primitive.attributes;
  107750. var accessor = null;
  107751. var buffer = null;
  107752. // Set positions, normal and uvs
  107753. for (var semantic in attributes) {
  107754. // Link accessor and buffer view
  107755. accessor = gltfRuntime.accessors[attributes[semantic]];
  107756. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  107757. if (semantic === "NORMAL") {
  107758. tempVertexData.normals = new Float32Array(buffer.length);
  107759. tempVertexData.normals.set(buffer);
  107760. }
  107761. else if (semantic === "POSITION") {
  107762. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  107763. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  107764. for (var j = 0; j < buffer.length; j += 4) {
  107765. tempVertexData.positions[j] = buffer[j];
  107766. tempVertexData.positions[j + 1] = buffer[j + 1];
  107767. tempVertexData.positions[j + 2] = buffer[j + 2];
  107768. }
  107769. }
  107770. else {
  107771. tempVertexData.positions = new Float32Array(buffer.length);
  107772. tempVertexData.positions.set(buffer);
  107773. }
  107774. verticesCounts.push(tempVertexData.positions.length);
  107775. }
  107776. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  107777. var channel = Number(semantic.split("_")[1]);
  107778. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  107779. var uvs = new Float32Array(buffer.length);
  107780. uvs.set(buffer);
  107781. normalizeUVs(uvs);
  107782. tempVertexData.set(uvs, uvKind);
  107783. }
  107784. else if (semantic === "JOINT") {
  107785. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  107786. tempVertexData.matricesIndices.set(buffer);
  107787. }
  107788. else if (semantic === "WEIGHT") {
  107789. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  107790. tempVertexData.matricesWeights.set(buffer);
  107791. }
  107792. else if (semantic === "COLOR") {
  107793. tempVertexData.colors = new Float32Array(buffer.length);
  107794. tempVertexData.colors.set(buffer);
  107795. }
  107796. }
  107797. // Indices
  107798. accessor = gltfRuntime.accessors[primitive.indices];
  107799. if (accessor) {
  107800. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  107801. tempVertexData.indices = new Int32Array(buffer.length);
  107802. tempVertexData.indices.set(buffer);
  107803. indexCounts.push(tempVertexData.indices.length);
  107804. }
  107805. else {
  107806. // Set indices on the fly
  107807. var indices = [];
  107808. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  107809. indices.push(j);
  107810. }
  107811. tempVertexData.indices = new Int32Array(indices);
  107812. indexCounts.push(tempVertexData.indices.length);
  107813. }
  107814. if (!vertexData) {
  107815. vertexData = tempVertexData;
  107816. }
  107817. else {
  107818. vertexData.merge(tempVertexData);
  107819. }
  107820. // Sub material
  107821. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  107822. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  107823. // Update vertices start and index start
  107824. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  107825. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  107826. }
  107827. }
  107828. var material;
  107829. if (subMaterials.length > 1) {
  107830. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  107831. material.subMaterials = subMaterials;
  107832. }
  107833. else {
  107834. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  107835. }
  107836. if (subMaterials.length === 1) {
  107837. material = subMaterials[0];
  107838. }
  107839. if (!newMesh.material) {
  107840. newMesh.material = material;
  107841. }
  107842. // Apply geometry
  107843. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  107844. newMesh.computeWorldMatrix(true);
  107845. // Apply submeshes
  107846. newMesh.subMeshes = [];
  107847. var index = 0;
  107848. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  107849. var meshID = meshes[meshIndex];
  107850. var mesh = gltfRuntime.meshes[meshID];
  107851. if (!mesh) {
  107852. continue;
  107853. }
  107854. for (var i = 0; i < mesh.primitives.length; i++) {
  107855. if (mesh.primitives[i].mode !== 4) {
  107856. //continue;
  107857. }
  107858. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  107859. index++;
  107860. }
  107861. }
  107862. // Finish
  107863. return newMesh;
  107864. };
  107865. /**
  107866. * Configure node transformation from position, rotation and scaling
  107867. */
  107868. var configureNode = function (newNode, position, rotation, scaling) {
  107869. if (newNode.position) {
  107870. newNode.position = position;
  107871. }
  107872. if (newNode.rotationQuaternion || newNode.rotation) {
  107873. newNode.rotationQuaternion = rotation;
  107874. }
  107875. if (newNode.scaling) {
  107876. newNode.scaling = scaling;
  107877. }
  107878. };
  107879. /**
  107880. * Configures node from transformation matrix
  107881. */
  107882. var configureNodeFromMatrix = function (newNode, node, parent) {
  107883. if (node.matrix) {
  107884. var position = new BABYLON.Vector3(0, 0, 0);
  107885. var rotation = new BABYLON.Quaternion();
  107886. var scaling = new BABYLON.Vector3(0, 0, 0);
  107887. var mat = BABYLON.Matrix.FromArray(node.matrix);
  107888. mat.decompose(scaling, rotation, position);
  107889. configureNode(newNode, position, rotation, scaling);
  107890. }
  107891. else if (node.translation && node.rotation && node.scale) {
  107892. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  107893. }
  107894. newNode.computeWorldMatrix(true);
  107895. };
  107896. /**
  107897. * Imports a node
  107898. */
  107899. var importNode = function (gltfRuntime, node, id, parent) {
  107900. var lastNode = null;
  107901. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  107902. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  107903. return null;
  107904. }
  107905. }
  107906. // Meshes
  107907. if (node.skin) {
  107908. if (node.meshes) {
  107909. var skin = gltfRuntime.skins[node.skin];
  107910. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  107911. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  107912. if (newMesh.skeleton === null) {
  107913. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  107914. if (!skin.babylonSkeleton) {
  107915. skin.babylonSkeleton = newMesh.skeleton;
  107916. }
  107917. }
  107918. lastNode = newMesh;
  107919. }
  107920. }
  107921. else if (node.meshes) {
  107922. /**
  107923. * Improve meshes property
  107924. */
  107925. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  107926. lastNode = newMesh;
  107927. }
  107928. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  107929. var light = gltfRuntime.lights[node.light];
  107930. if (light) {
  107931. if (light.type === "ambient") {
  107932. var ambienLight = light[light.type];
  107933. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  107934. hemiLight.name = node.name || "";
  107935. if (ambienLight.color) {
  107936. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  107937. }
  107938. lastNode = hemiLight;
  107939. }
  107940. else if (light.type === "directional") {
  107941. var directionalLight = light[light.type];
  107942. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  107943. dirLight.name = node.name || "";
  107944. if (directionalLight.color) {
  107945. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  107946. }
  107947. lastNode = dirLight;
  107948. }
  107949. else if (light.type === "point") {
  107950. var pointLight = light[light.type];
  107951. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  107952. ptLight.name = node.name || "";
  107953. if (pointLight.color) {
  107954. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  107955. }
  107956. lastNode = ptLight;
  107957. }
  107958. else if (light.type === "spot") {
  107959. var spotLight = light[light.type];
  107960. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  107961. spLight.name = node.name || "";
  107962. if (spotLight.color) {
  107963. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  107964. }
  107965. if (spotLight.fallOfAngle) {
  107966. spLight.angle = spotLight.fallOfAngle;
  107967. }
  107968. if (spotLight.fallOffExponent) {
  107969. spLight.exponent = spotLight.fallOffExponent;
  107970. }
  107971. lastNode = spLight;
  107972. }
  107973. }
  107974. }
  107975. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  107976. var camera = gltfRuntime.cameras[node.camera];
  107977. if (camera) {
  107978. if (camera.type === "orthographic") {
  107979. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  107980. orthoCamera.name = node.name || "";
  107981. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  107982. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  107983. lastNode = orthoCamera;
  107984. }
  107985. else if (camera.type === "perspective") {
  107986. var perspectiveCamera = camera[camera.type];
  107987. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  107988. persCamera.name = node.name || "";
  107989. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  107990. if (!perspectiveCamera.aspectRatio) {
  107991. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  107992. }
  107993. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  107994. persCamera.maxZ = perspectiveCamera.zfar;
  107995. persCamera.minZ = perspectiveCamera.znear;
  107996. }
  107997. lastNode = persCamera;
  107998. }
  107999. }
  108000. }
  108001. // Empty node
  108002. if (!node.jointName) {
  108003. if (node.babylonNode) {
  108004. return node.babylonNode;
  108005. }
  108006. else if (lastNode === null) {
  108007. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  108008. node.babylonNode = dummy;
  108009. lastNode = dummy;
  108010. }
  108011. }
  108012. if (lastNode !== null) {
  108013. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  108014. configureNodeFromMatrix(lastNode, node, parent);
  108015. }
  108016. else {
  108017. var translation = node.translation || [0, 0, 0];
  108018. var rotation = node.rotation || [0, 0, 0, 1];
  108019. var scale = node.scale || [1, 1, 1];
  108020. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  108021. }
  108022. lastNode.updateCache(true);
  108023. node.babylonNode = lastNode;
  108024. }
  108025. return lastNode;
  108026. };
  108027. /**
  108028. * Traverses nodes and creates them
  108029. */
  108030. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  108031. if (meshIncluded === void 0) { meshIncluded = false; }
  108032. var node = gltfRuntime.nodes[id];
  108033. var newNode = null;
  108034. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  108035. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  108036. meshIncluded = true;
  108037. }
  108038. else {
  108039. meshIncluded = false;
  108040. }
  108041. }
  108042. else {
  108043. meshIncluded = true;
  108044. }
  108045. if (!node.jointName && meshIncluded) {
  108046. newNode = importNode(gltfRuntime, node, id, parent);
  108047. if (newNode !== null) {
  108048. newNode.id = id;
  108049. newNode.parent = parent;
  108050. }
  108051. }
  108052. if (node.children) {
  108053. for (var i = 0; i < node.children.length; i++) {
  108054. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  108055. }
  108056. }
  108057. };
  108058. /**
  108059. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  108060. */
  108061. var postLoad = function (gltfRuntime) {
  108062. // Nodes
  108063. var currentScene = gltfRuntime.currentScene;
  108064. if (currentScene) {
  108065. for (var i = 0; i < currentScene.nodes.length; i++) {
  108066. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  108067. }
  108068. }
  108069. else {
  108070. for (var thing in gltfRuntime.scenes) {
  108071. currentScene = gltfRuntime.scenes[thing];
  108072. for (var i = 0; i < currentScene.nodes.length; i++) {
  108073. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  108074. }
  108075. }
  108076. }
  108077. // Set animations
  108078. loadAnimations(gltfRuntime);
  108079. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  108080. var skeleton = gltfRuntime.scene.skeletons[i];
  108081. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  108082. }
  108083. };
  108084. /**
  108085. * onBind shaderrs callback to set uniforms and matrices
  108086. */
  108087. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  108088. var materialValues = material.values || technique.parameters;
  108089. for (var unif in unTreatedUniforms) {
  108090. var uniform = unTreatedUniforms[unif];
  108091. var type = uniform.type;
  108092. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  108093. if (uniform.semantic && !uniform.source && !uniform.node) {
  108094. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  108095. }
  108096. else if (uniform.semantic && (uniform.source || uniform.node)) {
  108097. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  108098. if (source === null) {
  108099. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  108100. }
  108101. if (source === null) {
  108102. continue;
  108103. }
  108104. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  108105. }
  108106. }
  108107. else {
  108108. var value = materialValues[technique.uniforms[unif]];
  108109. if (!value) {
  108110. continue;
  108111. }
  108112. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  108113. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  108114. if (texture === null || texture === undefined) {
  108115. continue;
  108116. }
  108117. shaderMaterial.getEffect().setTexture(unif, texture);
  108118. }
  108119. else {
  108120. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  108121. }
  108122. }
  108123. }
  108124. onSuccess(shaderMaterial);
  108125. };
  108126. /**
  108127. * Prepare uniforms to send the only one time
  108128. * Loads the appropriate textures
  108129. */
  108130. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  108131. var materialValues = material.values || technique.parameters;
  108132. var techniqueUniforms = technique.uniforms;
  108133. /**
  108134. * Prepare values here (not matrices)
  108135. */
  108136. for (var unif in unTreatedUniforms) {
  108137. var uniform = unTreatedUniforms[unif];
  108138. var type = uniform.type;
  108139. var value = materialValues[techniqueUniforms[unif]];
  108140. if (value === undefined) {
  108141. // In case the value is the same for all materials
  108142. value = uniform.value;
  108143. }
  108144. if (!value) {
  108145. continue;
  108146. }
  108147. var onLoadTexture = function (uniformName) {
  108148. return function (texture) {
  108149. if (uniform.value && uniformName) {
  108150. // Static uniform
  108151. shaderMaterial.setTexture(uniformName, texture);
  108152. delete unTreatedUniforms[uniformName];
  108153. }
  108154. };
  108155. };
  108156. // Texture (sampler2D)
  108157. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  108158. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  108159. }
  108160. else {
  108161. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  108162. // Static uniform
  108163. delete unTreatedUniforms[unif];
  108164. }
  108165. }
  108166. }
  108167. };
  108168. /**
  108169. * Shader compilation failed
  108170. */
  108171. var onShaderCompileError = function (program, shaderMaterial, onError) {
  108172. return function (effect, error) {
  108173. shaderMaterial.dispose(true);
  108174. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  108175. };
  108176. };
  108177. /**
  108178. * Shader compilation success
  108179. */
  108180. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  108181. return function (_) {
  108182. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  108183. shaderMaterial.onBind = function (mesh) {
  108184. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  108185. };
  108186. };
  108187. };
  108188. /**
  108189. * Returns the appropriate uniform if already handled by babylon
  108190. */
  108191. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  108192. for (var unif in technique.uniforms) {
  108193. var uniform = technique.uniforms[unif];
  108194. var uniformParameter = technique.parameters[uniform];
  108195. if (tokenizer.currentIdentifier === unif) {
  108196. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  108197. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  108198. if (transformIndex !== -1) {
  108199. delete unTreatedUniforms[unif];
  108200. return babylonTransforms[transformIndex];
  108201. }
  108202. }
  108203. }
  108204. }
  108205. return tokenizer.currentIdentifier;
  108206. };
  108207. /**
  108208. * All shaders loaded. Create materials one by one
  108209. */
  108210. var importMaterials = function (gltfRuntime) {
  108211. // Create materials
  108212. for (var mat in gltfRuntime.materials) {
  108213. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  108214. }
  108215. };
  108216. /**
  108217. * Implementation of the base glTF spec
  108218. */
  108219. var GLTFLoaderBase = /** @class */ (function () {
  108220. function GLTFLoaderBase() {
  108221. }
  108222. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  108223. var gltfRuntime = {
  108224. extensions: {},
  108225. accessors: {},
  108226. buffers: {},
  108227. bufferViews: {},
  108228. meshes: {},
  108229. lights: {},
  108230. cameras: {},
  108231. nodes: {},
  108232. images: {},
  108233. textures: {},
  108234. shaders: {},
  108235. programs: {},
  108236. samplers: {},
  108237. techniques: {},
  108238. materials: {},
  108239. animations: {},
  108240. skins: {},
  108241. extensionsUsed: [],
  108242. scenes: {},
  108243. buffersCount: 0,
  108244. shaderscount: 0,
  108245. scene: scene,
  108246. rootUrl: rootUrl,
  108247. loadedBufferCount: 0,
  108248. loadedBufferViews: {},
  108249. loadedShaderCount: 0,
  108250. importOnlyMeshes: false,
  108251. dummyNodes: []
  108252. };
  108253. // Parse
  108254. if (parsedData.extensions) {
  108255. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  108256. }
  108257. if (parsedData.extensionsUsed) {
  108258. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  108259. }
  108260. if (parsedData.buffers) {
  108261. parseBuffers(parsedData.buffers, gltfRuntime);
  108262. }
  108263. if (parsedData.bufferViews) {
  108264. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  108265. }
  108266. if (parsedData.accessors) {
  108267. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  108268. }
  108269. if (parsedData.meshes) {
  108270. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  108271. }
  108272. if (parsedData.lights) {
  108273. parseObject(parsedData.lights, "lights", gltfRuntime);
  108274. }
  108275. if (parsedData.cameras) {
  108276. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  108277. }
  108278. if (parsedData.nodes) {
  108279. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  108280. }
  108281. if (parsedData.images) {
  108282. parseObject(parsedData.images, "images", gltfRuntime);
  108283. }
  108284. if (parsedData.textures) {
  108285. parseObject(parsedData.textures, "textures", gltfRuntime);
  108286. }
  108287. if (parsedData.shaders) {
  108288. parseShaders(parsedData.shaders, gltfRuntime);
  108289. }
  108290. if (parsedData.programs) {
  108291. parseObject(parsedData.programs, "programs", gltfRuntime);
  108292. }
  108293. if (parsedData.samplers) {
  108294. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  108295. }
  108296. if (parsedData.techniques) {
  108297. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  108298. }
  108299. if (parsedData.materials) {
  108300. parseObject(parsedData.materials, "materials", gltfRuntime);
  108301. }
  108302. if (parsedData.animations) {
  108303. parseObject(parsedData.animations, "animations", gltfRuntime);
  108304. }
  108305. if (parsedData.skins) {
  108306. parseObject(parsedData.skins, "skins", gltfRuntime);
  108307. }
  108308. if (parsedData.scenes) {
  108309. gltfRuntime.scenes = parsedData.scenes;
  108310. }
  108311. if (parsedData.scene && parsedData.scenes) {
  108312. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  108313. }
  108314. return gltfRuntime;
  108315. };
  108316. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  108317. var buffer = gltfRuntime.buffers[id];
  108318. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  108319. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  108320. }
  108321. else {
  108322. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  108323. if (request) {
  108324. onError(request.status + " " + request.statusText);
  108325. }
  108326. });
  108327. }
  108328. };
  108329. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108330. var texture = gltfRuntime.textures[id];
  108331. if (!texture || !texture.source) {
  108332. onError("");
  108333. return;
  108334. }
  108335. if (texture.babylonTexture) {
  108336. onSuccess(null);
  108337. return;
  108338. }
  108339. var source = gltfRuntime.images[texture.source];
  108340. if (BABYLON.Tools.IsBase64(source.uri)) {
  108341. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  108342. }
  108343. else {
  108344. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  108345. if (request) {
  108346. onError(request.status + " " + request.statusText);
  108347. }
  108348. });
  108349. }
  108350. };
  108351. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  108352. var texture = gltfRuntime.textures[id];
  108353. if (texture.babylonTexture) {
  108354. onSuccess(texture.babylonTexture);
  108355. return;
  108356. }
  108357. var sampler = gltfRuntime.samplers[texture.sampler];
  108358. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  108359. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  108360. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  108361. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  108362. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  108363. var blob = new Blob([buffer]);
  108364. var blobURL = URL.createObjectURL(blob);
  108365. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  108366. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  108367. if (sampler.wrapS !== undefined) {
  108368. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  108369. }
  108370. if (sampler.wrapT !== undefined) {
  108371. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  108372. }
  108373. newTexture.name = id;
  108374. texture.babylonTexture = newTexture;
  108375. onSuccess(newTexture);
  108376. };
  108377. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  108378. var shader = gltfRuntime.shaders[id];
  108379. if (BABYLON.Tools.IsBase64(shader.uri)) {
  108380. var shaderString = atob(shader.uri.split(",")[1]);
  108381. if (onSuccess) {
  108382. onSuccess(shaderString);
  108383. }
  108384. }
  108385. else {
  108386. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  108387. if (request && onError) {
  108388. onError(request.status + " " + request.statusText);
  108389. }
  108390. });
  108391. }
  108392. };
  108393. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  108394. var material = gltfRuntime.materials[id];
  108395. if (!material.technique) {
  108396. if (onError) {
  108397. onError("No technique found.");
  108398. }
  108399. return;
  108400. }
  108401. var technique = gltfRuntime.techniques[material.technique];
  108402. if (!technique) {
  108403. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  108404. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  108405. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  108406. onSuccess(defaultMaterial);
  108407. return;
  108408. }
  108409. var program = gltfRuntime.programs[technique.program];
  108410. var states = technique.states;
  108411. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  108412. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  108413. var newVertexShader = "";
  108414. var newPixelShader = "";
  108415. var vertexTokenizer = new Tokenizer(vertexShader);
  108416. var pixelTokenizer = new Tokenizer(pixelShader);
  108417. var unTreatedUniforms = {};
  108418. var uniforms = [];
  108419. var attributes = [];
  108420. var samplers = [];
  108421. // Fill uniform, sampler2D and attributes
  108422. for (var unif in technique.uniforms) {
  108423. var uniform = technique.uniforms[unif];
  108424. var uniformParameter = technique.parameters[uniform];
  108425. unTreatedUniforms[unif] = uniformParameter;
  108426. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  108427. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  108428. if (transformIndex !== -1) {
  108429. uniforms.push(babylonTransforms[transformIndex]);
  108430. delete unTreatedUniforms[unif];
  108431. }
  108432. else {
  108433. uniforms.push(unif);
  108434. }
  108435. }
  108436. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  108437. samplers.push(unif);
  108438. }
  108439. else {
  108440. uniforms.push(unif);
  108441. }
  108442. }
  108443. for (var attr in technique.attributes) {
  108444. var attribute = technique.attributes[attr];
  108445. var attributeParameter = technique.parameters[attribute];
  108446. if (attributeParameter.semantic) {
  108447. attributes.push(getAttribute(attributeParameter));
  108448. }
  108449. }
  108450. // Configure vertex shader
  108451. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  108452. var tokenType = vertexTokenizer.currentToken;
  108453. if (tokenType !== ETokenType.IDENTIFIER) {
  108454. newVertexShader += vertexTokenizer.currentString;
  108455. continue;
  108456. }
  108457. var foundAttribute = false;
  108458. for (var attr in technique.attributes) {
  108459. var attribute = technique.attributes[attr];
  108460. var attributeParameter = technique.parameters[attribute];
  108461. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  108462. newVertexShader += getAttribute(attributeParameter);
  108463. foundAttribute = true;
  108464. break;
  108465. }
  108466. }
  108467. if (foundAttribute) {
  108468. continue;
  108469. }
  108470. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  108471. }
  108472. // Configure pixel shader
  108473. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  108474. var tokenType = pixelTokenizer.currentToken;
  108475. if (tokenType !== ETokenType.IDENTIFIER) {
  108476. newPixelShader += pixelTokenizer.currentString;
  108477. continue;
  108478. }
  108479. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  108480. }
  108481. // Create shader material
  108482. var shaderPath = {
  108483. vertex: program.vertexShader + id,
  108484. fragment: program.fragmentShader + id
  108485. };
  108486. var options = {
  108487. attributes: attributes,
  108488. uniforms: uniforms,
  108489. samplers: samplers,
  108490. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  108491. };
  108492. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  108493. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  108494. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  108495. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  108496. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  108497. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  108498. if (states && states.functions) {
  108499. var functions = states.functions;
  108500. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  108501. shaderMaterial.backFaceCulling = false;
  108502. }
  108503. var blendFunc = functions.blendFuncSeparate;
  108504. if (blendFunc) {
  108505. 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) {
  108506. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  108507. }
  108508. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  108509. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  108510. }
  108511. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  108512. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  108513. }
  108514. 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) {
  108515. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  108516. }
  108517. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  108518. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  108519. }
  108520. 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) {
  108521. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  108522. }
  108523. }
  108524. }
  108525. };
  108526. return GLTFLoaderBase;
  108527. }());
  108528. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  108529. /**
  108530. * glTF V1 Loader
  108531. */
  108532. var GLTFLoader = /** @class */ (function () {
  108533. function GLTFLoader() {
  108534. // #region Stubs for IGLTFLoader interface
  108535. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  108536. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  108537. this.compileMaterials = false;
  108538. this.useClipPlane = false;
  108539. this.compileShadowGenerators = false;
  108540. this.onDisposeObservable = new BABYLON.Observable();
  108541. this.onMeshLoadedObservable = new BABYLON.Observable();
  108542. this.onTextureLoadedObservable = new BABYLON.Observable();
  108543. this.onMaterialLoadedObservable = new BABYLON.Observable();
  108544. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  108545. this.onCompleteObservable = new BABYLON.Observable();
  108546. this.onExtensionLoadedObservable = new BABYLON.Observable();
  108547. this.state = null;
  108548. }
  108549. GLTFLoader.RegisterExtension = function (extension) {
  108550. if (GLTFLoader.Extensions[extension.name]) {
  108551. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  108552. return;
  108553. }
  108554. GLTFLoader.Extensions[extension.name] = extension;
  108555. };
  108556. GLTFLoader.prototype.dispose = function () { };
  108557. // #endregion
  108558. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  108559. var _this = this;
  108560. scene.useRightHandedSystem = true;
  108561. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  108562. gltfRuntime.importOnlyMeshes = true;
  108563. if (meshesNames === "") {
  108564. gltfRuntime.importMeshesNames = [];
  108565. }
  108566. else if (typeof meshesNames === "string") {
  108567. gltfRuntime.importMeshesNames = [meshesNames];
  108568. }
  108569. else if (meshesNames && !(meshesNames instanceof Array)) {
  108570. gltfRuntime.importMeshesNames = [meshesNames];
  108571. }
  108572. else {
  108573. gltfRuntime.importMeshesNames = [];
  108574. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  108575. }
  108576. // Create nodes
  108577. _this._createNodes(gltfRuntime);
  108578. var meshes = new Array();
  108579. var skeletons = new Array();
  108580. // Fill arrays of meshes and skeletons
  108581. for (var nde in gltfRuntime.nodes) {
  108582. var node = gltfRuntime.nodes[nde];
  108583. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  108584. meshes.push(node.babylonNode);
  108585. }
  108586. }
  108587. for (var skl in gltfRuntime.skins) {
  108588. var skin = gltfRuntime.skins[skl];
  108589. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  108590. skeletons.push(skin.babylonSkeleton);
  108591. }
  108592. }
  108593. // Load buffers, shaders, materials, etc.
  108594. _this._loadBuffersAsync(gltfRuntime, function () {
  108595. _this._loadShadersAsync(gltfRuntime, function () {
  108596. importMaterials(gltfRuntime);
  108597. postLoad(gltfRuntime);
  108598. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  108599. onSuccess(meshes, [], skeletons);
  108600. }
  108601. });
  108602. }, onProgress);
  108603. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  108604. onSuccess(meshes, [], skeletons);
  108605. }
  108606. }, onError);
  108607. return true;
  108608. };
  108609. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  108610. var _this = this;
  108611. return new Promise(function (resolve, reject) {
  108612. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  108613. resolve({
  108614. meshes: meshes,
  108615. particleSystems: particleSystems,
  108616. skeletons: skeletons
  108617. });
  108618. }, onProgress, function (message) {
  108619. reject(new Error(message));
  108620. });
  108621. });
  108622. };
  108623. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  108624. var _this = this;
  108625. scene.useRightHandedSystem = true;
  108626. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  108627. // Load runtime extensios
  108628. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  108629. // Create nodes
  108630. _this._createNodes(gltfRuntime);
  108631. // Load buffers, shaders, materials, etc.
  108632. _this._loadBuffersAsync(gltfRuntime, function () {
  108633. _this._loadShadersAsync(gltfRuntime, function () {
  108634. importMaterials(gltfRuntime);
  108635. postLoad(gltfRuntime);
  108636. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  108637. onSuccess();
  108638. }
  108639. });
  108640. });
  108641. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  108642. onSuccess();
  108643. }
  108644. }, onError);
  108645. }, onError);
  108646. };
  108647. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  108648. var _this = this;
  108649. return new Promise(function (resolve, reject) {
  108650. _this._loadAsync(scene, data, rootUrl, function () {
  108651. resolve();
  108652. }, onProgress, function (message) {
  108653. reject(new Error(message));
  108654. });
  108655. });
  108656. };
  108657. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  108658. var hasShaders = false;
  108659. var processShader = function (sha, shader) {
  108660. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  108661. if (shaderString instanceof ArrayBuffer) {
  108662. return;
  108663. }
  108664. gltfRuntime.loadedShaderCount++;
  108665. if (shaderString) {
  108666. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  108667. }
  108668. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  108669. onload();
  108670. }
  108671. }, function () {
  108672. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  108673. });
  108674. };
  108675. for (var sha in gltfRuntime.shaders) {
  108676. hasShaders = true;
  108677. var shader = gltfRuntime.shaders[sha];
  108678. if (shader) {
  108679. processShader.bind(this, sha, shader)();
  108680. }
  108681. else {
  108682. BABYLON.Tools.Error("No shader named: " + sha);
  108683. }
  108684. }
  108685. if (!hasShaders) {
  108686. onload();
  108687. }
  108688. };
  108689. ;
  108690. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  108691. var hasBuffers = false;
  108692. var processBuffer = function (buf, buffer) {
  108693. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  108694. gltfRuntime.loadedBufferCount++;
  108695. if (bufferView) {
  108696. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  108697. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  108698. }
  108699. gltfRuntime.loadedBufferViews[buf] = bufferView;
  108700. }
  108701. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  108702. onLoad();
  108703. }
  108704. }, function () {
  108705. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  108706. });
  108707. };
  108708. for (var buf in gltfRuntime.buffers) {
  108709. hasBuffers = true;
  108710. var buffer = gltfRuntime.buffers[buf];
  108711. if (buffer) {
  108712. processBuffer.bind(this, buf, buffer)();
  108713. }
  108714. else {
  108715. BABYLON.Tools.Error("No buffer named: " + buf);
  108716. }
  108717. }
  108718. if (!hasBuffers) {
  108719. onLoad();
  108720. }
  108721. };
  108722. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  108723. var currentScene = gltfRuntime.currentScene;
  108724. if (currentScene) {
  108725. // Only one scene even if multiple scenes are defined
  108726. for (var i = 0; i < currentScene.nodes.length; i++) {
  108727. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  108728. }
  108729. }
  108730. else {
  108731. // Load all scenes
  108732. for (var thing in gltfRuntime.scenes) {
  108733. currentScene = gltfRuntime.scenes[thing];
  108734. for (var i = 0; i < currentScene.nodes.length; i++) {
  108735. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  108736. }
  108737. }
  108738. }
  108739. };
  108740. GLTFLoader.Extensions = {};
  108741. return GLTFLoader;
  108742. }());
  108743. GLTF1.GLTFLoader = GLTFLoader;
  108744. ;
  108745. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  108746. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108747. })(BABYLON || (BABYLON = {}));
  108748. //# sourceMappingURL=babylon.glTFLoader.js.map
  108749. "use strict";
  108750. var BABYLON;
  108751. (function (BABYLON) {
  108752. var GLTF1;
  108753. (function (GLTF1) {
  108754. /**
  108755. * Utils functions for GLTF
  108756. */
  108757. var GLTFUtils = /** @class */ (function () {
  108758. function GLTFUtils() {
  108759. }
  108760. /**
  108761. * Sets the given "parameter" matrix
  108762. * @param scene: the {BABYLON.Scene} object
  108763. * @param source: the source node where to pick the matrix
  108764. * @param parameter: the GLTF technique parameter
  108765. * @param uniformName: the name of the shader's uniform
  108766. * @param shaderMaterial: the shader material
  108767. */
  108768. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  108769. var mat = null;
  108770. if (parameter.semantic === "MODEL") {
  108771. mat = source.getWorldMatrix();
  108772. }
  108773. else if (parameter.semantic === "PROJECTION") {
  108774. mat = scene.getProjectionMatrix();
  108775. }
  108776. else if (parameter.semantic === "VIEW") {
  108777. mat = scene.getViewMatrix();
  108778. }
  108779. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  108780. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  108781. }
  108782. else if (parameter.semantic === "MODELVIEW") {
  108783. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  108784. }
  108785. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  108786. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  108787. }
  108788. else if (parameter.semantic === "MODELINVERSE") {
  108789. mat = source.getWorldMatrix().invert();
  108790. }
  108791. else if (parameter.semantic === "VIEWINVERSE") {
  108792. mat = scene.getViewMatrix().invert();
  108793. }
  108794. else if (parameter.semantic === "PROJECTIONINVERSE") {
  108795. mat = scene.getProjectionMatrix().invert();
  108796. }
  108797. else if (parameter.semantic === "MODELVIEWINVERSE") {
  108798. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  108799. }
  108800. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  108801. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  108802. }
  108803. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  108804. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  108805. }
  108806. else {
  108807. debugger;
  108808. }
  108809. if (mat) {
  108810. switch (parameter.type) {
  108811. case GLTF1.EParameterType.FLOAT_MAT2:
  108812. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  108813. break;
  108814. case GLTF1.EParameterType.FLOAT_MAT3:
  108815. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  108816. break;
  108817. case GLTF1.EParameterType.FLOAT_MAT4:
  108818. shaderMaterial.setMatrix(uniformName, mat);
  108819. break;
  108820. default: break;
  108821. }
  108822. }
  108823. };
  108824. /**
  108825. * Sets the given "parameter" matrix
  108826. * @param shaderMaterial: the shader material
  108827. * @param uniform: the name of the shader's uniform
  108828. * @param value: the value of the uniform
  108829. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  108830. */
  108831. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  108832. switch (type) {
  108833. case GLTF1.EParameterType.FLOAT:
  108834. shaderMaterial.setFloat(uniform, value);
  108835. return true;
  108836. case GLTF1.EParameterType.FLOAT_VEC2:
  108837. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  108838. return true;
  108839. case GLTF1.EParameterType.FLOAT_VEC3:
  108840. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  108841. return true;
  108842. case GLTF1.EParameterType.FLOAT_VEC4:
  108843. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  108844. return true;
  108845. default: return false;
  108846. }
  108847. };
  108848. /**
  108849. * Returns the wrap mode of the texture
  108850. * @param mode: the mode value
  108851. */
  108852. GLTFUtils.GetWrapMode = function (mode) {
  108853. switch (mode) {
  108854. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  108855. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  108856. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  108857. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  108858. }
  108859. };
  108860. /**
  108861. * Returns the byte stride giving an accessor
  108862. * @param accessor: the GLTF accessor objet
  108863. */
  108864. GLTFUtils.GetByteStrideFromType = function (accessor) {
  108865. // Needs this function since "byteStride" isn't requiered in glTF format
  108866. var type = accessor.type;
  108867. switch (type) {
  108868. case "VEC2": return 2;
  108869. case "VEC3": return 3;
  108870. case "VEC4": return 4;
  108871. case "MAT2": return 4;
  108872. case "MAT3": return 9;
  108873. case "MAT4": return 16;
  108874. default: return 1;
  108875. }
  108876. };
  108877. /**
  108878. * Returns the texture filter mode giving a mode value
  108879. * @param mode: the filter mode value
  108880. */
  108881. GLTFUtils.GetTextureFilterMode = function (mode) {
  108882. switch (mode) {
  108883. case GLTF1.ETextureFilterType.LINEAR:
  108884. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  108885. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  108886. case GLTF1.ETextureFilterType.NEAREST:
  108887. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  108888. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  108889. }
  108890. };
  108891. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  108892. var byteOffset = bufferView.byteOffset + byteOffset;
  108893. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  108894. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  108895. throw new Error("Buffer access is out of range");
  108896. }
  108897. var buffer = loadedBufferView.buffer;
  108898. byteOffset += loadedBufferView.byteOffset;
  108899. switch (componentType) {
  108900. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  108901. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  108902. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  108903. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  108904. default: return new Float32Array(buffer, byteOffset, byteLength);
  108905. }
  108906. };
  108907. /**
  108908. * Returns a buffer from its accessor
  108909. * @param gltfRuntime: the GLTF runtime
  108910. * @param accessor: the GLTF accessor
  108911. */
  108912. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  108913. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  108914. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  108915. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  108916. };
  108917. /**
  108918. * Decodes a buffer view into a string
  108919. * @param view: the buffer view
  108920. */
  108921. GLTFUtils.DecodeBufferToText = function (view) {
  108922. var result = "";
  108923. var length = view.byteLength;
  108924. for (var i = 0; i < length; ++i) {
  108925. result += String.fromCharCode(view[i]);
  108926. }
  108927. return result;
  108928. };
  108929. /**
  108930. * Returns the default material of gltf. Related to
  108931. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  108932. * @param scene: the Babylon.js scene
  108933. */
  108934. GLTFUtils.GetDefaultMaterial = function (scene) {
  108935. if (!GLTFUtils._DefaultMaterial) {
  108936. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  108937. "precision highp float;",
  108938. "",
  108939. "uniform mat4 worldView;",
  108940. "uniform mat4 projection;",
  108941. "",
  108942. "attribute vec3 position;",
  108943. "",
  108944. "void main(void)",
  108945. "{",
  108946. " gl_Position = projection * worldView * vec4(position, 1.0);",
  108947. "}"
  108948. ].join("\n");
  108949. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  108950. "precision highp float;",
  108951. "",
  108952. "uniform vec4 u_emission;",
  108953. "",
  108954. "void main(void)",
  108955. "{",
  108956. " gl_FragColor = u_emission;",
  108957. "}"
  108958. ].join("\n");
  108959. var shaderPath = {
  108960. vertex: "GLTFDefaultMaterial",
  108961. fragment: "GLTFDefaultMaterial"
  108962. };
  108963. var options = {
  108964. attributes: ["position"],
  108965. uniforms: ["worldView", "projection", "u_emission"],
  108966. samplers: new Array(),
  108967. needAlphaBlending: false
  108968. };
  108969. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  108970. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  108971. }
  108972. return GLTFUtils._DefaultMaterial;
  108973. };
  108974. // The GLTF default material
  108975. GLTFUtils._DefaultMaterial = null;
  108976. return GLTFUtils;
  108977. }());
  108978. GLTF1.GLTFUtils = GLTFUtils;
  108979. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108980. })(BABYLON || (BABYLON = {}));
  108981. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  108982. "use strict";
  108983. var BABYLON;
  108984. (function (BABYLON) {
  108985. var GLTF1;
  108986. (function (GLTF1) {
  108987. var GLTFLoaderExtension = /** @class */ (function () {
  108988. function GLTFLoaderExtension(name) {
  108989. this._name = name;
  108990. }
  108991. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  108992. get: function () {
  108993. return this._name;
  108994. },
  108995. enumerable: true,
  108996. configurable: true
  108997. });
  108998. /**
  108999. * Defines an override for loading the runtime
  109000. * Return true to stop further extensions from loading the runtime
  109001. */
  109002. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  109003. return false;
  109004. };
  109005. /**
  109006. * Defines an onverride for creating gltf runtime
  109007. * Return true to stop further extensions from creating the runtime
  109008. */
  109009. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  109010. return false;
  109011. };
  109012. /**
  109013. * Defines an override for loading buffers
  109014. * Return true to stop further extensions from loading this buffer
  109015. */
  109016. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  109017. return false;
  109018. };
  109019. /**
  109020. * Defines an override for loading texture buffers
  109021. * Return true to stop further extensions from loading this texture data
  109022. */
  109023. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  109024. return false;
  109025. };
  109026. /**
  109027. * Defines an override for creating textures
  109028. * Return true to stop further extensions from loading this texture
  109029. */
  109030. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  109031. return false;
  109032. };
  109033. /**
  109034. * Defines an override for loading shader strings
  109035. * Return true to stop further extensions from loading this shader data
  109036. */
  109037. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  109038. return false;
  109039. };
  109040. /**
  109041. * Defines an override for loading materials
  109042. * Return true to stop further extensions from loading this material
  109043. */
  109044. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  109045. return false;
  109046. };
  109047. // ---------
  109048. // Utilities
  109049. // ---------
  109050. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  109051. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  109052. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  109053. }, function () {
  109054. setTimeout(function () {
  109055. if (!onSuccess) {
  109056. return;
  109057. }
  109058. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  109059. });
  109060. });
  109061. };
  109062. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  109063. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  109064. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  109065. }, function () {
  109066. setTimeout(function () {
  109067. onSuccess();
  109068. });
  109069. });
  109070. };
  109071. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  109072. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  109073. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  109074. }, function () {
  109075. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  109076. });
  109077. };
  109078. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  109079. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  109080. if (buffer) {
  109081. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  109082. }
  109083. }, onError);
  109084. };
  109085. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  109086. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  109087. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  109088. }, function () {
  109089. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  109090. });
  109091. };
  109092. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  109093. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  109094. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  109095. }, function () {
  109096. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  109097. });
  109098. };
  109099. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  109100. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  109101. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  109102. }, function () {
  109103. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  109104. });
  109105. };
  109106. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  109107. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  109108. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  109109. }, function () {
  109110. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  109111. });
  109112. };
  109113. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  109114. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  109115. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  109116. if (func(loaderExtension)) {
  109117. return;
  109118. }
  109119. }
  109120. defaultFunc();
  109121. };
  109122. return GLTFLoaderExtension;
  109123. }());
  109124. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  109125. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  109126. })(BABYLON || (BABYLON = {}));
  109127. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  109128. "use strict";
  109129. var BABYLON;
  109130. (function (BABYLON) {
  109131. var GLTF1;
  109132. (function (GLTF1) {
  109133. var BinaryExtensionBufferName = "binary_glTF";
  109134. ;
  109135. ;
  109136. var GLTFBinaryExtension = /** @class */ (function (_super) {
  109137. __extends(GLTFBinaryExtension, _super);
  109138. function GLTFBinaryExtension() {
  109139. return _super.call(this, "KHR_binary_glTF") || this;
  109140. }
  109141. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  109142. var extensionsUsed = data.json.extensionsUsed;
  109143. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  109144. return false;
  109145. }
  109146. this._bin = data.bin;
  109147. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  109148. return true;
  109149. };
  109150. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  109151. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  109152. return false;
  109153. }
  109154. if (id !== BinaryExtensionBufferName) {
  109155. return false;
  109156. }
  109157. onSuccess(this._bin);
  109158. return true;
  109159. };
  109160. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  109161. var texture = gltfRuntime.textures[id];
  109162. var source = gltfRuntime.images[texture.source];
  109163. if (!source.extensions || !(this.name in source.extensions)) {
  109164. return false;
  109165. }
  109166. var sourceExt = source.extensions[this.name];
  109167. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  109168. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  109169. onSuccess(buffer);
  109170. return true;
  109171. };
  109172. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  109173. var shader = gltfRuntime.shaders[id];
  109174. if (!shader.extensions || !(this.name in shader.extensions)) {
  109175. return false;
  109176. }
  109177. var binaryExtensionShader = shader.extensions[this.name];
  109178. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  109179. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  109180. setTimeout(function () {
  109181. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  109182. onSuccess(shaderString);
  109183. });
  109184. return true;
  109185. };
  109186. return GLTFBinaryExtension;
  109187. }(GLTF1.GLTFLoaderExtension));
  109188. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  109189. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  109190. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  109191. })(BABYLON || (BABYLON = {}));
  109192. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  109193. "use strict";
  109194. var BABYLON;
  109195. (function (BABYLON) {
  109196. var GLTF1;
  109197. (function (GLTF1) {
  109198. ;
  109199. ;
  109200. ;
  109201. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  109202. __extends(GLTFMaterialsCommonExtension, _super);
  109203. function GLTFMaterialsCommonExtension() {
  109204. return _super.call(this, "KHR_materials_common") || this;
  109205. }
  109206. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  109207. if (!gltfRuntime.extensions)
  109208. return false;
  109209. var extension = gltfRuntime.extensions[this.name];
  109210. if (!extension)
  109211. return false;
  109212. // Create lights
  109213. var lights = extension.lights;
  109214. if (lights) {
  109215. for (var thing in lights) {
  109216. var light = lights[thing];
  109217. switch (light.type) {
  109218. case "ambient":
  109219. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  109220. var ambient = light.ambient;
  109221. if (ambient) {
  109222. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  109223. }
  109224. break;
  109225. case "point":
  109226. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  109227. var point = light.point;
  109228. if (point) {
  109229. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  109230. }
  109231. break;
  109232. case "directional":
  109233. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  109234. var directional = light.directional;
  109235. if (directional) {
  109236. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  109237. }
  109238. break;
  109239. case "spot":
  109240. var spot = light.spot;
  109241. if (spot) {
  109242. 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);
  109243. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  109244. }
  109245. break;
  109246. default:
  109247. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  109248. break;
  109249. }
  109250. }
  109251. }
  109252. return false;
  109253. };
  109254. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  109255. var material = gltfRuntime.materials[id];
  109256. if (!material || !material.extensions)
  109257. return false;
  109258. var extension = material.extensions[this.name];
  109259. if (!extension)
  109260. return false;
  109261. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  109262. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  109263. if (extension.technique === "CONSTANT") {
  109264. standardMaterial.disableLighting = true;
  109265. }
  109266. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  109267. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  109268. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  109269. // Ambient
  109270. if (typeof extension.values.ambient === "string") {
  109271. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  109272. }
  109273. else {
  109274. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  109275. }
  109276. // Diffuse
  109277. if (typeof extension.values.diffuse === "string") {
  109278. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  109279. }
  109280. else {
  109281. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  109282. }
  109283. // Emission
  109284. if (typeof extension.values.emission === "string") {
  109285. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  109286. }
  109287. else {
  109288. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  109289. }
  109290. // Specular
  109291. if (typeof extension.values.specular === "string") {
  109292. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  109293. }
  109294. else {
  109295. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  109296. }
  109297. return true;
  109298. };
  109299. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  109300. // Create buffer from texture url
  109301. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  109302. // Create texture from buffer
  109303. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  109304. }, onError);
  109305. };
  109306. return GLTFMaterialsCommonExtension;
  109307. }(GLTF1.GLTFLoaderExtension));
  109308. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  109309. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  109310. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  109311. })(BABYLON || (BABYLON = {}));
  109312. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  109313. "use strict";
  109314. var BABYLON;
  109315. (function (BABYLON) {
  109316. var GLTF2;
  109317. (function (GLTF2) {
  109318. var ArrayItem = /** @class */ (function () {
  109319. function ArrayItem() {
  109320. }
  109321. ArrayItem.Assign = function (values) {
  109322. if (values) {
  109323. for (var index = 0; index < values.length; index++) {
  109324. values[index]._index = index;
  109325. }
  109326. }
  109327. };
  109328. return ArrayItem;
  109329. }());
  109330. GLTF2.ArrayItem = ArrayItem;
  109331. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109332. })(BABYLON || (BABYLON = {}));
  109333. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  109334. "use strict";
  109335. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  109336. "use strict";
  109337. var BABYLON;
  109338. (function (BABYLON) {
  109339. var GLTF2;
  109340. (function (GLTF2) {
  109341. var GLTFLoader = /** @class */ (function () {
  109342. function GLTFLoader() {
  109343. this._completePromises = new Array();
  109344. this._disposed = false;
  109345. this._state = null;
  109346. this._extensions = {};
  109347. this._defaultSampler = {};
  109348. this._defaultBabylonMaterials = {};
  109349. this._requests = new Array();
  109350. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  109351. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  109352. this.compileMaterials = false;
  109353. this.useClipPlane = false;
  109354. this.compileShadowGenerators = false;
  109355. this.onDisposeObservable = new BABYLON.Observable();
  109356. this.onMeshLoadedObservable = new BABYLON.Observable();
  109357. this.onTextureLoadedObservable = new BABYLON.Observable();
  109358. this.onMaterialLoadedObservable = new BABYLON.Observable();
  109359. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  109360. this.onExtensionLoadedObservable = new BABYLON.Observable();
  109361. this.onCompleteObservable = new BABYLON.Observable();
  109362. }
  109363. GLTFLoader._Register = function (name, factory) {
  109364. if (GLTFLoader._Factories[name]) {
  109365. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  109366. return;
  109367. }
  109368. GLTFLoader._Factories[name] = factory;
  109369. // Keep the order of registration so that extensions registered first are called first.
  109370. GLTFLoader._Names.push(name);
  109371. };
  109372. Object.defineProperty(GLTFLoader.prototype, "state", {
  109373. get: function () {
  109374. return this._state;
  109375. },
  109376. enumerable: true,
  109377. configurable: true
  109378. });
  109379. GLTFLoader.prototype.dispose = function () {
  109380. if (this._disposed) {
  109381. return;
  109382. }
  109383. this._disposed = true;
  109384. this.onDisposeObservable.notifyObservers(this);
  109385. this.onDisposeObservable.clear();
  109386. this._clear();
  109387. };
  109388. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  109389. var _this = this;
  109390. return Promise.resolve().then(function () {
  109391. var nodes = null;
  109392. if (meshesNames) {
  109393. var nodeMap_1 = {};
  109394. if (_this._gltf.nodes) {
  109395. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  109396. var node = _a[_i];
  109397. if (node.name) {
  109398. nodeMap_1[node.name] = node;
  109399. }
  109400. }
  109401. }
  109402. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  109403. nodes = names.map(function (name) {
  109404. var node = nodeMap_1[name];
  109405. if (!node) {
  109406. throw new Error("Failed to find node '" + name + "'");
  109407. }
  109408. return node;
  109409. });
  109410. }
  109411. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  109412. return {
  109413. meshes: _this._getMeshes(),
  109414. particleSystems: [],
  109415. skeletons: _this._getSkeletons(),
  109416. };
  109417. });
  109418. });
  109419. };
  109420. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  109421. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  109422. };
  109423. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  109424. var _this = this;
  109425. return Promise.resolve().then(function () {
  109426. _this._loadExtensions();
  109427. _this._babylonScene = scene;
  109428. _this._rootUrl = rootUrl;
  109429. _this._progressCallback = onProgress;
  109430. _this._state = BABYLON.GLTFLoaderState.Loading;
  109431. _this._loadData(data);
  109432. _this._checkExtensions();
  109433. var promises = new Array();
  109434. if (nodes) {
  109435. promises.push(_this._loadNodesAsync(nodes));
  109436. }
  109437. else {
  109438. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  109439. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  109440. }
  109441. if (_this.compileMaterials) {
  109442. promises.push(_this._compileMaterialsAsync());
  109443. }
  109444. if (_this.compileShadowGenerators) {
  109445. promises.push(_this._compileShadowGeneratorsAsync());
  109446. }
  109447. var resultPromise = Promise.all(promises).then(function () {
  109448. _this._state = BABYLON.GLTFLoaderState.Ready;
  109449. _this._startAnimations();
  109450. });
  109451. resultPromise.then(function () {
  109452. _this._rootBabylonMesh.setEnabled(true);
  109453. BABYLON.Tools.SetImmediate(function () {
  109454. if (!_this._disposed) {
  109455. Promise.all(_this._completePromises).then(function () {
  109456. _this._state = BABYLON.GLTFLoaderState.Complete;
  109457. _this.onCompleteObservable.notifyObservers(_this);
  109458. _this.onCompleteObservable.clear();
  109459. _this._clear();
  109460. }).catch(function (error) {
  109461. BABYLON.Tools.Error("glTF Loader: " + error.message);
  109462. _this._clear();
  109463. });
  109464. }
  109465. });
  109466. });
  109467. return resultPromise;
  109468. }).catch(function (error) {
  109469. BABYLON.Tools.Error("glTF Loader: " + error.message);
  109470. _this._clear();
  109471. throw error;
  109472. });
  109473. };
  109474. GLTFLoader.prototype._loadExtensions = function () {
  109475. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  109476. var name_1 = _a[_i];
  109477. var extension = GLTFLoader._Factories[name_1](this);
  109478. this._extensions[name_1] = extension;
  109479. this.onExtensionLoadedObservable.notifyObservers(extension);
  109480. }
  109481. this.onExtensionLoadedObservable.clear();
  109482. };
  109483. GLTFLoader.prototype._loadData = function (data) {
  109484. this._gltf = data.json;
  109485. this._setupData();
  109486. if (data.bin) {
  109487. var buffers = this._gltf.buffers;
  109488. if (buffers && buffers[0] && !buffers[0].uri) {
  109489. var binaryBuffer = buffers[0];
  109490. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  109491. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  109492. }
  109493. binaryBuffer._data = Promise.resolve(data.bin);
  109494. }
  109495. else {
  109496. BABYLON.Tools.Warn("Unexpected BIN chunk");
  109497. }
  109498. }
  109499. };
  109500. GLTFLoader.prototype._setupData = function () {
  109501. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  109502. GLTF2.ArrayItem.Assign(this._gltf.animations);
  109503. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  109504. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  109505. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  109506. GLTF2.ArrayItem.Assign(this._gltf.images);
  109507. GLTF2.ArrayItem.Assign(this._gltf.materials);
  109508. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  109509. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  109510. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  109511. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  109512. GLTF2.ArrayItem.Assign(this._gltf.skins);
  109513. GLTF2.ArrayItem.Assign(this._gltf.textures);
  109514. if (this._gltf.nodes) {
  109515. var nodeParents = {};
  109516. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  109517. var node = _a[_i];
  109518. if (node.children) {
  109519. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  109520. var index = _c[_b];
  109521. nodeParents[index] = node._index;
  109522. }
  109523. }
  109524. }
  109525. var rootNode = this._createRootNode();
  109526. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  109527. var node = _e[_d];
  109528. var parentIndex = nodeParents[node._index];
  109529. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  109530. }
  109531. }
  109532. };
  109533. GLTFLoader.prototype._checkExtensions = function () {
  109534. if (this._gltf.extensionsRequired) {
  109535. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  109536. var name_2 = _a[_i];
  109537. var extension = this._extensions[name_2];
  109538. if (!extension || !extension.enabled) {
  109539. throw new Error("Require extension " + name_2 + " is not available");
  109540. }
  109541. }
  109542. }
  109543. };
  109544. GLTFLoader.prototype._createRootNode = function () {
  109545. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  109546. this._rootBabylonMesh.setEnabled(false);
  109547. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  109548. switch (this.coordinateSystemMode) {
  109549. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  109550. if (!this._babylonScene.useRightHandedSystem) {
  109551. rootNode.rotation = [0, 1, 0, 0];
  109552. rootNode.scale = [1, 1, -1];
  109553. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  109554. }
  109555. break;
  109556. }
  109557. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  109558. this._babylonScene.useRightHandedSystem = true;
  109559. break;
  109560. }
  109561. default: {
  109562. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  109563. }
  109564. }
  109565. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  109566. return rootNode;
  109567. };
  109568. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  109569. var promises = new Array();
  109570. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  109571. var node = nodes_1[_i];
  109572. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  109573. }
  109574. promises.push(this._loadAnimationsAsync());
  109575. return Promise.all(promises).then(function () { });
  109576. };
  109577. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  109578. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  109579. if (promise) {
  109580. return promise;
  109581. }
  109582. var promises = new Array();
  109583. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  109584. var index = _a[_i];
  109585. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  109586. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  109587. }
  109588. promises.push(this._loadAnimationsAsync());
  109589. return Promise.all(promises).then(function () { });
  109590. };
  109591. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  109592. if (node._primitiveBabylonMeshes) {
  109593. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  109594. var babylonMesh = _a[_i];
  109595. callback(babylonMesh);
  109596. }
  109597. }
  109598. else {
  109599. callback(node._babylonMesh);
  109600. }
  109601. };
  109602. GLTFLoader.prototype._getMeshes = function () {
  109603. var meshes = new Array();
  109604. // Root mesh is always first.
  109605. meshes.push(this._rootBabylonMesh);
  109606. var nodes = this._gltf.nodes;
  109607. if (nodes) {
  109608. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  109609. var node = nodes_2[_i];
  109610. if (node._babylonMesh) {
  109611. meshes.push(node._babylonMesh);
  109612. }
  109613. if (node._primitiveBabylonMeshes) {
  109614. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  109615. var babylonMesh = _b[_a];
  109616. meshes.push(babylonMesh);
  109617. }
  109618. }
  109619. }
  109620. }
  109621. return meshes;
  109622. };
  109623. GLTFLoader.prototype._getSkeletons = function () {
  109624. var skeletons = new Array();
  109625. var skins = this._gltf.skins;
  109626. if (skins) {
  109627. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  109628. var skin = skins_1[_i];
  109629. if (skin._babylonSkeleton) {
  109630. skeletons.push(skin._babylonSkeleton);
  109631. }
  109632. }
  109633. }
  109634. return skeletons;
  109635. };
  109636. GLTFLoader.prototype._startAnimations = function () {
  109637. var animations = this._gltf.animations;
  109638. if (!animations) {
  109639. return;
  109640. }
  109641. switch (this.animationStartMode) {
  109642. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  109643. // do nothing
  109644. break;
  109645. }
  109646. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  109647. var animation = animations[0];
  109648. animation._babylonAnimationGroup.start(true);
  109649. break;
  109650. }
  109651. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  109652. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  109653. var animation = animations_1[_i];
  109654. animation._babylonAnimationGroup.start(true);
  109655. }
  109656. break;
  109657. }
  109658. default: {
  109659. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  109660. return;
  109661. }
  109662. }
  109663. };
  109664. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  109665. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  109666. if (promise) {
  109667. return promise;
  109668. }
  109669. if (node._babylonMesh) {
  109670. throw new Error(context + ": Invalid recursive node hierarchy");
  109671. }
  109672. var promises = new Array();
  109673. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  109674. node._babylonMesh = babylonMesh;
  109675. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  109676. node._babylonAnimationTargets.push(babylonMesh);
  109677. GLTFLoader._LoadTransform(node, babylonMesh);
  109678. if (node.mesh != undefined) {
  109679. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  109680. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  109681. }
  109682. if (node.children) {
  109683. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  109684. var index = _a[_i];
  109685. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  109686. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  109687. }
  109688. }
  109689. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  109690. return Promise.all(promises).then(function () { });
  109691. };
  109692. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  109693. // TODO: instancing
  109694. var _this = this;
  109695. var promises = new Array();
  109696. var primitives = mesh.primitives;
  109697. if (!primitives || primitives.length === 0) {
  109698. throw new Error(context + ": Primitives are missing");
  109699. }
  109700. GLTF2.ArrayItem.Assign(primitives);
  109701. if (primitives.length === 1) {
  109702. var primitive = primitives[0];
  109703. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  109704. }
  109705. else {
  109706. node._primitiveBabylonMeshes = [];
  109707. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  109708. var primitive = primitives_1[_i];
  109709. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  109710. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  109711. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  109712. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  109713. }
  109714. }
  109715. if (node.skin != undefined) {
  109716. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  109717. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  109718. }
  109719. return Promise.all(promises).then(function () {
  109720. _this._forEachPrimitive(node, function (babylonMesh) {
  109721. babylonMesh._refreshBoundingInfo(true);
  109722. });
  109723. });
  109724. };
  109725. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  109726. var _this = this;
  109727. var promises = new Array();
  109728. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  109729. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  109730. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  109731. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  109732. }));
  109733. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  109734. if (primitive.material == undefined) {
  109735. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  109736. }
  109737. else {
  109738. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  109739. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  109740. babylonMesh.material = babylonMaterial;
  109741. }));
  109742. }
  109743. return Promise.all(promises).then(function () { });
  109744. };
  109745. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  109746. var _this = this;
  109747. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  109748. if (promise) {
  109749. return promise;
  109750. }
  109751. var attributes = primitive.attributes;
  109752. if (!attributes) {
  109753. throw new Error(context + ": Attributes are missing");
  109754. }
  109755. var promises = new Array();
  109756. var babylonVertexData = new BABYLON.VertexData();
  109757. if (primitive.indices == undefined) {
  109758. var positionAccessorIndex = attributes["POSITION"];
  109759. if (positionAccessorIndex != undefined) {
  109760. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  109761. babylonVertexData.indices = new Uint32Array(accessor.count);
  109762. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  109763. babylonVertexData.indices[i] = i;
  109764. }
  109765. }
  109766. }
  109767. else {
  109768. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  109769. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  109770. babylonVertexData.indices = data;
  109771. }));
  109772. }
  109773. var loadAttribute = function (attribute, kind) {
  109774. if (attributes[attribute] == undefined) {
  109775. return;
  109776. }
  109777. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  109778. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  109779. babylonMesh._delayInfo.push(kind);
  109780. }
  109781. if (attribute === "COLOR_0") {
  109782. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  109783. babylonMesh.hasVertexAlpha = true;
  109784. }
  109785. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  109786. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  109787. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  109788. if (attribute === "COLOR_0" && accessor.type === "VEC3") {
  109789. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  109790. }
  109791. babylonVertexData.set(attributeData, kind);
  109792. }));
  109793. };
  109794. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  109795. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  109796. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  109797. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  109798. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  109799. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  109800. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  109801. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  109802. return Promise.all(promises).then(function () {
  109803. return babylonVertexData;
  109804. });
  109805. };
  109806. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  109807. if (!primitive.targets) {
  109808. return;
  109809. }
  109810. if (node._numMorphTargets == undefined) {
  109811. node._numMorphTargets = primitive.targets.length;
  109812. }
  109813. else if (primitive.targets.length !== node._numMorphTargets) {
  109814. throw new Error(context + ": Primitives do not have the same number of targets");
  109815. }
  109816. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  109817. for (var index = 0; index < primitive.targets.length; index++) {
  109818. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  109819. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  109820. // TODO: tell the target whether it has positions, normals, tangents
  109821. }
  109822. };
  109823. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  109824. if (!primitive.targets) {
  109825. return Promise.resolve();
  109826. }
  109827. var promises = new Array();
  109828. var morphTargetManager = babylonMesh.morphTargetManager;
  109829. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  109830. var babylonMorphTarget = morphTargetManager.getTarget(index);
  109831. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  109832. }
  109833. return Promise.all(promises).then(function () { });
  109834. };
  109835. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  109836. var _this = this;
  109837. var promises = new Array();
  109838. var loadAttribute = function (attribute, setData) {
  109839. if (attributes[attribute] == undefined) {
  109840. return;
  109841. }
  109842. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  109843. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  109844. setData(data);
  109845. }));
  109846. };
  109847. loadAttribute("POSITION", function (data) {
  109848. if (babylonVertexData.positions) {
  109849. for (var i = 0; i < data.length; i++) {
  109850. data[i] += babylonVertexData.positions[i];
  109851. }
  109852. babylonMorphTarget.setPositions(data);
  109853. }
  109854. });
  109855. loadAttribute("NORMAL", function (data) {
  109856. if (babylonVertexData.normals) {
  109857. for (var i = 0; i < data.length; i++) {
  109858. data[i] += babylonVertexData.normals[i];
  109859. }
  109860. babylonMorphTarget.setNormals(data);
  109861. }
  109862. });
  109863. loadAttribute("TANGENT", function (data) {
  109864. if (babylonVertexData.tangents) {
  109865. // Tangent data for morph targets is stored as xyz delta.
  109866. // The vertexData.tangent is stored as xyzw.
  109867. // So we need to skip every fourth vertexData.tangent.
  109868. for (var i = 0, j = 0; i < data.length; i++) {
  109869. data[i] += babylonVertexData.tangents[j++];
  109870. if ((i + 1) % 3 == 0) {
  109871. j++;
  109872. }
  109873. }
  109874. babylonMorphTarget.setTangents(data);
  109875. }
  109876. });
  109877. return Promise.all(promises).then(function () { });
  109878. };
  109879. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  109880. if (accessor.componentType == 5126 /* FLOAT */) {
  109881. return data;
  109882. }
  109883. var factor = 1;
  109884. if (accessor.normalized) {
  109885. switch (accessor.componentType) {
  109886. case 5121 /* UNSIGNED_BYTE */: {
  109887. factor = 1 / 255;
  109888. break;
  109889. }
  109890. case 5123 /* UNSIGNED_SHORT */: {
  109891. factor = 1 / 65535;
  109892. break;
  109893. }
  109894. default: {
  109895. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  109896. }
  109897. }
  109898. }
  109899. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  109900. for (var i = 0; i < result.length; i++) {
  109901. result[i] = data[i] * factor;
  109902. }
  109903. return result;
  109904. };
  109905. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  109906. var result = new Float32Array(data.length / 3 * 4);
  109907. var offset = 0;
  109908. for (var i = 0; i < result.length; i++) {
  109909. if ((i + 1) % 4 === 0) {
  109910. result[i] = 1;
  109911. }
  109912. else {
  109913. result[i] = data[offset++];
  109914. }
  109915. }
  109916. return result;
  109917. };
  109918. GLTFLoader._LoadTransform = function (node, babylonNode) {
  109919. var position = BABYLON.Vector3.Zero();
  109920. var rotation = BABYLON.Quaternion.Identity();
  109921. var scaling = BABYLON.Vector3.One();
  109922. if (node.matrix) {
  109923. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  109924. matrix.decompose(scaling, rotation, position);
  109925. }
  109926. else {
  109927. if (node.translation)
  109928. position = BABYLON.Vector3.FromArray(node.translation);
  109929. if (node.rotation)
  109930. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  109931. if (node.scale)
  109932. scaling = BABYLON.Vector3.FromArray(node.scale);
  109933. }
  109934. babylonNode.position = position;
  109935. babylonNode.rotationQuaternion = rotation;
  109936. babylonNode.scaling = scaling;
  109937. };
  109938. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  109939. var _this = this;
  109940. var assignSkeleton = function () {
  109941. _this._forEachPrimitive(node, function (babylonMesh) {
  109942. babylonMesh.skeleton = skin._babylonSkeleton;
  109943. });
  109944. node._babylonMesh.parent = _this._rootBabylonMesh;
  109945. node._babylonMesh.position = BABYLON.Vector3.Zero();
  109946. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  109947. node._babylonMesh.scaling = BABYLON.Vector3.One();
  109948. };
  109949. if (skin._loaded) {
  109950. return skin._loaded.then(function () {
  109951. assignSkeleton();
  109952. });
  109953. }
  109954. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  109955. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  109956. var skeletonId = "skeleton" + skin._index;
  109957. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  109958. skin._babylonSkeleton = babylonSkeleton;
  109959. _this._loadBones(context, skin, inverseBindMatricesData);
  109960. assignSkeleton();
  109961. }));
  109962. };
  109963. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  109964. if (skin.inverseBindMatrices == undefined) {
  109965. return Promise.resolve(null);
  109966. }
  109967. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  109968. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  109969. return data;
  109970. });
  109971. };
  109972. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  109973. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  109974. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  109975. node._babylonAnimationTargets.push(babylonBone);
  109976. return babylonBone;
  109977. };
  109978. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  109979. var babylonBones = {};
  109980. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  109981. var index = _a[_i];
  109982. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  109983. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  109984. }
  109985. };
  109986. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  109987. var babylonBone = babylonBones[node._index];
  109988. if (babylonBone) {
  109989. return babylonBone;
  109990. }
  109991. var boneIndex = skin.joints.indexOf(node._index);
  109992. var baseMatrix = BABYLON.Matrix.Identity();
  109993. if (inverseBindMatricesData && boneIndex !== -1) {
  109994. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  109995. baseMatrix.invertToRef(baseMatrix);
  109996. }
  109997. var babylonParentBone = null;
  109998. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  109999. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  110000. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  110001. }
  110002. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  110003. babylonBones[node._index] = babylonBone;
  110004. return babylonBone;
  110005. };
  110006. GLTFLoader.prototype._getNodeMatrix = function (node) {
  110007. return node.matrix ?
  110008. BABYLON.Matrix.FromArray(node.matrix) :
  110009. 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());
  110010. };
  110011. GLTFLoader.prototype._loadAnimationsAsync = function () {
  110012. var animations = this._gltf.animations;
  110013. if (!animations) {
  110014. return Promise.resolve();
  110015. }
  110016. var promises = new Array();
  110017. for (var index = 0; index < animations.length; index++) {
  110018. var animation = animations[index];
  110019. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  110020. }
  110021. return Promise.all(promises).then(function () { });
  110022. };
  110023. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  110024. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  110025. animation._babylonAnimationGroup = babylonAnimationGroup;
  110026. var promises = new Array();
  110027. GLTF2.ArrayItem.Assign(animation.channels);
  110028. GLTF2.ArrayItem.Assign(animation.samplers);
  110029. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  110030. var channel = _a[_i];
  110031. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  110032. }
  110033. this.onAnimationGroupLoadedObservable.notifyObservers(babylonAnimationGroup);
  110034. return Promise.all(promises).then(function () {
  110035. babylonAnimationGroup.normalize();
  110036. });
  110037. };
  110038. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  110039. var _this = this;
  110040. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  110041. if (!targetNode._babylonMesh || targetNode.skin != undefined) {
  110042. return Promise.resolve();
  110043. }
  110044. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  110045. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  110046. var targetPath;
  110047. var animationType;
  110048. switch (channel.target.path) {
  110049. case "translation" /* TRANSLATION */: {
  110050. targetPath = "position";
  110051. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  110052. break;
  110053. }
  110054. case "rotation" /* ROTATION */: {
  110055. targetPath = "rotationQuaternion";
  110056. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  110057. break;
  110058. }
  110059. case "scale" /* SCALE */: {
  110060. targetPath = "scaling";
  110061. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  110062. break;
  110063. }
  110064. case "weights" /* WEIGHTS */: {
  110065. targetPath = "influence";
  110066. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  110067. break;
  110068. }
  110069. default: {
  110070. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  110071. }
  110072. }
  110073. var outputBufferOffset = 0;
  110074. var getNextOutputValue;
  110075. switch (targetPath) {
  110076. case "position": {
  110077. getNextOutputValue = function () {
  110078. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  110079. outputBufferOffset += 3;
  110080. return value;
  110081. };
  110082. break;
  110083. }
  110084. case "rotationQuaternion": {
  110085. getNextOutputValue = function () {
  110086. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  110087. outputBufferOffset += 4;
  110088. return value;
  110089. };
  110090. break;
  110091. }
  110092. case "scaling": {
  110093. getNextOutputValue = function () {
  110094. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  110095. outputBufferOffset += 3;
  110096. return value;
  110097. };
  110098. break;
  110099. }
  110100. case "influence": {
  110101. getNextOutputValue = function () {
  110102. var value = new Array(targetNode._numMorphTargets);
  110103. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  110104. value[i] = data.output[outputBufferOffset++];
  110105. }
  110106. return value;
  110107. };
  110108. break;
  110109. }
  110110. }
  110111. var getNextKey;
  110112. switch (data.interpolation) {
  110113. case "STEP" /* STEP */: {
  110114. getNextKey = function (frameIndex) { return ({
  110115. frame: data.input[frameIndex],
  110116. value: getNextOutputValue(),
  110117. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  110118. }); };
  110119. break;
  110120. }
  110121. case "LINEAR" /* LINEAR */: {
  110122. getNextKey = function (frameIndex) { return ({
  110123. frame: data.input[frameIndex],
  110124. value: getNextOutputValue()
  110125. }); };
  110126. break;
  110127. }
  110128. case "CUBICSPLINE" /* CUBICSPLINE */: {
  110129. getNextKey = function (frameIndex) { return ({
  110130. frame: data.input[frameIndex],
  110131. inTangent: getNextOutputValue(),
  110132. value: getNextOutputValue(),
  110133. outTangent: getNextOutputValue()
  110134. }); };
  110135. break;
  110136. }
  110137. }
  110138. var keys = new Array(data.input.length);
  110139. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  110140. keys[frameIndex] = getNextKey(frameIndex);
  110141. }
  110142. if (targetPath === "influence") {
  110143. var _loop_1 = function (targetIndex) {
  110144. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  110145. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  110146. babylonAnimation.setKeys(keys.map(function (key) { return ({
  110147. frame: key.frame,
  110148. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  110149. value: key.value[targetIndex],
  110150. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  110151. }); }));
  110152. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  110153. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  110154. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  110155. });
  110156. };
  110157. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  110158. _loop_1(targetIndex);
  110159. }
  110160. }
  110161. else {
  110162. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  110163. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  110164. babylonAnimation.setKeys(keys);
  110165. if (targetNode._babylonAnimationTargets) {
  110166. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  110167. var target = _a[_i];
  110168. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  110169. }
  110170. }
  110171. }
  110172. });
  110173. };
  110174. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  110175. if (sampler._data) {
  110176. return sampler._data;
  110177. }
  110178. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  110179. switch (interpolation) {
  110180. case "STEP" /* STEP */:
  110181. case "LINEAR" /* LINEAR */:
  110182. case "CUBICSPLINE" /* CUBICSPLINE */: {
  110183. break;
  110184. }
  110185. default: {
  110186. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  110187. }
  110188. }
  110189. var inputData;
  110190. var outputData;
  110191. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  110192. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  110193. sampler._data = Promise.all([
  110194. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  110195. inputData = data;
  110196. }),
  110197. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  110198. outputData = data;
  110199. })
  110200. ]).then(function () {
  110201. return {
  110202. input: inputData,
  110203. interpolation: interpolation,
  110204. output: outputData,
  110205. };
  110206. });
  110207. return sampler._data;
  110208. };
  110209. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  110210. if (buffer._data) {
  110211. return buffer._data;
  110212. }
  110213. if (!buffer.uri) {
  110214. throw new Error(context + ": Uri is missing");
  110215. }
  110216. buffer._data = this._loadUriAsync(context, buffer.uri);
  110217. return buffer._data;
  110218. };
  110219. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  110220. if (bufferView._data) {
  110221. return bufferView._data;
  110222. }
  110223. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  110224. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  110225. try {
  110226. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  110227. }
  110228. catch (e) {
  110229. throw new Error(context + ": " + e.message);
  110230. }
  110231. });
  110232. return bufferView._data;
  110233. };
  110234. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  110235. var _this = this;
  110236. if (accessor.sparse) {
  110237. throw new Error(context + ": Sparse accessors are not currently supported");
  110238. }
  110239. if (accessor._data) {
  110240. return accessor._data;
  110241. }
  110242. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  110243. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  110244. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  110245. var byteOffset = accessor.byteOffset || 0;
  110246. var byteStride = bufferView.byteStride;
  110247. if (byteStride === 0) {
  110248. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  110249. }
  110250. try {
  110251. switch (accessor.componentType) {
  110252. case 5120 /* BYTE */: {
  110253. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  110254. }
  110255. case 5121 /* UNSIGNED_BYTE */: {
  110256. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  110257. }
  110258. case 5122 /* SHORT */: {
  110259. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  110260. }
  110261. case 5123 /* UNSIGNED_SHORT */: {
  110262. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  110263. }
  110264. case 5125 /* UNSIGNED_INT */: {
  110265. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  110266. }
  110267. case 5126 /* FLOAT */: {
  110268. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  110269. }
  110270. default: {
  110271. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  110272. }
  110273. }
  110274. }
  110275. catch (e) {
  110276. throw new Error(context + ": " + e.messsage);
  110277. }
  110278. });
  110279. return accessor._data;
  110280. };
  110281. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  110282. byteOffset += data.byteOffset;
  110283. var targetLength = count * numComponents;
  110284. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  110285. return new typedArray(data.buffer, byteOffset, targetLength);
  110286. }
  110287. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  110288. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  110289. var targetBuffer = new typedArray(targetLength);
  110290. var sourceIndex = 0;
  110291. var targetIndex = 0;
  110292. while (targetIndex < targetLength) {
  110293. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  110294. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  110295. targetIndex++;
  110296. }
  110297. sourceIndex += elementStride;
  110298. }
  110299. return targetBuffer;
  110300. };
  110301. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  110302. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  110303. if (!babylonMaterial) {
  110304. babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, "__gltf_default", drawMode);
  110305. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  110306. babylonMaterial.metallic = 1;
  110307. babylonMaterial.roughness = 1;
  110308. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  110309. }
  110310. return babylonMaterial;
  110311. };
  110312. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  110313. var promises = new Array();
  110314. // Ensure metallic workflow
  110315. babylonMaterial.metallic = 1;
  110316. babylonMaterial.roughness = 1;
  110317. var properties = material.pbrMetallicRoughness;
  110318. if (properties) {
  110319. if (properties.baseColorFactor) {
  110320. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  110321. babylonMaterial.alpha = properties.baseColorFactor[3];
  110322. }
  110323. else {
  110324. babylonMaterial.albedoColor = BABYLON.Color3.White();
  110325. }
  110326. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  110327. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  110328. if (properties.baseColorTexture) {
  110329. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  110330. babylonMaterial.albedoTexture = texture;
  110331. }));
  110332. }
  110333. if (properties.metallicRoughnessTexture) {
  110334. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  110335. babylonMaterial.metallicTexture = texture;
  110336. }));
  110337. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  110338. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  110339. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  110340. }
  110341. }
  110342. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  110343. return Promise.all(promises).then(function () { });
  110344. };
  110345. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  110346. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, babylonDrawMode, assign);
  110347. if (promise) {
  110348. return promise;
  110349. }
  110350. material._babylonData = material._babylonData || {};
  110351. var babylonData = material._babylonData[babylonDrawMode];
  110352. if (!babylonData) {
  110353. var promises = new Array();
  110354. var name_3 = material.name || "materialSG_" + material._index;
  110355. var babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, name_3, babylonDrawMode);
  110356. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  110357. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  110358. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  110359. babylonData = {
  110360. material: babylonMaterial,
  110361. meshes: [],
  110362. loaded: Promise.all(promises).then(function () { })
  110363. };
  110364. material._babylonData[babylonDrawMode] = babylonData;
  110365. }
  110366. babylonData.meshes.push(babylonMesh);
  110367. assign(babylonData.material);
  110368. return babylonData.loaded;
  110369. };
  110370. GLTFLoader.prototype._createMaterial = function (type, name, drawMode) {
  110371. var babylonMaterial = new type(name, this._babylonScene);
  110372. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  110373. babylonMaterial.fillMode = drawMode;
  110374. return babylonMaterial;
  110375. };
  110376. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  110377. var promises = new Array();
  110378. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  110379. if (material.doubleSided) {
  110380. babylonMaterial.backFaceCulling = false;
  110381. babylonMaterial.twoSidedLighting = true;
  110382. }
  110383. if (material.normalTexture) {
  110384. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  110385. babylonMaterial.bumpTexture = texture;
  110386. }));
  110387. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  110388. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  110389. if (material.normalTexture.scale != undefined) {
  110390. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  110391. }
  110392. }
  110393. if (material.occlusionTexture) {
  110394. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  110395. babylonMaterial.ambientTexture = texture;
  110396. }));
  110397. babylonMaterial.useAmbientInGrayScale = true;
  110398. if (material.occlusionTexture.strength != undefined) {
  110399. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  110400. }
  110401. }
  110402. if (material.emissiveTexture) {
  110403. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  110404. babylonMaterial.emissiveTexture = texture;
  110405. }));
  110406. }
  110407. return Promise.all(promises).then(function () { });
  110408. };
  110409. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  110410. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  110411. switch (alphaMode) {
  110412. case "OPAQUE" /* OPAQUE */: {
  110413. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  110414. break;
  110415. }
  110416. case "MASK" /* MASK */: {
  110417. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  110418. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  110419. if (babylonMaterial.alpha) {
  110420. if (babylonMaterial.alpha === 0) {
  110421. babylonMaterial.alphaCutOff = 1;
  110422. }
  110423. else {
  110424. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  110425. }
  110426. babylonMaterial.alpha = 1;
  110427. }
  110428. if (babylonMaterial.albedoTexture) {
  110429. babylonMaterial.albedoTexture.hasAlpha = true;
  110430. }
  110431. break;
  110432. }
  110433. case "BLEND" /* BLEND */: {
  110434. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  110435. if (babylonMaterial.albedoTexture) {
  110436. babylonMaterial.albedoTexture.hasAlpha = true;
  110437. babylonMaterial.useAlphaFromAlbedoTexture = true;
  110438. }
  110439. break;
  110440. }
  110441. default: {
  110442. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  110443. }
  110444. }
  110445. };
  110446. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  110447. var _this = this;
  110448. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  110449. context = "#/textures/" + textureInfo.index;
  110450. var promises = new Array();
  110451. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  110452. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  110453. var deferred = new BABYLON.Deferred();
  110454. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  110455. if (!_this._disposed) {
  110456. deferred.resolve();
  110457. }
  110458. }, function (message, exception) {
  110459. if (!_this._disposed) {
  110460. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  110461. }
  110462. });
  110463. promises.push(deferred.promise);
  110464. babylonTexture.name = texture.name || "texture" + texture._index;
  110465. babylonTexture.wrapU = samplerData.wrapU;
  110466. babylonTexture.wrapV = samplerData.wrapV;
  110467. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  110468. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  110469. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  110470. babylonTexture.updateURL(objectURL);
  110471. }));
  110472. assign(babylonTexture);
  110473. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  110474. return Promise.all(promises).then(function () { });
  110475. };
  110476. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  110477. if (!sampler._data) {
  110478. sampler._data = {
  110479. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  110480. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  110481. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  110482. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  110483. };
  110484. }
  110485. ;
  110486. return sampler._data;
  110487. };
  110488. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  110489. if (image._objectURL) {
  110490. return image._objectURL;
  110491. }
  110492. var promise;
  110493. if (image.uri) {
  110494. promise = this._loadUriAsync(context, image.uri);
  110495. }
  110496. else {
  110497. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  110498. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  110499. }
  110500. image._objectURL = promise.then(function (data) {
  110501. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  110502. });
  110503. return image._objectURL;
  110504. };
  110505. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  110506. var _this = this;
  110507. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  110508. if (promise) {
  110509. return promise;
  110510. }
  110511. if (!GLTFLoader._ValidateUri(uri)) {
  110512. throw new Error(context + ": Uri '" + uri + "' is invalid");
  110513. }
  110514. if (BABYLON.Tools.IsBase64(uri)) {
  110515. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  110516. }
  110517. return new Promise(function (resolve, reject) {
  110518. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  110519. if (!_this._disposed) {
  110520. resolve(new Uint8Array(data));
  110521. }
  110522. }, function (event) {
  110523. if (!_this._disposed) {
  110524. try {
  110525. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  110526. request._lengthComputable = event.lengthComputable;
  110527. request._loaded = event.loaded;
  110528. request._total = event.total;
  110529. _this._onProgress();
  110530. }
  110531. }
  110532. catch (e) {
  110533. reject(e);
  110534. }
  110535. }
  110536. }, _this._babylonScene.database, true, function (request, exception) {
  110537. if (!_this._disposed) {
  110538. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  110539. }
  110540. });
  110541. _this._requests.push(request);
  110542. });
  110543. };
  110544. GLTFLoader.prototype._onProgress = function () {
  110545. if (!this._progressCallback) {
  110546. return;
  110547. }
  110548. var lengthComputable = true;
  110549. var loaded = 0;
  110550. var total = 0;
  110551. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  110552. var request = _a[_i];
  110553. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  110554. return;
  110555. }
  110556. lengthComputable = lengthComputable && request._lengthComputable;
  110557. loaded += request._loaded;
  110558. total += request._total;
  110559. }
  110560. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  110561. };
  110562. GLTFLoader._GetProperty = function (context, array, index) {
  110563. if (!array || index == undefined || !array[index]) {
  110564. throw new Error(context + ": Failed to find index (" + index + ")");
  110565. }
  110566. return array[index];
  110567. };
  110568. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  110569. // Set defaults if undefined
  110570. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  110571. switch (mode) {
  110572. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  110573. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  110574. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  110575. default:
  110576. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  110577. return BABYLON.Texture.WRAP_ADDRESSMODE;
  110578. }
  110579. };
  110580. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  110581. // Set defaults if undefined
  110582. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  110583. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  110584. if (magFilter === 9729 /* LINEAR */) {
  110585. switch (minFilter) {
  110586. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  110587. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  110588. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  110589. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  110590. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  110591. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  110592. default:
  110593. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  110594. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  110595. }
  110596. }
  110597. else {
  110598. if (magFilter !== 9728 /* NEAREST */) {
  110599. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  110600. }
  110601. switch (minFilter) {
  110602. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  110603. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  110604. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  110605. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  110606. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  110607. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  110608. default:
  110609. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  110610. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  110611. }
  110612. }
  110613. };
  110614. GLTFLoader._GetNumComponents = function (context, type) {
  110615. switch (type) {
  110616. case "SCALAR": return 1;
  110617. case "VEC2": return 2;
  110618. case "VEC3": return 3;
  110619. case "VEC4": return 4;
  110620. case "MAT2": return 4;
  110621. case "MAT3": return 9;
  110622. case "MAT4": return 16;
  110623. }
  110624. throw new Error(context + ": Invalid type (" + type + ")");
  110625. };
  110626. GLTFLoader._ValidateUri = function (uri) {
  110627. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  110628. };
  110629. GLTFLoader._GetDrawMode = function (context, mode) {
  110630. mode = mode || 4 /* TRIANGLES */;
  110631. switch (mode) {
  110632. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  110633. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  110634. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  110635. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  110636. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  110637. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  110638. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  110639. }
  110640. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  110641. };
  110642. GLTFLoader.prototype._compileMaterialsAsync = function () {
  110643. var promises = new Array();
  110644. if (this._gltf.materials) {
  110645. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  110646. var material = _a[_i];
  110647. if (material._babylonData) {
  110648. for (var babylonDrawMode in material._babylonData) {
  110649. var babylonData = material._babylonData[babylonDrawMode];
  110650. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  110651. var babylonMesh = _c[_b];
  110652. // Ensure nonUniformScaling is set if necessary.
  110653. babylonMesh.computeWorldMatrix(true);
  110654. var babylonMaterial = babylonData.material;
  110655. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  110656. if (this.useClipPlane) {
  110657. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  110658. }
  110659. }
  110660. }
  110661. }
  110662. }
  110663. }
  110664. return Promise.all(promises).then(function () { });
  110665. };
  110666. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  110667. var promises = new Array();
  110668. var lights = this._babylonScene.lights;
  110669. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  110670. var light = lights_1[_i];
  110671. var generator = light.getShadowGenerator();
  110672. if (generator) {
  110673. promises.push(generator.forceCompilationAsync());
  110674. }
  110675. }
  110676. return Promise.all(promises).then(function () { });
  110677. };
  110678. GLTFLoader.prototype._clear = function () {
  110679. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  110680. var request = _a[_i];
  110681. request.abort();
  110682. }
  110683. this._requests.length = 0;
  110684. if (this._gltf && this._gltf.images) {
  110685. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  110686. var image = _c[_b];
  110687. if (image._objectURL) {
  110688. image._objectURL.then(function (value) {
  110689. URL.revokeObjectURL(value);
  110690. });
  110691. image._objectURL = undefined;
  110692. }
  110693. }
  110694. }
  110695. delete this._gltf;
  110696. delete this._babylonScene;
  110697. this._completePromises.length = 0;
  110698. for (var name_4 in this._extensions) {
  110699. this._extensions[name_4].dispose();
  110700. }
  110701. this._extensions = {};
  110702. delete this._rootBabylonMesh;
  110703. delete this._progressCallback;
  110704. this.onMeshLoadedObservable.clear();
  110705. this.onTextureLoadedObservable.clear();
  110706. this.onMaterialLoadedObservable.clear();
  110707. };
  110708. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  110709. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  110710. var name_5 = _a[_i];
  110711. var extension = this._extensions[name_5];
  110712. if (extension.enabled) {
  110713. var promise = actionAsync(extension);
  110714. if (promise) {
  110715. return promise;
  110716. }
  110717. }
  110718. }
  110719. return null;
  110720. };
  110721. GLTFLoader._Names = new Array();
  110722. GLTFLoader._Factories = {};
  110723. return GLTFLoader;
  110724. }());
  110725. GLTF2.GLTFLoader = GLTFLoader;
  110726. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  110727. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110728. })(BABYLON || (BABYLON = {}));
  110729. //# sourceMappingURL=babylon.glTFLoader.js.map
  110730. "use strict";
  110731. var BABYLON;
  110732. (function (BABYLON) {
  110733. var GLTF2;
  110734. (function (GLTF2) {
  110735. var GLTFLoaderExtension = /** @class */ (function () {
  110736. function GLTFLoaderExtension(loader) {
  110737. this.enabled = true;
  110738. this._loader = loader;
  110739. }
  110740. GLTFLoaderExtension.prototype.dispose = function () {
  110741. delete this._loader;
  110742. };
  110743. // #region Overridable Methods
  110744. /** Override this method to modify the default behavior for loading scenes. */
  110745. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  110746. /** Override this method to modify the default behavior for loading nodes. */
  110747. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  110748. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  110749. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  110750. /** Override this method to modify the default behavior for loading materials. */
  110751. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) { return null; };
  110752. /** Override this method to modify the default behavior for loading uris. */
  110753. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  110754. // #endregion
  110755. /** Helper method called by a loader extension to load an glTF extension. */
  110756. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  110757. if (!property.extensions) {
  110758. return null;
  110759. }
  110760. var extensions = property.extensions;
  110761. var extension = extensions[this.name];
  110762. if (!extension) {
  110763. return null;
  110764. }
  110765. // Clear out the extension before executing the action to avoid recursing into the same property.
  110766. delete extensions[this.name];
  110767. try {
  110768. return actionAsync(context + "/extensions/" + this.name, extension);
  110769. }
  110770. finally {
  110771. // Restore the extension after executing the action.
  110772. extensions[this.name] = extension;
  110773. }
  110774. };
  110775. /** Helper method called by the loader to allow extensions to override loading scenes. */
  110776. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  110777. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  110778. };
  110779. /** Helper method called by the loader to allow extensions to override loading nodes. */
  110780. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  110781. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  110782. };
  110783. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  110784. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  110785. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  110786. };
  110787. /** Helper method called by the loader to allow extensions to override loading materials. */
  110788. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, babylonDrawMode, assign) {
  110789. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); });
  110790. };
  110791. /** Helper method called by the loader to allow extensions to override loading uris. */
  110792. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  110793. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  110794. };
  110795. return GLTFLoaderExtension;
  110796. }());
  110797. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  110798. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110799. })(BABYLON || (BABYLON = {}));
  110800. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  110801. "use strict";
  110802. var BABYLON;
  110803. (function (BABYLON) {
  110804. var GLTF2;
  110805. (function (GLTF2) {
  110806. var Extensions;
  110807. (function (Extensions) {
  110808. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  110809. var NAME = "MSFT_lod";
  110810. var MSFT_lod = /** @class */ (function (_super) {
  110811. __extends(MSFT_lod, _super);
  110812. function MSFT_lod() {
  110813. var _this = _super !== null && _super.apply(this, arguments) || this;
  110814. _this.name = NAME;
  110815. /**
  110816. * Maximum number of LODs to load, starting from the lowest LOD.
  110817. */
  110818. _this.maxLODsToLoad = Number.MAX_VALUE;
  110819. _this._loadingNodeLOD = null;
  110820. _this._loadNodeSignals = {};
  110821. _this._loadingMaterialLOD = null;
  110822. _this._loadMaterialSignals = {};
  110823. return _this;
  110824. }
  110825. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  110826. var _this = this;
  110827. return this._loadExtensionAsync(context, node, function (context, extension) {
  110828. var firstPromise;
  110829. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  110830. var _loop_1 = function (indexLOD) {
  110831. var nodeLOD = nodeLODs[indexLOD];
  110832. if (indexLOD !== 0) {
  110833. _this._loadingNodeLOD = nodeLOD;
  110834. if (!_this._loadNodeSignals[nodeLOD._index]) {
  110835. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  110836. }
  110837. }
  110838. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  110839. if (indexLOD !== 0) {
  110840. var previousNodeLOD = nodeLODs[indexLOD - 1];
  110841. if (previousNodeLOD._babylonMesh) {
  110842. previousNodeLOD._babylonMesh.dispose();
  110843. delete previousNodeLOD._babylonMesh;
  110844. }
  110845. }
  110846. if (indexLOD !== nodeLODs.length - 1) {
  110847. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  110848. if (_this._loadNodeSignals[nodeIndex]) {
  110849. _this._loadNodeSignals[nodeIndex].resolve();
  110850. delete _this._loadNodeSignals[nodeIndex];
  110851. }
  110852. }
  110853. });
  110854. if (indexLOD === 0) {
  110855. firstPromise = promise;
  110856. }
  110857. else {
  110858. _this._loader._completePromises.push(promise);
  110859. _this._loadingNodeLOD = null;
  110860. }
  110861. };
  110862. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  110863. _loop_1(indexLOD);
  110864. }
  110865. return firstPromise;
  110866. });
  110867. };
  110868. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  110869. var _this = this;
  110870. // Don't load material LODs if already loading a node LOD.
  110871. if (this._loadingNodeLOD) {
  110872. return null;
  110873. }
  110874. return this._loadExtensionAsync(context, material, function (context, extension) {
  110875. var firstPromise;
  110876. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  110877. var _loop_2 = function (indexLOD) {
  110878. var materialLOD = materialLODs[indexLOD];
  110879. if (indexLOD !== 0) {
  110880. _this._loadingMaterialLOD = materialLOD;
  110881. if (!_this._loadMaterialSignals[materialLOD._index]) {
  110882. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  110883. }
  110884. }
  110885. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  110886. if (indexLOD !== 0) {
  110887. var babylonDataLOD = materialLOD._babylonData;
  110888. assign(babylonDataLOD[babylonDrawMode].material);
  110889. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  110890. if (previousBabylonDataLOD[babylonDrawMode]) {
  110891. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  110892. delete previousBabylonDataLOD[babylonDrawMode];
  110893. }
  110894. }
  110895. if (indexLOD !== materialLODs.length - 1) {
  110896. var materialIndex = materialLODs[indexLOD + 1]._index;
  110897. if (_this._loadMaterialSignals[materialIndex]) {
  110898. _this._loadMaterialSignals[materialIndex].resolve();
  110899. delete _this._loadMaterialSignals[materialIndex];
  110900. }
  110901. }
  110902. });
  110903. if (indexLOD === 0) {
  110904. firstPromise = promise;
  110905. }
  110906. else {
  110907. _this._loader._completePromises.push(promise);
  110908. _this._loadingMaterialLOD = null;
  110909. }
  110910. };
  110911. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  110912. _loop_2(indexLOD);
  110913. }
  110914. return firstPromise;
  110915. });
  110916. };
  110917. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  110918. var _this = this;
  110919. // Defer the loading of uris if loading a material or node LOD.
  110920. if (this._loadingMaterialLOD) {
  110921. var index = this._loadingMaterialLOD._index;
  110922. return this._loadMaterialSignals[index].promise.then(function () {
  110923. return _this._loader._loadUriAsync(context, uri);
  110924. });
  110925. }
  110926. else if (this._loadingNodeLOD) {
  110927. var index = this._loadingNodeLOD._index;
  110928. return this._loadNodeSignals[index].promise.then(function () {
  110929. return _this._loader._loadUriAsync(context, uri);
  110930. });
  110931. }
  110932. return null;
  110933. };
  110934. /**
  110935. * Gets an array of LOD properties from lowest to highest.
  110936. */
  110937. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  110938. if (this.maxLODsToLoad <= 0) {
  110939. throw new Error("maxLODsToLoad must be greater than zero");
  110940. }
  110941. var properties = new Array();
  110942. for (var i = ids.length - 1; i >= 0; i--) {
  110943. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  110944. if (properties.length === this.maxLODsToLoad) {
  110945. return properties;
  110946. }
  110947. }
  110948. properties.push(property);
  110949. return properties;
  110950. };
  110951. return MSFT_lod;
  110952. }(GLTF2.GLTFLoaderExtension));
  110953. Extensions.MSFT_lod = MSFT_lod;
  110954. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  110955. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110956. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110957. })(BABYLON || (BABYLON = {}));
  110958. //# sourceMappingURL=MSFT_lod.js.map
  110959. "use strict";
  110960. var BABYLON;
  110961. (function (BABYLON) {
  110962. var GLTF2;
  110963. (function (GLTF2) {
  110964. var Extensions;
  110965. (function (Extensions) {
  110966. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  110967. var NAME = "KHR_draco_mesh_compression";
  110968. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  110969. __extends(KHR_draco_mesh_compression, _super);
  110970. function KHR_draco_mesh_compression(loader) {
  110971. var _this = _super.call(this, loader) || this;
  110972. _this.name = NAME;
  110973. _this._dracoCompression = null;
  110974. // Disable extension if decoder is not available.
  110975. if (!BABYLON.DracoCompression.DecoderUrl) {
  110976. _this.enabled = false;
  110977. }
  110978. return _this;
  110979. }
  110980. KHR_draco_mesh_compression.prototype.dispose = function () {
  110981. if (this._dracoCompression) {
  110982. this._dracoCompression.dispose();
  110983. }
  110984. _super.prototype.dispose.call(this);
  110985. };
  110986. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  110987. var _this = this;
  110988. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  110989. if (primitive.mode != undefined) {
  110990. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  110991. primitive.mode !== 4 /* TRIANGLES */) {
  110992. throw new Error(context + ": Unsupported mode " + primitive.mode);
  110993. }
  110994. // TODO: handle triangle strips
  110995. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  110996. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  110997. }
  110998. }
  110999. var attributes = {};
  111000. var loadAttribute = function (name, kind) {
  111001. var uniqueId = extension.attributes[name];
  111002. if (uniqueId == undefined) {
  111003. return;
  111004. }
  111005. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  111006. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  111007. babylonMesh._delayInfo.push(kind);
  111008. }
  111009. attributes[kind] = uniqueId;
  111010. };
  111011. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  111012. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  111013. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  111014. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  111015. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  111016. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  111017. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  111018. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  111019. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  111020. return _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  111021. try {
  111022. if (!_this._dracoCompression) {
  111023. _this._dracoCompression = new BABYLON.DracoCompression();
  111024. }
  111025. return _this._dracoCompression.decodeMeshAsync(data, attributes);
  111026. }
  111027. catch (e) {
  111028. throw new Error(context + ": " + e.message);
  111029. }
  111030. });
  111031. });
  111032. };
  111033. return KHR_draco_mesh_compression;
  111034. }(GLTF2.GLTFLoaderExtension));
  111035. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  111036. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  111037. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  111038. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  111039. })(BABYLON || (BABYLON = {}));
  111040. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  111041. "use strict";
  111042. var BABYLON;
  111043. (function (BABYLON) {
  111044. var GLTF2;
  111045. (function (GLTF2) {
  111046. var Extensions;
  111047. (function (Extensions) {
  111048. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  111049. var NAME = "KHR_materials_pbrSpecularGlossiness";
  111050. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  111051. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  111052. function KHR_materials_pbrSpecularGlossiness() {
  111053. var _this = _super !== null && _super.apply(this, arguments) || this;
  111054. _this.name = NAME;
  111055. return _this;
  111056. }
  111057. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  111058. var _this = this;
  111059. return this._loadExtensionAsync(context, material, function (context, extension) {
  111060. material._babylonData = material._babylonData || {};
  111061. var babylonData = material._babylonData[babylonDrawMode];
  111062. if (!babylonData) {
  111063. var promises = new Array();
  111064. var name_1 = material.name || "materialSG_" + material._index;
  111065. var babylonMaterial = _this._loader._createMaterial(BABYLON.PBRMaterial, name_1, babylonDrawMode);
  111066. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  111067. promises.push(_this._loadSpecularGlossinessPropertiesAsync(context, material, extension, babylonMaterial));
  111068. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  111069. babylonData = {
  111070. material: babylonMaterial,
  111071. meshes: [],
  111072. loaded: Promise.all(promises).then(function () { })
  111073. };
  111074. material._babylonData[babylonDrawMode] = babylonData;
  111075. }
  111076. babylonData.meshes.push(babylonMesh);
  111077. assign(babylonData.material);
  111078. return babylonData.loaded;
  111079. });
  111080. };
  111081. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  111082. var promises = new Array();
  111083. if (properties.diffuseFactor) {
  111084. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  111085. babylonMaterial.alpha = properties.diffuseFactor[3];
  111086. }
  111087. else {
  111088. babylonMaterial.albedoColor = BABYLON.Color3.White();
  111089. }
  111090. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  111091. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  111092. if (properties.diffuseTexture) {
  111093. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  111094. babylonMaterial.albedoTexture = texture;
  111095. }));
  111096. }
  111097. if (properties.specularGlossinessTexture) {
  111098. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  111099. babylonMaterial.reflectivityTexture = texture;
  111100. }));
  111101. babylonMaterial.reflectivityTexture.hasAlpha = true;
  111102. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  111103. }
  111104. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  111105. return Promise.all(promises).then(function () { });
  111106. };
  111107. return KHR_materials_pbrSpecularGlossiness;
  111108. }(GLTF2.GLTFLoaderExtension));
  111109. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  111110. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  111111. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  111112. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  111113. })(BABYLON || (BABYLON = {}));
  111114. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  111115. "use strict";
  111116. var BABYLON;
  111117. (function (BABYLON) {
  111118. var GLTF2;
  111119. (function (GLTF2) {
  111120. var Extensions;
  111121. (function (Extensions) {
  111122. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  111123. var NAME = "KHR_lights";
  111124. var LightType;
  111125. (function (LightType) {
  111126. LightType["AMBIENT"] = "ambient";
  111127. LightType["DIRECTIONAL"] = "directional";
  111128. LightType["POINT"] = "point";
  111129. LightType["SPOT"] = "spot";
  111130. })(LightType || (LightType = {}));
  111131. var KHR_lights = /** @class */ (function (_super) {
  111132. __extends(KHR_lights, _super);
  111133. function KHR_lights() {
  111134. var _this = _super !== null && _super.apply(this, arguments) || this;
  111135. _this.name = NAME;
  111136. return _this;
  111137. }
  111138. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  111139. var _this = this;
  111140. return this._loadExtensionAsync(context, scene, function (context, extension) {
  111141. var promise = _this._loader._loadSceneAsync(context, scene);
  111142. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  111143. if (light.type !== LightType.AMBIENT) {
  111144. throw new Error(context + ": Only ambient lights are allowed on a scene");
  111145. }
  111146. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  111147. return promise;
  111148. });
  111149. };
  111150. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  111151. var _this = this;
  111152. return this._loadExtensionAsync(context, node, function (context, extension) {
  111153. var promise = _this._loader._loadNodeAsync(context, node);
  111154. var babylonLight;
  111155. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  111156. var name = node._babylonMesh.name;
  111157. switch (light.type) {
  111158. case LightType.AMBIENT: {
  111159. throw new Error(context + ": Ambient lights are not allowed on a node");
  111160. }
  111161. case LightType.DIRECTIONAL: {
  111162. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  111163. break;
  111164. }
  111165. case LightType.POINT: {
  111166. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  111167. break;
  111168. }
  111169. case LightType.SPOT: {
  111170. var spotLight = light;
  111171. // TODO: support inner and outer cone angles
  111172. //const innerConeAngle = spotLight.innerConeAngle || 0;
  111173. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  111174. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  111175. break;
  111176. }
  111177. default: {
  111178. throw new Error(context + ": Invalid light type (" + light.type + ")");
  111179. }
  111180. }
  111181. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  111182. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  111183. babylonLight.parent = node._babylonMesh;
  111184. return promise;
  111185. });
  111186. };
  111187. Object.defineProperty(KHR_lights.prototype, "_lights", {
  111188. get: function () {
  111189. var extensions = this._loader._gltf.extensions;
  111190. if (!extensions || !extensions[this.name]) {
  111191. throw new Error("#/extensions: '" + this.name + "' not found");
  111192. }
  111193. var extension = extensions[this.name];
  111194. return extension.lights;
  111195. },
  111196. enumerable: true,
  111197. configurable: true
  111198. });
  111199. return KHR_lights;
  111200. }(GLTF2.GLTFLoaderExtension));
  111201. Extensions.KHR_lights = KHR_lights;
  111202. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  111203. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  111204. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  111205. })(BABYLON || (BABYLON = {}));
  111206. //# sourceMappingURL=KHR_lights.js.map
  111207. return BABYLON;
  111208. });
  111209. /***/ }),
  111210. /* 33 */
  111211. /***/ (function(module, exports, __webpack_require__) {
  111212. /*!
  111213. * PEP v0.4.3 | https://github.com/jquery/PEP
  111214. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  111215. */
  111216. !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);
  111217. // define inherited MouseEvent properties
  111218. // skip bubbles and cancelable since they're set above in initEvent()
  111219. for(var d,e=2;e<m.length;e++)d=m[e],c[d]=b[d]||n[e];c.buttons=b.buttons||0;
  111220. // Spec requires that pointers without pressure specified use 0.5 for down
  111221. // state and 0 for up state.
  111222. var f=0;
  111223. // add x/y properties aliased to clientX/Y
  111224. // define the properties of the PointerEvent interface
  111225. 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(){
  111226. // only activate if this platform does not have pointer events
  111227. 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}})}/**
  111228. * This is the constructor for new PointerEvents.
  111229. *
  111230. * New Pointer Events must be given a type, and an optional dictionary of
  111231. * initialization properties.
  111232. *
  111233. * Due to certain platform requirements, events returned from the constructor
  111234. * identify as MouseEvents.
  111235. *
  111236. * @constructor
  111237. * @param {String} inType The type of the event to create.
  111238. * @param {Object} [inDict] An optional dictionary of initial event properties.
  111239. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  111240. */
  111241. 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},
  111242. // return value, key, map
  111243. forEach:function(a,b){return this.array.forEach(function(c,d){a.call(b,c,d,this)},this)}};var q=[
  111244. // MouseEvent
  111245. "bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget",
  111246. // DOM Level 3
  111247. "buttons",
  111248. // PointerEvent
  111249. "pointerId","width","height","pressure","tiltX","tiltY","pointerType","hwTimestamp","isPrimary",
  111250. // event instance
  111251. "type","target","currentTarget","which","pageX","pageY","timeStamp"],r=[
  111252. // MouseEvent
  111253. !1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,
  111254. // DOM Level 3
  111255. 0,
  111256. // PointerEvent
  111257. 0,0,0,0,0,0,"",0,!1,
  111258. // event instance
  111259. "",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),
  111260. // Scope objects for native events.
  111261. // This exists for ease of testing.
  111262. eventSources:Object.create(null),eventSourceList:[],/**
  111263. * Add a new event source that will generate pointer events.
  111264. *
  111265. * `inSource` must contain an array of event names named `events`, and
  111266. * functions with the names specified in the `events` array.
  111267. * @param {string} name A name for the event source
  111268. * @param {Object} source A new source of platform events.
  111269. */
  111270. 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++)
  111271. // call eventsource register
  111272. b.register.call(b,a)},unregister:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  111273. // call eventsource register
  111274. b.unregister.call(b,a)},contains:/*scope.external.contains || */function(a,b){try{return a.contains(b)}catch(c){
  111275. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  111276. return!1}},
  111277. // EVENTS
  111278. 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)},
  111279. // LISTENER LOGIC
  111280. eventHandler:function(a){
  111281. // This is used to prevent multiple dispatch of pointerevents from
  111282. // platform events. This can happen when two elements in different scopes
  111283. // are set up to create pointer events, which is relevant to Shadow DOM.
  111284. if(!a._handledByPE){var b=a.type,c=this.eventMap&&this.eventMap[b];c&&c(a),a._handledByPE=!0}},
  111285. // set up event listeners
  111286. listen:function(a,b){b.forEach(function(b){this.addEvent(a,b)},this)},
  111287. // remove event listeners
  111288. 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)},
  111289. // EVENT CREATION AND TRACKING
  111290. /**
  111291. * Creates a new Event of type `inType`, based on the information in
  111292. * `inEvent`.
  111293. *
  111294. * @param {string} inType A string representing the type of event to create
  111295. * @param {Event} inEvent A platform event with a target
  111296. * @return {Event} A PointerEvent of type `inType`
  111297. */
  111298. makeEvent:function(b,c){
  111299. // relatedTarget must be null if pointer is captured
  111300. 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},
  111301. // make and dispatch an event in one call
  111302. fireEvent:function(a,b){var c=this.makeEvent(a,b);return this.dispatchEvent(c)},/**
  111303. * Returns a snapshot of inEvent, with writable properties.
  111304. *
  111305. * @param {Event} inEvent An event that contains properties to copy.
  111306. * @return {Object} An object containing shallow copies of `inEvent`'s
  111307. * properties.
  111308. */
  111309. 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],
  111310. // Work around SVGInstanceElement shadow tree
  111311. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  111312. // This is the behavior implemented by Firefox.
  111313. !t||"target"!==b&&"relatedTarget"!==b||c[b]instanceof SVGElementInstance&&(c[b]=c[b].correspondingUseElement);
  111314. // keep the semantics of preventDefault
  111315. 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){
  111316. // Order of conditions due to document.contains() missing in IE.
  111317. for(var d=a.target,e=[];d!==document&&!d.contains(a.relatedTarget);)
  111318. // Touch: Do not propagate if node is detached.
  111319. 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)}},/**
  111320. * Dispatches the event to its target.
  111321. *
  111322. * @param {Event} inEvent The event to be dispatched.
  111323. * @return {Boolean} True if an event handler returns true, false otherwise.
  111324. */
  111325. 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(
  111326. // is element a shadow host?
  111327. e=this.targetingShadow(f);e;){if(
  111328. // find the the element inside the shadow root
  111329. d=e.elementFromPoint(b,c)){
  111330. // shadowed element may contain a shadow root
  111331. var g=this.targetingShadow(d);return this.searchRoot(g,b,c)||d}
  111332. // check for older shadows
  111333. e=this.olderShadow(e)}
  111334. // light dom element is the target
  111335. return f}},owner:function(a){
  111336. // walk up until you hit the shadow root or document
  111337. for(var b=a;b.parentNode;)b=b.parentNode;
  111338. // the owner element is expected to be a Document or ShadowRoot
  111339. 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);
  111340. // if x, y is not in this root, fall back to document search
  111341. 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){
  111342. // Only watch scopes that can target find, as these are top-level.
  111343. // Otherwise we can see duplicate additions and removals that add noise.
  111344. //
  111345. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  111346. // a removal without an insertion when a node is redistributed among
  111347. // shadows. Since it all ends up correct in the document, watching only
  111348. // the document will yield the correct mutations to watch.
  111349. 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))},
  111350. // register all touch-action = none nodes on document load
  111351. 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){
  111352. // find children with touch-action
  111353. var b=x(a,this.findElements,this);
  111354. // flatten the list
  111355. // make sure the added nodes are accounted for
  111356. 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){}
  111357. // handler block for native mouse events
  111358. 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:[],
  111359. // collide with the global mouse listener
  111360. 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++){
  111361. // simulated mouse events will be swallowed near a primary touchend
  111362. 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);
  111363. // Update buttons state after possible out-of-document mouseup.
  111364. 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];
  111365. // Produces wrong state of buttons in Browsers without `buttons` support
  111366. // when a mouse button that was pressed outside the document is released
  111367. // inside and other buttons are still pressed down.
  111368. c.buttons=b?b.buttons&~d:0,a.buttons=c.buttons}H.set(this.POINTER_ID,a),
  111369. // Support: Firefox <=44 only
  111370. // FF Ubuntu includes the lifted button in the `buttons` property on
  111371. // mouseup.
  111372. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  111373. 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),
  111374. // set touch-action on shadows as well
  111375. 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),
  111376. // remove touch-action from shadow
  111377. 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);
  111378. // simply update scrollType if listeners are already established
  111379. 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){
  111380. // set primary touch if there no pointers, or the only pointer is the mouse
  111381. (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,
  111382. // forward modifier keys
  111383. c.altKey=b.altKey,c.ctrlKey=b.ctrlKey,c.metaKey=b.metaKey,c.shiftKey=b.shiftKey;
  111384. // forward touch preventDefaults
  111385. 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))},
  111386. // For single axis scrollers, determines whether the element should emit
  111387. // pointer events or behave as a scroller
  111388. shouldScroll:function(a){if(this.firstXY){var b,c=a.currentTarget._scrollType;if("none"===c)
  111389. // this element is a touch-action: none, should never scroll
  111390. b=!1;else if("XY"===c)
  111391. // this element should always scroll
  111392. 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]);
  111393. // if delta in the scroll axis > delta other axis, scroll instead of
  111394. // making events
  111395. 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},
  111396. // In some instances, a touchstart can happen without a touchend. This
  111397. // leaves the pointermap in a broken state.
  111398. // Therefore, on every touchstart, we remove the touches that did not fire a
  111399. // touchend event.
  111400. // To keep state globally consistent, we fire a
  111401. // pointercancel for this "abandoned" touch
  111402. vacuumTouches:function(a){var b=a.touches;
  111403. // pointermap.size should be < tl.length here, as the touchstart has not
  111404. // been processed yet.
  111405. if(R.size>=b.length){var c=[];R.forEach(function(a,d){
  111406. // Never remove pointerId == 1, which is mouse.
  111407. // Touch identifiers are 2 smaller than their pointerId, which is the
  111408. // index in pointermap.
  111409. 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);
  111410. // a finger drifted off the screen, ignore it
  111411. if(c){var d=c.out,e=c.outTarget;u.move(b),d&&e!==b.target&&(d.relatedTarget=b.target,b.relatedTarget=e,
  111412. // recover from retargeting by shadow
  111413. d.target=e,b.target?(u.leaveOut(d),u.enterOver(b)):(
  111414. // clean up case when finger leaves the screen
  111415. 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)},
  111416. // prevent synth mouse events from creating pointer events
  111417. dedupSynthMouse:function(a){var b=N.lastTouches,c=a.changedTouches[0];
  111418. // only the primary finger will synth mouse events
  111419. if(this.isPrimaryTouch(c)){
  111420. // remember x/y of last touch
  111421. 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});
  111422. /***/ }),
  111423. /* 34 */
  111424. /***/ (function(module, exports, __webpack_require__) {
  111425. "use strict";
  111426. Object.defineProperty(exports, "__esModule", { value: true });
  111427. var defaultViewer_1 = __webpack_require__(4);
  111428. var mappers_1 = __webpack_require__(1);
  111429. function InitTags(selector) {
  111430. if (selector === void 0) { selector = 'babylon'; }
  111431. var elements = document.querySelectorAll(selector);
  111432. for (var i = 0; i < elements.length; ++i) {
  111433. var element = elements.item(i);
  111434. var configMapper = mappers_1.mapperManager.getMapper('dom');
  111435. var config = configMapper.map(element);
  111436. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  111437. }
  111438. }
  111439. exports.InitTags = InitTags;
  111440. /***/ })
  111441. /******/ ]);
  111442. return BabylonViewer;
  111443. });